Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b6b509811d | ||
|
|
87bdda3cfa | ||
|
|
291727a27d | ||
|
|
e66b786229 | ||
|
|
e05e1cdf76 | ||
|
|
f92cc7a159 | ||
|
|
ebd2181946 | ||
|
|
3efa1a03f2 | ||
|
|
115e85b47d | ||
|
|
31a3314ebd | ||
|
|
bf33025ea9 | ||
|
|
1a33ee3fc4 | ||
|
|
4722885910 | ||
|
|
117fcb6936 |
@@ -1,6 +1,6 @@
|
||||
repos:
|
||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||
rev: v0.0.151
|
||||
rev: v0.0.154
|
||||
hooks:
|
||||
- id: ruff
|
||||
|
||||
|
||||
6
Cargo.lock
generated
6
Cargo.lock
generated
@@ -703,7 +703,7 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
|
||||
|
||||
[[package]]
|
||||
name = "flake8-to-ruff"
|
||||
version = "0.0.151-dev.0"
|
||||
version = "0.0.154-dev.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap 4.0.22",
|
||||
@@ -1837,7 +1837,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ruff"
|
||||
version = "0.0.151"
|
||||
version = "0.0.154"
|
||||
dependencies = [
|
||||
"annotate-snippets 0.9.1",
|
||||
"anyhow",
|
||||
@@ -1889,7 +1889,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ruff_dev"
|
||||
version = "0.0.151"
|
||||
version = "0.0.154"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap 4.0.22",
|
||||
|
||||
@@ -6,7 +6,7 @@ members = [
|
||||
|
||||
[package]
|
||||
name = "ruff"
|
||||
version = "0.0.151"
|
||||
version = "0.0.154"
|
||||
edition = "2021"
|
||||
rust-version = "1.65.0"
|
||||
|
||||
|
||||
48
LICENSE
48
LICENSE
@@ -363,6 +363,31 @@ are:
|
||||
THE SOFTWARE.
|
||||
"""
|
||||
|
||||
- flake8-return, licensed as follows:
|
||||
"""
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Afonasev Evgeniy
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
"""
|
||||
|
||||
- isort, licensed as follows:
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
@@ -471,6 +496,29 @@ are:
|
||||
SOFTWARE.
|
||||
"""
|
||||
|
||||
- pygrep-hooks, licensed as follows:
|
||||
"""
|
||||
Copyright (c) 2018 Anthony Sottile
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
"""
|
||||
|
||||
- pyupgrade, licensed as follows:
|
||||
"""
|
||||
Copyright (c) 2017 Anthony Sottile
|
||||
|
||||
203
README.md
203
README.md
@@ -71,24 +71,27 @@ of [Conda](https://docs.conda.io/en/latest/):
|
||||
1. [Supported Rules](#supported-rules)
|
||||
1. [Pyflakes (F)](#pyflakes)
|
||||
1. [pycodestyle (E, W)](#pycodestyle)
|
||||
1. [mccabe (C90)](#mccabe)
|
||||
1. [isort (I)](#isort)
|
||||
1. [pydocstyle (D)](#pydocstyle)
|
||||
1. [pyupgrade (U)](#pyupgrade)
|
||||
1. [pep8-naming (N)](#pep8-naming)
|
||||
1. [eradicate (ERA)](#eradicate)
|
||||
1. [flake8-2020 (YTT)](#flake8-2020)
|
||||
1. [flake8-annotations (ANN)](#flake8-annotations)
|
||||
1. [flake8-bandit (S)](#flake8-bandit)
|
||||
1. [flake8-comprehensions (C)](#flake8-comprehensions)
|
||||
1. [flake8-blind-except (BLE)](#flake8-blind-except)
|
||||
1. [flake8-boolean-trap (FBT)](#flake8-boolean-trap)
|
||||
1. [flake8-bugbear (B)](#flake8-bugbear)
|
||||
1. [flake8-builtins (A)](#flake8-builtins)
|
||||
1. [flake8-debugger (T)](#flake8-debugger)
|
||||
1. [flake8-tidy-imports (I25)](#flake8-tidy-imports)
|
||||
1. [flake8-print (T)](#flake8-print)
|
||||
1. [flake8-comprehensions (C4)](#flake8-comprehensions)
|
||||
1. [flake8-debugger (T10)](#flake8-debugger)
|
||||
1. [flake8-print (T20)](#flake8-print)
|
||||
1. [flake8-quotes (Q)](#flake8-quotes)
|
||||
1. [flake8-annotations (ANN)](#flake8-annotations)
|
||||
1. [flake8-2020 (YTT)](#flake8-2020)
|
||||
1. [flake8-blind-except (BLE)](#flake8-blind-except)
|
||||
1. [mccabe (C90)](#mccabe)
|
||||
1. [flake8-return (ET)](#flake8-return)
|
||||
1. [flake8-tidy-imports (I25)](#flake8-tidy-imports)
|
||||
1. [eradicate (ERA)](#eradicate)
|
||||
1. [pygrep-hooks (PGH)](#pygrep-hooks)
|
||||
1. [Pylint (PL)](#pylint)
|
||||
1. [Ruff-specific rules (RUF)](#ruff-specific-rules)
|
||||
1. [Meta rules (M)](#meta-rules)
|
||||
1. [Editor Integrations](#editor-integrations)
|
||||
@@ -143,7 +146,7 @@ Ruff also works with [pre-commit](https://pre-commit.com):
|
||||
```yaml
|
||||
repos:
|
||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||
rev: v0.0.151
|
||||
rev: v0.0.154
|
||||
hooks:
|
||||
- id: ruff
|
||||
```
|
||||
@@ -314,10 +317,10 @@ Options:
|
||||
|
||||
### Ignoring errors
|
||||
|
||||
To omit a lint check entirely, add it to the "ignore" list via `--ignore` or `--extend-ignore`,
|
||||
either on the command-line or in your `project.toml` file.
|
||||
To omit a lint check entirely, add it to the "ignore" list via [`ignore`](#ignore) or
|
||||
[`extend-ignore`](#extend-ignore), either on the command-line or in your `project.toml` file.
|
||||
|
||||
To ignore an error in-line, Ruff uses a `noqa` system similar to [Flake8](https://flake8.pycqa.org/en/3.1.1/user/ignoring-errors.html).
|
||||
To ignore an error inline, Ruff uses a `noqa` system similar to [Flake8](https://flake8.pycqa.org/en/3.1.1/user/ignoring-errors.html).
|
||||
To ignore an individual error, add `# noqa: {code}` to the end of the line, like so:
|
||||
|
||||
```python
|
||||
@@ -332,7 +335,7 @@ x = 1 # noqa
|
||||
```
|
||||
|
||||
Note that, for multi-line strings, the `noqa` directive should come at the end of the string, and
|
||||
will apply to the entire body, like so:
|
||||
will apply to the entire string, like so:
|
||||
|
||||
```python
|
||||
"""Lorem ipsum dolor sit amet.
|
||||
@@ -341,6 +344,15 @@ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor i
|
||||
""" # noqa: E501
|
||||
```
|
||||
|
||||
To ignore all errors across an entire file, Ruff supports Flake8's `# flake8: noqa` directive (or,
|
||||
equivalently, `# ruff: noqa`). Adding either of those directives to any part of a file will disable
|
||||
error reporting for the entire file.
|
||||
|
||||
For targeted exclusions across entire files (e.g., "Ignore all F841 violations in
|
||||
`/path/to/file.py`"), see the [`per-file-ignores`](#per-file-ignores) configuration setting.
|
||||
|
||||
### Automating `noqa` Directives
|
||||
|
||||
Ruff supports several workflows to aid in `noqa` management.
|
||||
|
||||
First, Ruff provides a special error code, `M001`, to enforce that your `noqa` directives are
|
||||
@@ -439,6 +451,14 @@ For more, see [pycodestyle](https://pypi.org/project/pycodestyle/2.9.1/) on PyPI
|
||||
| W292 | NoNewLineAtEndOfFile | No newline at end of file | |
|
||||
| W605 | InvalidEscapeSequence | Invalid escape sequence: '\c' | |
|
||||
|
||||
### mccabe
|
||||
|
||||
For more, see [mccabe](https://pypi.org/project/mccabe/0.7.0/) on PyPI.
|
||||
|
||||
| Code | Name | Message | Fix |
|
||||
| ---- | ---- | ------- | --- |
|
||||
| C901 | FunctionIsTooComplex | `...` is too complex (10) | |
|
||||
|
||||
### isort
|
||||
|
||||
For more, see [isort](https://pypi.org/project/isort/5.10.1/) on PyPI.
|
||||
@@ -541,13 +561,40 @@ For more, see [pep8-naming](https://pypi.org/project/pep8-naming/0.13.2/) on PyP
|
||||
| N817 | CamelcaseImportedAsAcronym | Camelcase `...` imported as acronym `...` | |
|
||||
| N818 | ErrorSuffixOnExceptionName | Exception name `...` should be named with an Error suffix | |
|
||||
|
||||
### eradicate
|
||||
### flake8-2020
|
||||
|
||||
For more, see [eradicate](https://pypi.org/project/eradicate/2.1.0/) on PyPI.
|
||||
For more, see [flake8-2020](https://pypi.org/project/flake8-2020/1.7.0/) on PyPI.
|
||||
|
||||
| Code | Name | Message | Fix |
|
||||
| ---- | ---- | ------- | --- |
|
||||
| ERA001 | CommentedOutCode | Found commented-out code | 🛠 |
|
||||
| YTT101 | SysVersionSlice3Referenced | `sys.version[:3]` referenced (python3.10), use `sys.version_info` | |
|
||||
| YTT102 | SysVersion2Referenced | `sys.version[2]` referenced (python3.10), use `sys.version_info` | |
|
||||
| YTT103 | SysVersionCmpStr3 | `sys.version` compared to string (python3.10), use `sys.version_info` | |
|
||||
| YTT201 | SysVersionInfo0Eq3Referenced | `sys.version_info[0] == 3` referenced (python4), use `>=` | |
|
||||
| YTT202 | SixPY3Referenced | `six.PY3` referenced (python4), use `not six.PY2` | |
|
||||
| YTT203 | SysVersionInfo1CmpInt | `sys.version_info[1]` compared to integer (python4), compare `sys.version_info` to tuple | |
|
||||
| YTT204 | SysVersionInfoMinorCmpInt | `sys.version_info.minor` compared to integer (python4), compare `sys.version_info` to tuple | |
|
||||
| YTT301 | SysVersion0Referenced | `sys.version[0]` referenced (python10), use `sys.version_info` | |
|
||||
| YTT302 | SysVersionCmpStr10 | `sys.version` compared to string (python10), use `sys.version_info` | |
|
||||
| YTT303 | SysVersionSlice1Referenced | `sys.version[:1]` referenced (python10), use `sys.version_info` | |
|
||||
|
||||
### flake8-annotations
|
||||
|
||||
For more, see [flake8-annotations](https://pypi.org/project/flake8-annotations/2.9.1/) on PyPI.
|
||||
|
||||
| Code | Name | Message | Fix |
|
||||
| ---- | ---- | ------- | --- |
|
||||
| ANN001 | MissingTypeFunctionArgument | Missing type annotation for function argument `...` | |
|
||||
| ANN002 | MissingTypeArgs | Missing type annotation for `*...` | |
|
||||
| ANN003 | MissingTypeKwargs | Missing type annotation for `**...` | |
|
||||
| ANN101 | MissingTypeSelf | Missing type annotation for `...` in method | |
|
||||
| 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 `...` | |
|
||||
| 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 `...` | |
|
||||
|
||||
### flake8-bandit
|
||||
|
||||
@@ -562,36 +609,13 @@ For more, see [flake8-bandit](https://pypi.org/project/flake8-bandit/4.1.1/) on
|
||||
| S106 | HardcodedPasswordFuncArg | Possible hardcoded password: `"..."` | |
|
||||
| S107 | HardcodedPasswordDefault | Possible hardcoded password: `"..."` | |
|
||||
|
||||
### flake8-comprehensions
|
||||
### flake8-blind-except
|
||||
|
||||
For more, see [flake8-comprehensions](https://pypi.org/project/flake8-comprehensions/3.10.1/) on PyPI.
|
||||
For more, see [flake8-blind-except](https://pypi.org/project/flake8-blind-except/0.2.1/) on PyPI.
|
||||
|
||||
| Code | Name | Message | Fix |
|
||||
| ---- | ---- | ------- | --- |
|
||||
| C400 | UnnecessaryGeneratorList | Unnecessary generator (rewrite as a `list` comprehension) | 🛠 |
|
||||
| C401 | UnnecessaryGeneratorSet | Unnecessary generator (rewrite as a `set` comprehension) | 🛠 |
|
||||
| C402 | UnnecessaryGeneratorDict | Unnecessary generator (rewrite as a `dict` comprehension) | 🛠 |
|
||||
| C403 | UnnecessaryListComprehensionSet | Unnecessary `list` comprehension (rewrite as a `set` comprehension) | 🛠 |
|
||||
| C404 | UnnecessaryListComprehensionDict | Unnecessary `list` comprehension (rewrite as a `dict` comprehension) | 🛠 |
|
||||
| C405 | UnnecessaryLiteralSet | Unnecessary `(list\|tuple)` literal (rewrite as a `set` literal) | 🛠 |
|
||||
| C406 | UnnecessaryLiteralDict | Unnecessary `(list\|tuple)` literal (rewrite as a `dict` literal) | 🛠 |
|
||||
| C408 | UnnecessaryCollectionCall | Unnecessary `(dict\|list\|tuple)` call (rewrite as a literal) | 🛠 |
|
||||
| C409 | UnnecessaryLiteralWithinTupleCall | Unnecessary `(list\|tuple)` literal passed to `tuple()` (remove the outer call to `tuple()`) | 🛠 |
|
||||
| C410 | UnnecessaryLiteralWithinListCall | Unnecessary `(list\|tuple)` literal passed to `list()` (rewrite as a `list` literal) | 🛠 |
|
||||
| C411 | UnnecessaryListCall | Unnecessary `list` call (remove the outer call to `list()`) | 🛠 |
|
||||
| C413 | UnnecessaryCallAroundSorted | Unnecessary `(list\|reversed)` call around `sorted()` | |
|
||||
| C414 | UnnecessaryDoubleCastOrProcess | Unnecessary `(list\|reversed\|set\|sorted\|tuple)` call within `(list\|set\|sorted\|tuple)()` | |
|
||||
| C415 | UnnecessarySubscriptReversal | Unnecessary subscript reversal of iterable within `(reversed\|set\|sorted)()` | |
|
||||
| C416 | UnnecessaryComprehension | Unnecessary `(list\|set)` comprehension (rewrite using `(list\|set)()`) | 🛠 |
|
||||
| C417 | UnnecessaryMap | Unnecessary `map` usage (rewrite using a `(list\|set\|dict)` comprehension) | |
|
||||
|
||||
### flake8-debugger
|
||||
|
||||
For more, see [flake8-debugger](https://pypi.org/project/flake8-debugger/4.1.2/) on PyPI.
|
||||
|
||||
| Code | Name | Message | Fix |
|
||||
| ---- | ---- | ------- | --- |
|
||||
| T100 | Debugger | Import for `...` found | |
|
||||
| BLE001 | BlindExcept | Blind except Exception: statement | |
|
||||
|
||||
### flake8-boolean-trap
|
||||
|
||||
@@ -647,13 +671,36 @@ For more, see [flake8-builtins](https://pypi.org/project/flake8-builtins/2.0.1/)
|
||||
| A002 | BuiltinArgumentShadowing | Argument `...` is shadowing a python builtin | |
|
||||
| A003 | BuiltinAttributeShadowing | Class attribute `...` is shadowing a python builtin | |
|
||||
|
||||
### flake8-tidy-imports
|
||||
### flake8-comprehensions
|
||||
|
||||
For more, see [flake8-tidy-imports](https://pypi.org/project/flake8-tidy-imports/4.8.0/) on PyPI.
|
||||
For more, see [flake8-comprehensions](https://pypi.org/project/flake8-comprehensions/3.10.1/) on PyPI.
|
||||
|
||||
| Code | Name | Message | Fix |
|
||||
| ---- | ---- | ------- | --- |
|
||||
| I252 | BannedRelativeImport | Relative imports are banned | |
|
||||
| C400 | UnnecessaryGeneratorList | Unnecessary generator (rewrite as a `list` comprehension) | 🛠 |
|
||||
| C401 | UnnecessaryGeneratorSet | Unnecessary generator (rewrite as a `set` comprehension) | 🛠 |
|
||||
| C402 | UnnecessaryGeneratorDict | Unnecessary generator (rewrite as a `dict` comprehension) | 🛠 |
|
||||
| C403 | UnnecessaryListComprehensionSet | Unnecessary `list` comprehension (rewrite as a `set` comprehension) | 🛠 |
|
||||
| C404 | UnnecessaryListComprehensionDict | Unnecessary `list` comprehension (rewrite as a `dict` comprehension) | 🛠 |
|
||||
| C405 | UnnecessaryLiteralSet | Unnecessary `(list\|tuple)` literal (rewrite as a `set` literal) | 🛠 |
|
||||
| C406 | UnnecessaryLiteralDict | Unnecessary `(list\|tuple)` literal (rewrite as a `dict` literal) | 🛠 |
|
||||
| C408 | UnnecessaryCollectionCall | Unnecessary `(dict\|list\|tuple)` call (rewrite as a literal) | 🛠 |
|
||||
| C409 | UnnecessaryLiteralWithinTupleCall | Unnecessary `(list\|tuple)` literal passed to `tuple()` (remove the outer call to `tuple()`) | 🛠 |
|
||||
| C410 | UnnecessaryLiteralWithinListCall | Unnecessary `(list\|tuple)` literal passed to `list()` (rewrite as a `list` literal) | 🛠 |
|
||||
| C411 | UnnecessaryListCall | Unnecessary `list` call (remove the outer call to `list()`) | 🛠 |
|
||||
| C413 | UnnecessaryCallAroundSorted | Unnecessary `(list\|reversed)` call around `sorted()` | |
|
||||
| C414 | UnnecessaryDoubleCastOrProcess | Unnecessary `(list\|reversed\|set\|sorted\|tuple)` call within `(list\|set\|sorted\|tuple)()` | |
|
||||
| C415 | UnnecessarySubscriptReversal | Unnecessary subscript reversal of iterable within `(reversed\|set\|sorted)()` | |
|
||||
| C416 | UnnecessaryComprehension | Unnecessary `(list\|set)` comprehension (rewrite using `(list\|set)()`) | 🛠 |
|
||||
| C417 | UnnecessaryMap | Unnecessary `map` usage (rewrite using a `(list\|set\|dict)` comprehension) | |
|
||||
|
||||
### flake8-debugger
|
||||
|
||||
For more, see [flake8-debugger](https://pypi.org/project/flake8-debugger/4.1.2/) on PyPI.
|
||||
|
||||
| Code | Name | Message | Fix |
|
||||
| ---- | ---- | ------- | --- |
|
||||
| T100 | Debugger | Import for `...` found | |
|
||||
|
||||
### flake8-print
|
||||
|
||||
@@ -675,56 +722,44 @@ For more, see [flake8-quotes](https://pypi.org/project/flake8-quotes/3.3.1/) on
|
||||
| Q002 | BadQuotesDocstring | Single quote docstring found but double quotes preferred | |
|
||||
| Q003 | AvoidQuoteEscape | Change outer quotes to avoid escaping inner quotes | |
|
||||
|
||||
### flake8-annotations
|
||||
### flake8-return
|
||||
|
||||
For more, see [flake8-annotations](https://pypi.org/project/flake8-annotations/2.9.1/) on PyPI.
|
||||
For more, see [flake8-return](https://pypi.org/project/flake8-return/1.2.0/) on PyPI.
|
||||
|
||||
| Code | Name | Message | Fix |
|
||||
| ---- | ---- | ------- | --- |
|
||||
| ANN001 | MissingTypeFunctionArgument | Missing type annotation for function argument `...` | |
|
||||
| ANN002 | MissingTypeArgs | Missing type annotation for `*...` | |
|
||||
| ANN003 | MissingTypeKwargs | Missing type annotation for `**...` | |
|
||||
| ANN101 | MissingTypeSelf | Missing type annotation for `...` in method | |
|
||||
| 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 `...` | |
|
||||
| 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 `...` | |
|
||||
| RET501 | UnnecessaryReturnNone | Do not explicitly `return None` in function if it is the only possible return value | 🛠 |
|
||||
| RET502 | ImplicitReturnValue | Do not implicitly `return None` in function able to return non-`None` value | 🛠 |
|
||||
| RET503 | ImplicitReturn | Missing explicit `return` at the end of function able to return non-`None` value | 🛠 |
|
||||
| RET504 | UnnecessaryAssign | Unnecessary variable assignment before `return` statement | |
|
||||
| RET505 | SuperfluousElseReturn | Unnecessary `else` after `return` statement | |
|
||||
| RET506 | SuperfluousElseRaise | Unnecessary `else` after `raise` statement | |
|
||||
| RET507 | SuperfluousElseContinue | Unnecessary `else` after `continue` statement | |
|
||||
| RET508 | SuperfluousElseBreak | Unnecessary `else` after `break` statement | |
|
||||
|
||||
### flake8-2020
|
||||
### flake8-tidy-imports
|
||||
|
||||
For more, see [flake8-2020](https://pypi.org/project/flake8-2020/1.7.0/) on PyPI.
|
||||
For more, see [flake8-tidy-imports](https://pypi.org/project/flake8-tidy-imports/4.8.0/) on PyPI.
|
||||
|
||||
| Code | Name | Message | Fix |
|
||||
| ---- | ---- | ------- | --- |
|
||||
| YTT101 | SysVersionSlice3Referenced | `sys.version[:3]` referenced (python3.10), use `sys.version_info` | |
|
||||
| YTT102 | SysVersion2Referenced | `sys.version[2]` referenced (python3.10), use `sys.version_info` | |
|
||||
| YTT103 | SysVersionCmpStr3 | `sys.version` compared to string (python3.10), use `sys.version_info` | |
|
||||
| YTT201 | SysVersionInfo0Eq3Referenced | `sys.version_info[0] == 3` referenced (python4), use `>=` | |
|
||||
| YTT202 | SixPY3Referenced | `six.PY3` referenced (python4), use `not six.PY2` | |
|
||||
| YTT203 | SysVersionInfo1CmpInt | `sys.version_info[1]` compared to integer (python4), compare `sys.version_info` to tuple | |
|
||||
| YTT204 | SysVersionInfoMinorCmpInt | `sys.version_info.minor` compared to integer (python4), compare `sys.version_info` to tuple | |
|
||||
| YTT301 | SysVersion0Referenced | `sys.version[0]` referenced (python10), use `sys.version_info` | |
|
||||
| YTT302 | SysVersionCmpStr10 | `sys.version` compared to string (python10), use `sys.version_info` | |
|
||||
| YTT303 | SysVersionSlice1Referenced | `sys.version[:1]` referenced (python10), use `sys.version_info` | |
|
||||
| I252 | BannedRelativeImport | Relative imports are banned | |
|
||||
|
||||
### flake8-blind-except
|
||||
### eradicate
|
||||
|
||||
For more, see [flake8-blind-except](https://pypi.org/project/flake8-blind-except/0.2.1/) on PyPI.
|
||||
For more, see [eradicate](https://pypi.org/project/eradicate/2.1.0/) on PyPI.
|
||||
|
||||
| Code | Name | Message | Fix |
|
||||
| ---- | ---- | ------- | --- |
|
||||
| BLE001 | BlindExcept | Blind except Exception: statement | |
|
||||
| ERA001 | CommentedOutCode | Found commented-out code | 🛠 |
|
||||
|
||||
### mccabe
|
||||
### pygrep-hooks
|
||||
|
||||
For more, see [mccabe](https://pypi.org/project/mccabe/0.7.0/) on PyPI.
|
||||
For more, see [pygrep-hooks](https://github.com/pre-commit/pygrep-hooks) on GitHub.
|
||||
|
||||
| Code | Name | Message | Fix |
|
||||
| ---- | ---- | ------- | --- |
|
||||
| C901 | FunctionIsTooComplex | `...` is too complex (10) | |
|
||||
| PGH001 | NoEval | No builtin `eval()` allowed | |
|
||||
|
||||
### Pylint
|
||||
|
||||
@@ -732,6 +767,9 @@ For more, see [Pylint](https://pypi.org/project/pylint/2.15.7/) on PyPI.
|
||||
|
||||
| Code | Name | Message | Fix |
|
||||
| ---- | ---- | ------- | --- |
|
||||
| PLR1701 | ConsiderMergingIsinstance | Consider merging these isinstance calls: `isinstance(..., (...))` | |
|
||||
| PLC3002 | UnnecessaryDirectLambdaCall | Lambda expression called directly. Execute the expression inline instead. | |
|
||||
| PLR0206 | PropertyWithParameters | Cannot have defined parameters for properties | |
|
||||
| PLE1142 | AwaitOutsideAsync | `await` should be used within an async function | |
|
||||
|
||||
### Ruff-specific rules
|
||||
@@ -896,12 +934,14 @@ natively, including:
|
||||
- [`flake8-eradicate`](https://pypi.org/project/flake8-eradicate/)
|
||||
- [`flake8-print`](https://pypi.org/project/flake8-print/)
|
||||
- [`flake8-quotes`](https://pypi.org/project/flake8-quotes/)
|
||||
- [`flake8-return`](https://pypi.org/project/flake8-return/)
|
||||
- [`flake8-super`](https://pypi.org/project/flake8-super/)
|
||||
- [`flake8-tidy-imports`](https://pypi.org/project/flake8-tidy-imports/) (1/3)
|
||||
- [`mccabe`](https://pypi.org/project/mccabe/)
|
||||
- [`yesqa`](https://github.com/asottile/yesqa)
|
||||
- [`eradicate`](https://pypi.org/project/eradicate/)
|
||||
- [`pyupgrade`](https://pypi.org/project/pyupgrade/) (16/33)
|
||||
- [`pygrep-hooks`](https://github.com/pre-commit/pygrep-hooks) (1/10)
|
||||
- [`autoflake`](https://pypi.org/project/autoflake/) (1/7)
|
||||
|
||||
Beyond the rule set, Ruff suffers from the following limitations vis-à-vis Flake8:
|
||||
@@ -942,12 +982,15 @@ Today, Ruff can be used to replace Flake8 when used with any of the following pl
|
||||
- [`flake8-eradicate`](https://pypi.org/project/flake8-eradicate/)
|
||||
- [`flake8-print`](https://pypi.org/project/flake8-print/)
|
||||
- [`flake8-quotes`](https://pypi.org/project/flake8-quotes/)
|
||||
- [`flake8-return`](https://pypi.org/project/flake8-return/)
|
||||
- [`flake8-super`](https://pypi.org/project/flake8-super/)
|
||||
- [`flake8-tidy-imports`](https://pypi.org/project/flake8-tidy-imports/) (1/3)
|
||||
- [`mccabe`](https://pypi.org/project/mccabe/)
|
||||
|
||||
Ruff can also replace [`isort`](https://pypi.org/project/isort/), [`yesqa`](https://github.com/asottile/yesqa),
|
||||
and a subset of the rules implemented in [`pyupgrade`](https://pypi.org/project/pyupgrade/) (16/33).
|
||||
Ruff can also replace [`isort`](https://pypi.org/project/isort/),
|
||||
[`yesqa`](https://github.com/asottile/yesqa), [`eradicate`](https://pypi.org/project/eradicate/),
|
||||
[`pygrep-hooks`](https://github.com/pre-commit/pygrep-hooks) (1/10), and a subset of the rules
|
||||
implemented in [`pyupgrade`](https://pypi.org/project/pyupgrade/) (16/33).
|
||||
|
||||
If you're looking to use Ruff, but rely on an unsupported Flake8 plugin, free to file an Issue.
|
||||
|
||||
@@ -1261,7 +1304,7 @@ Exclusions are based on globs, and can be either:
|
||||
(to exclude any Python files in `directory`). Note that these paths are relative to the
|
||||
project root (e.g., the directory containing your `pyproject.toml`).
|
||||
|
||||
Note that you'll typically want to use [`extend_exclude`](#extend_exclude) to modify the excluded
|
||||
Note that you'll typically want to use [`extend_exclude`](#extend-exclude) to modify the excluded
|
||||
paths.
|
||||
|
||||
**Default value**: `[".bzr", ".direnv", ".eggs", ".git", ".hg", ".mypy_cache", ".nox", ".pants.d", ".ruff_cache", ".svn", ".tox", ".venv", "__pypackages__", "_build", "buck-out", "build", "dist", "node_modules", "venv"]`
|
||||
|
||||
11
create_plugin.sh
Executable file
11
create_plugin.sh
Executable file
@@ -0,0 +1,11 @@
|
||||
set -euxo pipefail
|
||||
|
||||
NAME=$1
|
||||
|
||||
mkdir -p src/$1
|
||||
mkdir -p resources/test/fixtures/$1
|
||||
touch src/$1/mod.rs
|
||||
|
||||
sed -i "" "s/mod flake8_print;/mod flake8_print; mod flake8_return;/g" src/lib.rs
|
||||
sed -i "" "s|// flake8-print|// flake8-return\n// flake8-print|g" src/checks.rs
|
||||
|
||||
4
flake8_to_ruff/Cargo.lock
generated
4
flake8_to_ruff/Cargo.lock
generated
@@ -771,7 +771,7 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
|
||||
|
||||
[[package]]
|
||||
name = "flake8_to_ruff"
|
||||
version = "0.0.151"
|
||||
version = "0.0.154"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -1975,7 +1975,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ruff"
|
||||
version = "0.0.151"
|
||||
version = "0.0.154"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bincode",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "flake8-to-ruff"
|
||||
version = "0.0.151-dev.0"
|
||||
version = "0.0.154-dev.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
|
||||
@@ -17,6 +17,7 @@ pub enum Plugin {
|
||||
Flake8Eradicate,
|
||||
Flake8Print,
|
||||
Flake8Quotes,
|
||||
Flake8Return,
|
||||
Flake8TidyImports,
|
||||
McCabe,
|
||||
PEP8Naming,
|
||||
@@ -39,6 +40,7 @@ impl FromStr for Plugin {
|
||||
"flake8-eradicate" => Ok(Plugin::Flake8BlindExcept),
|
||||
"flake8-print" => Ok(Plugin::Flake8Print),
|
||||
"flake8-quotes" => Ok(Plugin::Flake8Quotes),
|
||||
"flake8-return" => Ok(Plugin::Flake8Return),
|
||||
"flake8-tidy-imports" => Ok(Plugin::Flake8TidyImports),
|
||||
"mccabe" => Ok(Plugin::McCabe),
|
||||
"pep8-naming" => Ok(Plugin::PEP8Naming),
|
||||
@@ -62,6 +64,7 @@ impl Plugin {
|
||||
Plugin::Flake8Eradicate => CheckCodePrefix::ERA,
|
||||
Plugin::Flake8Print => CheckCodePrefix::T2,
|
||||
Plugin::Flake8Quotes => CheckCodePrefix::Q,
|
||||
Plugin::Flake8Return => CheckCodePrefix::RET,
|
||||
Plugin::Flake8TidyImports => CheckCodePrefix::I25,
|
||||
Plugin::McCabe => CheckCodePrefix::C9,
|
||||
Plugin::PEP8Naming => CheckCodePrefix::N,
|
||||
@@ -97,6 +100,7 @@ impl Plugin {
|
||||
Plugin::Flake8Eradicate => vec![CheckCodePrefix::ERA],
|
||||
Plugin::Flake8Print => vec![CheckCodePrefix::T2],
|
||||
Plugin::Flake8Quotes => vec![CheckCodePrefix::Q],
|
||||
Plugin::Flake8Return => vec![CheckCodePrefix::RET],
|
||||
Plugin::Flake8TidyImports => vec![CheckCodePrefix::I25],
|
||||
Plugin::McCabe => vec![CheckCodePrefix::C9],
|
||||
Plugin::PEP8Naming => vec![CheckCodePrefix::N],
|
||||
@@ -389,6 +393,7 @@ pub fn infer_plugins_from_codes(codes: &BTreeSet<CheckCodePrefix>) -> Vec<Plugin
|
||||
Plugin::Flake8Eradicate,
|
||||
Plugin::Flake8Print,
|
||||
Plugin::Flake8Quotes,
|
||||
Plugin::Flake8Return,
|
||||
Plugin::Flake8TidyImports,
|
||||
Plugin::PEP8Naming,
|
||||
Plugin::Pyupgrade,
|
||||
|
||||
4
resources/test/fixtures/flake8_return/RET501.py
vendored
Normal file
4
resources/test/fixtures/flake8_return/RET501.py
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
def x(y):
|
||||
if not y:
|
||||
return
|
||||
return None # error
|
||||
65
resources/test/fixtures/flake8_return/RET502.py
vendored
Normal file
65
resources/test/fixtures/flake8_return/RET502.py
vendored
Normal file
@@ -0,0 +1,65 @@
|
||||
def x(y):
|
||||
if not y:
|
||||
return # error
|
||||
return 1
|
||||
|
||||
|
||||
# without return value
|
||||
def x(y):
|
||||
if not y:
|
||||
return
|
||||
return
|
||||
|
||||
|
||||
def x(y):
|
||||
if y:
|
||||
return
|
||||
print()
|
||||
|
||||
|
||||
# with return value
|
||||
def x(y):
|
||||
if not y:
|
||||
return 1
|
||||
return 2
|
||||
|
||||
|
||||
def x(y):
|
||||
for i in range(10):
|
||||
if i > 100:
|
||||
return i
|
||||
else:
|
||||
return 1
|
||||
|
||||
|
||||
def x(y):
|
||||
try:
|
||||
return 1
|
||||
except:
|
||||
return 2
|
||||
|
||||
|
||||
def x(y):
|
||||
try:
|
||||
return 1
|
||||
finally:
|
||||
return 2
|
||||
|
||||
|
||||
# inner function
|
||||
def x(y):
|
||||
if not y:
|
||||
return 1
|
||||
|
||||
def inner():
|
||||
return
|
||||
|
||||
return 2
|
||||
|
||||
|
||||
def x(y):
|
||||
if not y:
|
||||
return
|
||||
|
||||
def inner():
|
||||
return 1
|
||||
116
resources/test/fixtures/flake8_return/RET503.py
vendored
Normal file
116
resources/test/fixtures/flake8_return/RET503.py
vendored
Normal file
@@ -0,0 +1,116 @@
|
||||
###
|
||||
# Errors
|
||||
###
|
||||
|
||||
# if/elif/else
|
||||
def x(y):
|
||||
if not y:
|
||||
return 1
|
||||
# error
|
||||
|
||||
|
||||
def x(y):
|
||||
if not y:
|
||||
print() # error
|
||||
else:
|
||||
return 2
|
||||
|
||||
|
||||
def x(y):
|
||||
if not y:
|
||||
return 1
|
||||
|
||||
print() # error
|
||||
|
||||
|
||||
# for
|
||||
def x(y):
|
||||
for i in range(10):
|
||||
if i > 10:
|
||||
return i
|
||||
# error
|
||||
|
||||
|
||||
def x(y):
|
||||
for i in range(10):
|
||||
if i > 10:
|
||||
return i
|
||||
else:
|
||||
print() # error
|
||||
|
||||
|
||||
###
|
||||
# Non-errors
|
||||
###
|
||||
|
||||
# raise as last return
|
||||
def x(y):
|
||||
if not y:
|
||||
return 1
|
||||
raise Exception
|
||||
|
||||
|
||||
# last line in while loop
|
||||
def x(y):
|
||||
while True:
|
||||
if y > 0:
|
||||
return 1
|
||||
y += 1
|
||||
|
||||
|
||||
# exclude empty functions
|
||||
def x(y):
|
||||
return None
|
||||
|
||||
|
||||
# return inner with statement
|
||||
def x(y):
|
||||
with y:
|
||||
return 1
|
||||
|
||||
|
||||
async def function():
|
||||
async with thing as foo:
|
||||
return foo.bar
|
||||
|
||||
|
||||
# assert as last return
|
||||
def x(y):
|
||||
if not y:
|
||||
return 1
|
||||
assert False, "Sanity check"
|
||||
|
||||
|
||||
# return value within loop
|
||||
def bar1(x, y, z):
|
||||
for i in x:
|
||||
if i > y:
|
||||
break
|
||||
return z
|
||||
|
||||
|
||||
def bar3(x, y, z):
|
||||
for i in x:
|
||||
if i > y:
|
||||
if z:
|
||||
break
|
||||
else:
|
||||
return z
|
||||
return None
|
||||
|
||||
|
||||
def bar1(x, y, z):
|
||||
for i in x:
|
||||
if i < y:
|
||||
continue
|
||||
return z
|
||||
|
||||
|
||||
def bar3(x, y, z):
|
||||
for i in x:
|
||||
if i < y:
|
||||
if z:
|
||||
continue
|
||||
else:
|
||||
return z
|
||||
return None
|
||||
232
resources/test/fixtures/flake8_return/RET504.py
vendored
Normal file
232
resources/test/fixtures/flake8_return/RET504.py
vendored
Normal file
@@ -0,0 +1,232 @@
|
||||
###
|
||||
# Errors
|
||||
###
|
||||
def x():
|
||||
a = 1
|
||||
return a # error
|
||||
|
||||
|
||||
def x():
|
||||
b, a = 1, 2
|
||||
print(b)
|
||||
return a # error
|
||||
|
||||
|
||||
def x():
|
||||
a = 1
|
||||
print()
|
||||
return a # error
|
||||
|
||||
|
||||
def x():
|
||||
a = 1
|
||||
print(a)
|
||||
a = 2
|
||||
return a # error
|
||||
|
||||
|
||||
def x():
|
||||
a = 1
|
||||
if True:
|
||||
return a # error
|
||||
a = 2
|
||||
print(a)
|
||||
return a
|
||||
|
||||
|
||||
# Can be refactored false positives
|
||||
# https://github.com/afonasev/flake8-return/issues/47#issuecomment-1122571066
|
||||
def get_bar_if_exists(obj):
|
||||
result = ""
|
||||
if hasattr(obj, "bar"):
|
||||
result = str(obj.bar)
|
||||
return result
|
||||
|
||||
|
||||
# https://github.com/afonasev/flake8-return/issues/47#issue-641117366
|
||||
def x():
|
||||
formatted = _USER_AGENT_FORMATTER.format(format_string, **values)
|
||||
# clean up after any blank components
|
||||
formatted = formatted.replace("()", "").replace(" ", " ").strip()
|
||||
return formatted
|
||||
|
||||
|
||||
# https://github.com/afonasev/flake8-return/issues/47#issue-641117366
|
||||
def user_agent_username(username=None):
|
||||
|
||||
if not username:
|
||||
return ""
|
||||
|
||||
username = username.replace(" ", "_") # Avoid spaces or %20.
|
||||
try:
|
||||
username.encode("ascii") # just test, but not actually use it
|
||||
except UnicodeEncodeError:
|
||||
username = quote(username.encode("utf-8"))
|
||||
else:
|
||||
# % is legal in the default $wgLegalTitleChars
|
||||
# This is so that ops know the real pywikibot will not
|
||||
# allow a useragent in the username to allow through a hand-coded
|
||||
# percent-encoded value.
|
||||
if "%" in username:
|
||||
username = quote(username)
|
||||
return username
|
||||
|
||||
|
||||
###
|
||||
# Non-errors
|
||||
###
|
||||
def x(y):
|
||||
a = 1
|
||||
print(a)
|
||||
return a
|
||||
|
||||
|
||||
def x():
|
||||
a = 1
|
||||
if y:
|
||||
return a
|
||||
a = a + 2
|
||||
print(a)
|
||||
return a
|
||||
|
||||
|
||||
def x():
|
||||
a = {}
|
||||
a["b"] = 2
|
||||
return a
|
||||
|
||||
|
||||
def x():
|
||||
a = []
|
||||
a.append(2)
|
||||
return a
|
||||
|
||||
|
||||
def x():
|
||||
a = lambda x: x
|
||||
a()
|
||||
return a
|
||||
|
||||
|
||||
# ignore unpacking
|
||||
def x():
|
||||
b, a = [1, 2]
|
||||
return a
|
||||
|
||||
|
||||
def x():
|
||||
val = ""
|
||||
for i in range(5):
|
||||
val = val + str(i)
|
||||
return val
|
||||
|
||||
|
||||
def x():
|
||||
val = ""
|
||||
i = 5
|
||||
while i:
|
||||
val = val + str(i)
|
||||
i = i - x
|
||||
return val
|
||||
|
||||
|
||||
# Test cases for using value for assignment then returning it
|
||||
# See:https://github.com/afonasev/flake8-return/issues/47
|
||||
def resolve_from_url(self, url: str) -> dict:
|
||||
local_match = self.local_scope_re.match(url)
|
||||
if local_match:
|
||||
schema = get_schema(name=local_match.group(1))
|
||||
self.store[url] = schema
|
||||
return schema
|
||||
raise NotImplementedError(...)
|
||||
|
||||
|
||||
my_dict = {}
|
||||
|
||||
|
||||
def my_func():
|
||||
foo = calculate_foo()
|
||||
my_dict["foo_result"] = foo
|
||||
return foo
|
||||
|
||||
|
||||
# Refactored incorrect false positives
|
||||
# See test cases above marked: "Can be refactored false positives"
|
||||
# https://github.com/afonasev/flake8-return/issues/47#issuecomment-1122571066
|
||||
def get_bar_if_exists(obj):
|
||||
if hasattr(obj, "bar"):
|
||||
return str(obj.bar)
|
||||
return ""
|
||||
|
||||
|
||||
# https://github.com/afonasev/flake8-return/issues/47#issue-641117366
|
||||
def x():
|
||||
formatted = _USER_AGENT_FORMATTER.format(format_string, **values)
|
||||
# clean up after any blank components
|
||||
return formatted.replace("()", "").replace(" ", " ").strip()
|
||||
|
||||
|
||||
# https://github.com/afonasev/flake8-return/issues/47#issue-641117366
|
||||
def user_agent_username(username=None):
|
||||
|
||||
if not username:
|
||||
return ""
|
||||
|
||||
username = username.replace(" ", "_") # Avoid spaces or %20.
|
||||
try:
|
||||
username.encode("ascii") # just test,
|
||||
# but not actually use it
|
||||
except UnicodeEncodeError:
|
||||
username = quote(username.encode("utf-8"))
|
||||
else:
|
||||
# % is legal in the default $wgLegalTitleChars
|
||||
# This is so that ops know the real pywikibot will not
|
||||
# allow a useragent in the username to allow through a
|
||||
# hand-coded percent-encoded value.
|
||||
if "%" in username:
|
||||
username = quote(username)
|
||||
return username
|
||||
|
||||
|
||||
# https://github.com/afonasev/flake8-return/issues/116#issue-1367575481
|
||||
def no_exception_loop():
|
||||
success = False
|
||||
for _ in range(10):
|
||||
try:
|
||||
success = True
|
||||
except Exception:
|
||||
print("exception")
|
||||
return success
|
||||
|
||||
|
||||
# https://github.com/afonasev/flake8-return/issues/116#issue-1367575481
|
||||
def no_exception():
|
||||
success = False
|
||||
try:
|
||||
success = True
|
||||
except Exception:
|
||||
print("exception")
|
||||
return success
|
||||
|
||||
|
||||
# https://github.com/afonasev/flake8-return/issues/116#issue-1367575481
|
||||
def exception():
|
||||
success = True
|
||||
try:
|
||||
print("raising")
|
||||
raise Exception
|
||||
except Exception:
|
||||
success = False
|
||||
return success
|
||||
|
||||
|
||||
# https://github.com/afonasev/flake8-return/issues/66
|
||||
def close(self):
|
||||
any_failed = False
|
||||
for task in self.tasks:
|
||||
try:
|
||||
task()
|
||||
except BaseException:
|
||||
any_failed = True
|
||||
report(traceback.format_exc())
|
||||
return any_failed
|
||||
141
resources/test/fixtures/flake8_return/RET505.py
vendored
Normal file
141
resources/test/fixtures/flake8_return/RET505.py
vendored
Normal file
@@ -0,0 +1,141 @@
|
||||
###
|
||||
# Error
|
||||
###
|
||||
def foo2(x, y, w, z):
|
||||
if x: # [no-else-return]
|
||||
a = 1
|
||||
return y
|
||||
elif z:
|
||||
b = 2
|
||||
return w
|
||||
else:
|
||||
c = 3
|
||||
return z
|
||||
|
||||
|
||||
def foo5(x, y, z):
|
||||
if x: # [no-else-return]
|
||||
if y:
|
||||
a = 4
|
||||
else:
|
||||
b = 2
|
||||
return
|
||||
elif z:
|
||||
c = 2
|
||||
else:
|
||||
c = 3
|
||||
return
|
||||
|
||||
|
||||
def foo2(x, y, w, z):
|
||||
if x:
|
||||
a = 1
|
||||
elif z:
|
||||
b = 2
|
||||
else:
|
||||
c = 3
|
||||
|
||||
if x: # [no-else-return]
|
||||
a = 1
|
||||
return y
|
||||
elif z:
|
||||
b = 2
|
||||
return w
|
||||
else:
|
||||
c = 3
|
||||
return z
|
||||
|
||||
|
||||
def foo1(x, y, z):
|
||||
if x: # [no-else-return]
|
||||
a = 1
|
||||
return y
|
||||
else:
|
||||
b = 2
|
||||
return z
|
||||
|
||||
|
||||
def foo3(x, y, z):
|
||||
if x:
|
||||
a = 1
|
||||
if y: # [no-else-return]
|
||||
b = 2
|
||||
return y
|
||||
else:
|
||||
c = 3
|
||||
return x
|
||||
else:
|
||||
d = 4
|
||||
return z
|
||||
|
||||
|
||||
def foo4(x, y):
|
||||
if x: # [no-else-return]
|
||||
if y:
|
||||
a = 4
|
||||
else:
|
||||
b = 2
|
||||
return
|
||||
else:
|
||||
c = 3
|
||||
return
|
||||
|
||||
|
||||
def foo6(x, y):
|
||||
if x:
|
||||
if y: # [no-else-return]
|
||||
a = 4
|
||||
return
|
||||
else:
|
||||
b = 2
|
||||
else:
|
||||
c = 3
|
||||
return
|
||||
|
||||
|
||||
def bar4(x):
|
||||
if x: # [no-else-return]
|
||||
return True
|
||||
else:
|
||||
try:
|
||||
return False
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
###
|
||||
# Non-error
|
||||
###
|
||||
def bar1(x, y, z):
|
||||
if x:
|
||||
return y
|
||||
return z
|
||||
|
||||
|
||||
def bar2(w, x, y, z):
|
||||
if x:
|
||||
return y
|
||||
if z:
|
||||
a = 1
|
||||
else:
|
||||
return w
|
||||
return None
|
||||
|
||||
|
||||
def bar3(x, y, z):
|
||||
if x:
|
||||
if z:
|
||||
return y
|
||||
else:
|
||||
return z
|
||||
return None
|
||||
|
||||
|
||||
x = 0
|
||||
|
||||
if x == 1:
|
||||
y = "a"
|
||||
elif x == 2:
|
||||
y = "b"
|
||||
else:
|
||||
y = "c"
|
||||
112
resources/test/fixtures/flake8_return/RET506.py
vendored
Normal file
112
resources/test/fixtures/flake8_return/RET506.py
vendored
Normal file
@@ -0,0 +1,112 @@
|
||||
###
|
||||
# Errors
|
||||
###
|
||||
def foo2(x, y, w, z):
|
||||
if x: # [no-else-raise]
|
||||
a = 1
|
||||
raise Exception(y)
|
||||
elif z:
|
||||
b = 2
|
||||
raise Exception(w)
|
||||
else:
|
||||
c = 3
|
||||
raise Exception(z)
|
||||
|
||||
|
||||
def foo5(x, y, z):
|
||||
if x: # [no-else-raise]
|
||||
if y:
|
||||
a = 4
|
||||
else:
|
||||
b = 2
|
||||
raise Exception(x)
|
||||
elif z:
|
||||
raise Exception(y)
|
||||
else:
|
||||
c = 3
|
||||
raise Exception(z)
|
||||
|
||||
|
||||
def foo1(x, y, z):
|
||||
if x: # [no-else-raise]
|
||||
a = 1
|
||||
raise Exception(y)
|
||||
else:
|
||||
b = 2
|
||||
raise Exception(z)
|
||||
|
||||
|
||||
def foo3(x, y, z):
|
||||
if x:
|
||||
a = 1
|
||||
if y: # [no-else-raise]
|
||||
b = 2
|
||||
raise Exception(y)
|
||||
else:
|
||||
c = 3
|
||||
raise Exception(x)
|
||||
else:
|
||||
d = 4
|
||||
raise Exception(z)
|
||||
|
||||
|
||||
def foo4(x, y):
|
||||
if x: # [no-else-raise]
|
||||
if y:
|
||||
a = 4
|
||||
else:
|
||||
b = 2
|
||||
raise Exception(x)
|
||||
else:
|
||||
c = 3
|
||||
raise Exception(y)
|
||||
|
||||
|
||||
def foo6(x, y):
|
||||
if x:
|
||||
if y: # [no-else-raise]
|
||||
a = 4
|
||||
raise Exception(x)
|
||||
else:
|
||||
b = 2
|
||||
else:
|
||||
c = 3
|
||||
raise Exception(y)
|
||||
|
||||
|
||||
def bar4(x):
|
||||
if x: # [no-else-raise]
|
||||
raise Exception(True)
|
||||
else:
|
||||
try:
|
||||
raise Exception(False)
|
||||
except ValueError:
|
||||
raise Exception(None)
|
||||
|
||||
|
||||
###
|
||||
# Non-errors
|
||||
###
|
||||
def bar1(x, y, z):
|
||||
if x:
|
||||
raise Exception(y)
|
||||
raise Exception(z)
|
||||
|
||||
|
||||
def bar2(w, x, y, z):
|
||||
if x:
|
||||
raise Exception(y)
|
||||
if z:
|
||||
a = 1
|
||||
else:
|
||||
raise Exception(w)
|
||||
raise Exception(None)
|
||||
|
||||
|
||||
def bar3(x, y, z):
|
||||
if x:
|
||||
if z:
|
||||
raise Exception(y)
|
||||
else:
|
||||
raise Exception(z)
|
||||
raise Exception(None)
|
||||
106
resources/test/fixtures/flake8_return/RET507.py
vendored
Normal file
106
resources/test/fixtures/flake8_return/RET507.py
vendored
Normal file
@@ -0,0 +1,106 @@
|
||||
###
|
||||
# Errors
|
||||
###
|
||||
def foo2(x, y, w, z):
|
||||
for i in x:
|
||||
if i < y: # [no-else-continue]
|
||||
continue
|
||||
elif i < w:
|
||||
continue
|
||||
else:
|
||||
a = z
|
||||
|
||||
|
||||
def foo5(x, y, z):
|
||||
for i in x:
|
||||
if i < y: # [no-else-continue]
|
||||
if y:
|
||||
a = 4
|
||||
else:
|
||||
b = 2
|
||||
continue
|
||||
elif z:
|
||||
c = 2
|
||||
else:
|
||||
c = 3
|
||||
continue
|
||||
|
||||
|
||||
###
|
||||
# Non-errors
|
||||
###
|
||||
def foo1(x, y, z):
|
||||
for i in x:
|
||||
if i < y: # [no-else-continue]
|
||||
continue
|
||||
else:
|
||||
a = z
|
||||
|
||||
|
||||
def foo3(x, y, z):
|
||||
for i in x:
|
||||
if i < y:
|
||||
a = 1
|
||||
if z: # [no-else-continue]
|
||||
b = 2
|
||||
continue
|
||||
else:
|
||||
c = 3
|
||||
continue
|
||||
else:
|
||||
d = 4
|
||||
continue
|
||||
|
||||
|
||||
def foo4(x, y):
|
||||
for i in x:
|
||||
if i < x: # [no-else-continue]
|
||||
if y:
|
||||
a = 4
|
||||
else:
|
||||
b = 2
|
||||
continue
|
||||
else:
|
||||
c = 3
|
||||
continue
|
||||
|
||||
|
||||
def foo6(x, y):
|
||||
for i in x:
|
||||
if i < x:
|
||||
if y: # [no-else-continue]
|
||||
a = 4
|
||||
continue
|
||||
else:
|
||||
b = 2
|
||||
else:
|
||||
c = 3
|
||||
continue
|
||||
|
||||
|
||||
def bar4(x):
|
||||
for i in range(10):
|
||||
if x: # [no-else-continue]
|
||||
continue
|
||||
else:
|
||||
try:
|
||||
return
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
|
||||
def bar1(x, y, z):
|
||||
for i in x:
|
||||
if i < y:
|
||||
continue
|
||||
return z
|
||||
|
||||
|
||||
def bar3(x, y, z):
|
||||
for i in x:
|
||||
if i < y:
|
||||
if z:
|
||||
continue
|
||||
else:
|
||||
return z
|
||||
return None
|
||||
138
resources/test/fixtures/flake8_return/RET508.py
vendored
Normal file
138
resources/test/fixtures/flake8_return/RET508.py
vendored
Normal file
@@ -0,0 +1,138 @@
|
||||
###
|
||||
# Errors
|
||||
###
|
||||
def foo2(x, y, w, z):
|
||||
for i in x:
|
||||
if i > y: # [no-else-break]
|
||||
break
|
||||
elif i > w:
|
||||
break
|
||||
else:
|
||||
a = z
|
||||
|
||||
|
||||
def foo5(x, y, z):
|
||||
for i in x:
|
||||
if i > y: # [no-else-break]
|
||||
if y:
|
||||
a = 4
|
||||
else:
|
||||
b = 2
|
||||
break
|
||||
elif z:
|
||||
c = 2
|
||||
else:
|
||||
c = 3
|
||||
break
|
||||
|
||||
|
||||
def foo1(x, y, z):
|
||||
for i in x:
|
||||
if i > y: # [no-else-break]
|
||||
break
|
||||
else:
|
||||
a = z
|
||||
|
||||
|
||||
def foo3(x, y, z):
|
||||
for i in x:
|
||||
if i > y:
|
||||
a = 1
|
||||
if z: # [no-else-break]
|
||||
b = 2
|
||||
break
|
||||
else:
|
||||
c = 3
|
||||
break
|
||||
else:
|
||||
d = 4
|
||||
break
|
||||
|
||||
|
||||
def foo4(x, y):
|
||||
for i in x:
|
||||
if i > x: # [no-else-break]
|
||||
if y:
|
||||
a = 4
|
||||
else:
|
||||
b = 2
|
||||
break
|
||||
else:
|
||||
c = 3
|
||||
break
|
||||
|
||||
|
||||
def foo6(x, y):
|
||||
for i in x:
|
||||
if i > x:
|
||||
if y: # [no-else-break]
|
||||
a = 4
|
||||
break
|
||||
else:
|
||||
b = 2
|
||||
else:
|
||||
c = 3
|
||||
break
|
||||
|
||||
|
||||
def bar4(x):
|
||||
for i in range(10):
|
||||
if x: # [no-else-break]
|
||||
break
|
||||
else:
|
||||
try:
|
||||
return
|
||||
except ValueError:
|
||||
break
|
||||
|
||||
|
||||
###
|
||||
# Non-errors
|
||||
###
|
||||
def bar1(x, y, z):
|
||||
for i in x:
|
||||
if i > y:
|
||||
break
|
||||
return z
|
||||
|
||||
|
||||
def bar2(w, x, y, z):
|
||||
for i in w:
|
||||
if i > x:
|
||||
break
|
||||
if z < i:
|
||||
a = y
|
||||
else:
|
||||
break
|
||||
return
|
||||
|
||||
|
||||
def bar3(x, y, z):
|
||||
for i in x:
|
||||
if i > y:
|
||||
if z:
|
||||
break
|
||||
else:
|
||||
return z
|
||||
return None
|
||||
|
||||
|
||||
def nested1(x, y, z):
|
||||
for i in x:
|
||||
if i > x:
|
||||
for j in y:
|
||||
if j < z:
|
||||
break
|
||||
else:
|
||||
a = z
|
||||
|
||||
|
||||
def nested2(x, y, z):
|
||||
for i in x:
|
||||
if i > x:
|
||||
for j in y:
|
||||
if j > z:
|
||||
break
|
||||
break
|
||||
else:
|
||||
a = z
|
||||
@@ -1,7 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional
|
||||
from typing import Callable, List, Tuple, Optional, Sequence
|
||||
|
||||
from models import (
|
||||
Fruit,
|
||||
@@ -37,4 +37,12 @@ def f(x: int) -> List[int]:
|
||||
return y
|
||||
|
||||
|
||||
x: Optional[int] = None
|
||||
x: Tuple[int, ...] = (1, 2)
|
||||
|
||||
|
||||
def f(param: "Optional[Callable]" = None) -> "None":
|
||||
pass
|
||||
|
||||
|
||||
def f(param: Optional["Sequence"] = None) -> "None":
|
||||
pass
|
||||
|
||||
9
resources/test/fixtures/pygrep-hooks/PGH001_0.py
vendored
Normal file
9
resources/test/fixtures/pygrep-hooks/PGH001_0.py
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
from ast import literal_eval
|
||||
|
||||
eval("3 + 4")
|
||||
|
||||
literal_eval({1: 2})
|
||||
|
||||
|
||||
def fn() -> None:
|
||||
eval("3 + 4")
|
||||
11
resources/test/fixtures/pygrep-hooks/PGH001_1.py
vendored
Normal file
11
resources/test/fixtures/pygrep-hooks/PGH001_1.py
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
def eval(content: str) -> None:
|
||||
pass
|
||||
|
||||
|
||||
eval("3 + 4")
|
||||
|
||||
literal_eval({1: 2})
|
||||
|
||||
|
||||
def fn() -> None:
|
||||
eval("3 + 4")
|
||||
37
resources/test/fixtures/pylint/consider_merging_isinstance.py
vendored
Normal file
37
resources/test/fixtures/pylint/consider_merging_isinstance.py
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
"""Checks use of consider-merging-isinstance"""
|
||||
# pylint:disable=line-too-long, simplifiable-condition
|
||||
|
||||
|
||||
def isinstances():
|
||||
"Examples of isinstances"
|
||||
var = range(10)
|
||||
|
||||
# merged
|
||||
if isinstance(var[1], (int, float)):
|
||||
pass
|
||||
result = isinstance(var[2], (int, float))
|
||||
|
||||
# not merged
|
||||
if isinstance(var[3], int) or isinstance(var[3], float) or isinstance(var[3], list) and True: # [consider-merging-isinstance]
|
||||
pass
|
||||
result = isinstance(var[4], int) or isinstance(var[4], float) or isinstance(var[5], list) and False # [consider-merging-isinstance]
|
||||
|
||||
result = isinstance(var[5], int) or True or isinstance(var[5], float) # [consider-merging-isinstance]
|
||||
|
||||
infered_isinstance = isinstance
|
||||
result = infered_isinstance(var[6], int) or infered_isinstance(var[6], float) or infered_isinstance(var[6], list) and False # [consider-merging-isinstance]
|
||||
result = isinstance(var[10], str) or isinstance(var[10], int) and var[8] * 14 or isinstance(var[10], float) and var[5] * 14.4 or isinstance(var[10], list) # [consider-merging-isinstance]
|
||||
result = isinstance(var[11], int) or isinstance(var[11], int) or isinstance(var[11], float) # [consider-merging-isinstance]
|
||||
|
||||
result = isinstance(var[20])
|
||||
result = isinstance()
|
||||
|
||||
# Combination merged and not merged
|
||||
result = isinstance(var[12], (int, float)) or isinstance(var[12], list) # [consider-merging-isinstance]
|
||||
|
||||
# not merged but valid
|
||||
result = isinstance(var[5], int) and var[5] * 14 or isinstance(var[5], float) and var[5] * 14.4
|
||||
result = isinstance(var[7], int) or not isinstance(var[7], float)
|
||||
result = isinstance(var[6], int) or isinstance(var[7], float)
|
||||
result = isinstance(var[6], int) or isinstance(var[7], int)
|
||||
return result
|
||||
30
resources/test/fixtures/pylint/property_with_parameters.py
vendored
Normal file
30
resources/test/fixtures/pylint/property_with_parameters.py
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
# pylint: disable=missing-docstring, too-few-public-methods
|
||||
from abc import ABCMeta, abstractmethod
|
||||
|
||||
|
||||
class Cls:
|
||||
@property
|
||||
def attribute(self, param, param1): # [property-with-parameters]
|
||||
return param + param1
|
||||
|
||||
@property
|
||||
def attribute_keyword_only(self, *, param, param1): # [property-with-parameters]
|
||||
return param + param1
|
||||
|
||||
@property
|
||||
def attribute_positional_only(self, param, param1, /): # [property-with-parameters]
|
||||
return param + param1
|
||||
|
||||
|
||||
class MyClassBase(metaclass=ABCMeta):
|
||||
"""MyClassBase."""
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def example(self):
|
||||
"""Getter."""
|
||||
|
||||
@example.setter
|
||||
@abstractmethod
|
||||
def example(self, value):
|
||||
"""Setter."""
|
||||
5
resources/test/fixtures/pylint/unnecessary_direct_lambda_call.py
vendored
Normal file
5
resources/test/fixtures/pylint/unnecessary_direct_lambda_call.py
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
"""Test unnecessary direct calls to lambda expressions."""
|
||||
# pylint: disable=undefined-variable, line-too-long
|
||||
|
||||
y = (lambda x: x**2 + 2*x + 1)(a) # [unnecessary-direct-lambda-call]
|
||||
y = max((lambda x: x**2)(a), (lambda x: x+1)(a)) # [unnecessary-direct-lambda-call,unnecessary-direct-lambda-call]
|
||||
7
resources/test/fixtures/ruff/flake8_noqa.py
vendored
Normal file
7
resources/test/fixtures/ruff/flake8_noqa.py
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
# flake8: noqa
|
||||
|
||||
import os
|
||||
|
||||
|
||||
def f():
|
||||
x = 1
|
||||
7
resources/test/fixtures/ruff/ruff_noqa.py
vendored
Normal file
7
resources/test/fixtures/ruff/ruff_noqa.py
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
# ruff: noqa
|
||||
|
||||
import os
|
||||
|
||||
|
||||
def f():
|
||||
x = 1
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ruff_dev"
|
||||
version = "0.0.151"
|
||||
version = "0.0.154"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -28,11 +28,12 @@ pub fn main(cli: &Cli) -> Result<()> {
|
||||
output.push('\n');
|
||||
output.push('\n');
|
||||
|
||||
if let Some(url) = check_category.url() {
|
||||
if let Some((url, platform)) = check_category.url() {
|
||||
output.push_str(&format!(
|
||||
"For more, see [{}]({}) on PyPI.",
|
||||
"For more, see [{}]({}) on {}.",
|
||||
check_category.title(),
|
||||
url
|
||||
url,
|
||||
platform
|
||||
));
|
||||
output.push('\n');
|
||||
output.push('\n');
|
||||
|
||||
@@ -36,8 +36,8 @@ use crate::visibility::{module_visibility, transition_scope, Modifier, Visibilit
|
||||
use crate::{
|
||||
docstrings, flake8_2020, flake8_annotations, flake8_bandit, flake8_blind_except,
|
||||
flake8_boolean_trap, flake8_bugbear, flake8_builtins, flake8_comprehensions, flake8_debugger,
|
||||
flake8_print, flake8_tidy_imports, mccabe, pep8_naming, pycodestyle, pydocstyle, pyflakes,
|
||||
pylint, pyupgrade, rules,
|
||||
flake8_print, flake8_return, flake8_tidy_imports, mccabe, pep8_naming, pycodestyle, pydocstyle,
|
||||
pyflakes, pygrep_hooks, pylint, pyupgrade, rules,
|
||||
};
|
||||
|
||||
const GLOBAL_SCOPE_INDEX: usize = 0;
|
||||
@@ -421,9 +421,23 @@ where
|
||||
if self.settings.enabled.contains(&CheckCode::B018) {
|
||||
flake8_bugbear::plugins::useless_expression(self, body);
|
||||
}
|
||||
|
||||
if self.settings.enabled.contains(&CheckCode::B019) {
|
||||
flake8_bugbear::plugins::cached_instance_method(self, decorator_list);
|
||||
}
|
||||
|
||||
if self.settings.enabled.contains(&CheckCode::RET501)
|
||||
|| self.settings.enabled.contains(&CheckCode::RET502)
|
||||
|| self.settings.enabled.contains(&CheckCode::RET503)
|
||||
|| self.settings.enabled.contains(&CheckCode::RET504)
|
||||
|| self.settings.enabled.contains(&CheckCode::RET505)
|
||||
|| self.settings.enabled.contains(&CheckCode::RET506)
|
||||
|| self.settings.enabled.contains(&CheckCode::RET507)
|
||||
|| self.settings.enabled.contains(&CheckCode::RET508)
|
||||
{
|
||||
flake8_return::plugins::function(self, body);
|
||||
}
|
||||
|
||||
if self.settings.enabled.contains(&CheckCode::C901) {
|
||||
if let Some(check) = mccabe::checks::function_is_too_complex(
|
||||
stmt,
|
||||
@@ -441,6 +455,10 @@ where
|
||||
);
|
||||
}
|
||||
|
||||
if self.settings.enabled.contains(&CheckCode::PLR0206) {
|
||||
pylint::plugins::property_with_parameters(self, stmt, decorator_list, args);
|
||||
}
|
||||
|
||||
self.check_builtin_shadowing(name, Range::from_located(stmt), true);
|
||||
|
||||
// Visit the decorators and arguments, but avoid the body, which will be
|
||||
@@ -1191,7 +1209,10 @@ where
|
||||
let prev_in_literal = self.in_literal;
|
||||
let prev_in_type_definition = self.in_type_definition;
|
||||
|
||||
if self.in_type_definition && self.annotations_future_enabled {
|
||||
if !(self.in_deferred_type_definition || self.in_deferred_string_type_definition)
|
||||
&& self.in_type_definition
|
||||
&& self.annotations_future_enabled
|
||||
{
|
||||
if let ExprKind::Constant {
|
||||
value: Constant::Str(value),
|
||||
..
|
||||
@@ -1700,6 +1721,16 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
// pygrep-hooks
|
||||
if self.settings.enabled.contains(&CheckCode::PGH001) {
|
||||
pygrep_hooks::checks::no_eval(self, func);
|
||||
}
|
||||
|
||||
// pylint
|
||||
if self.settings.enabled.contains(&CheckCode::PLC3002) {
|
||||
pylint::plugins::unnecessary_direct_lambda_call(self, expr, func);
|
||||
}
|
||||
|
||||
// Ruff
|
||||
if self.settings.enabled.contains(&CheckCode::RUF101) {
|
||||
rules::plugins::convert_exit_to_sys_exit(self, func);
|
||||
@@ -2046,6 +2077,11 @@ where
|
||||
}
|
||||
self.push_scope(Scope::new(ScopeKind::Generator));
|
||||
}
|
||||
ExprKind::BoolOp { op, values } => {
|
||||
if self.settings.enabled.contains(&CheckCode::PLR1701) {
|
||||
pylint::plugins::consider_merging_isinstance(self, expr, op, values);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
|
||||
@@ -2825,9 +2861,11 @@ impl<'a> Checker<'a> {
|
||||
self.scope_stack = scopes;
|
||||
self.parent_stack = parents;
|
||||
self.in_annotation = in_annotation;
|
||||
self.in_type_definition = true;
|
||||
self.in_deferred_type_definition = true;
|
||||
self.visit_expr(expr);
|
||||
self.in_deferred_type_definition = false;
|
||||
self.in_type_definition = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2856,9 +2894,11 @@ impl<'a> Checker<'a> {
|
||||
self.scope_stack = scopes;
|
||||
self.parent_stack = parents;
|
||||
self.in_annotation = in_annotation;
|
||||
self.in_type_definition = true;
|
||||
self.in_deferred_string_type_definition = true;
|
||||
self.visit_expr(expr);
|
||||
self.in_deferred_string_type_definition = false;
|
||||
self.in_type_definition = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,10 +9,10 @@ use crate::ast::types::Range;
|
||||
use crate::autofix::Fix;
|
||||
use crate::checks::{Check, CheckCode, CheckKind};
|
||||
use crate::noqa;
|
||||
use crate::noqa::Directive;
|
||||
use crate::noqa::{is_file_exempt, Directive};
|
||||
use crate::settings::Settings;
|
||||
|
||||
// Regex from PEP263
|
||||
// Regex from PEP263.
|
||||
static CODING_COMMENT_REGEX: Lazy<Regex> =
|
||||
Lazy::new(|| Regex::new(r"^[ \t\f]*#.*?coding[:=][ \t]*utf-?8").unwrap());
|
||||
|
||||
@@ -58,8 +58,11 @@ pub fn check_lines(
|
||||
}
|
||||
|
||||
macro_rules! add_if {
|
||||
($check:expr, $noqa:expr) => {{
|
||||
match $noqa {
|
||||
($check:expr, $noqa_lineno:expr, $line:expr) => {{
|
||||
match noqa_directives
|
||||
.entry($noqa_lineno)
|
||||
.or_insert_with(|| (noqa::extract_noqa_directive($line), vec![]))
|
||||
{
|
||||
(Directive::All(..), matches) => {
|
||||
matches.push($check.kind.code().as_ref());
|
||||
if ignore_noqa {
|
||||
@@ -83,6 +86,12 @@ pub fn check_lines(
|
||||
|
||||
let lines: Vec<&str> = contents.lines().collect();
|
||||
for (lineno, line) in lines.iter().enumerate() {
|
||||
// If we hit an exemption for the entire file, bail.
|
||||
if is_file_exempt(line) {
|
||||
checks.drain(..);
|
||||
return;
|
||||
}
|
||||
|
||||
// Grab the noqa (logical) line number for the current (physical) line.
|
||||
// If there are newlines at the end of the file, they won't be represented in
|
||||
// `noqa_line_for`, so fallback to the current line.
|
||||
@@ -106,11 +115,7 @@ pub fn check_lines(
|
||||
Location::new(lineno + 2, 0),
|
||||
));
|
||||
}
|
||||
|
||||
let noqa = noqa_directives.entry(noqa_lineno).or_insert_with(|| {
|
||||
(noqa::extract_noqa_directive(lines[noqa_lineno]), vec![])
|
||||
});
|
||||
add_if!(check, noqa);
|
||||
add_if!(check, noqa_lineno, lines[noqa_lineno]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -155,11 +160,7 @@ pub fn check_lines(
|
||||
end_location: Location::new(lineno + 1, line_length),
|
||||
},
|
||||
);
|
||||
|
||||
let noqa = noqa_directives
|
||||
.entry(noqa_lineno)
|
||||
.or_insert_with(|| (noqa::extract_noqa_directive(lines[noqa_lineno]), vec![]));
|
||||
add_if!(check, noqa);
|
||||
add_if!(check, noqa_lineno, lines[noqa_lineno]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -179,10 +180,7 @@ pub fn check_lines(
|
||||
|
||||
let lineno = lines.len() - 1;
|
||||
let noqa_lineno = noqa_line_for.get(&(lineno + 1)).unwrap_or(&(lineno + 1)) - 1;
|
||||
let noqa = noqa_directives
|
||||
.entry(noqa_lineno)
|
||||
.or_insert_with(|| (noqa::extract_noqa_directive(lines[noqa_lineno]), vec![]));
|
||||
add_if!(check, noqa);
|
||||
add_if!(check, noqa_lineno, lines[noqa_lineno]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -269,13 +267,12 @@ mod tests {
|
||||
#[test]
|
||||
fn e501_non_ascii_char() {
|
||||
let line = "'\u{4e9c}' * 2"; // 7 in UTF-32, 9 in UTF-8.
|
||||
let noqa_line_for: IntMap<usize, usize> = IntMap::default();
|
||||
let check_with_max_line_length = |line_length: usize| {
|
||||
let mut checks: Vec<Check> = vec![];
|
||||
check_lines(
|
||||
&mut checks,
|
||||
line,
|
||||
&noqa_line_for,
|
||||
&IntMap::default(),
|
||||
&Settings {
|
||||
line_length,
|
||||
..Settings::for_rule(CheckCode::E501)
|
||||
|
||||
294
src/checks.rs
294
src/checks.rs
@@ -90,7 +90,10 @@ pub enum CheckCode {
|
||||
F831,
|
||||
F841,
|
||||
F901,
|
||||
// pylint errors
|
||||
// pylint
|
||||
PLR1701,
|
||||
PLC3002,
|
||||
PLR0206,
|
||||
PLE1142,
|
||||
// flake8-builtins
|
||||
A001,
|
||||
@@ -149,6 +152,15 @@ pub enum CheckCode {
|
||||
C901,
|
||||
// flake8-tidy-imports
|
||||
I252,
|
||||
// flake8-return
|
||||
RET501,
|
||||
RET502,
|
||||
RET503,
|
||||
RET504,
|
||||
RET505,
|
||||
RET506,
|
||||
RET507,
|
||||
RET508,
|
||||
// flake8-print
|
||||
T201,
|
||||
T203,
|
||||
@@ -278,35 +290,53 @@ pub enum CheckCode {
|
||||
RUF101,
|
||||
// Meta
|
||||
M001,
|
||||
// pygrep-hooks
|
||||
PGH001,
|
||||
}
|
||||
|
||||
#[derive(EnumIter, Debug, PartialEq, Eq)]
|
||||
pub enum CheckCategory {
|
||||
Pyflakes,
|
||||
Pycodestyle,
|
||||
McCabe,
|
||||
Isort,
|
||||
Pydocstyle,
|
||||
Pyupgrade,
|
||||
PEP8Naming,
|
||||
Eradicate,
|
||||
Flake82020,
|
||||
Flake8Annotations,
|
||||
Flake8Bandit,
|
||||
Flake8Comprehensions,
|
||||
Flake8Debugger,
|
||||
Flake8BlindExcept,
|
||||
Flake8BooleanTrap,
|
||||
Flake8Bugbear,
|
||||
Flake8Builtins,
|
||||
Flake8TidyImports,
|
||||
Flake8Comprehensions,
|
||||
Flake8Debugger,
|
||||
Flake8Print,
|
||||
Flake8Quotes,
|
||||
Flake8Annotations,
|
||||
Flake82020,
|
||||
Flake8BlindExcept,
|
||||
McCabe,
|
||||
Flake8Return,
|
||||
Flake8TidyImports,
|
||||
Eradicate,
|
||||
PygrepHooks,
|
||||
Pylint,
|
||||
Ruff,
|
||||
Meta,
|
||||
}
|
||||
|
||||
pub enum Platform {
|
||||
PyPI,
|
||||
GitHub,
|
||||
}
|
||||
|
||||
impl fmt::Display for Platform {
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
Platform::PyPI => fmt.write_str("PyPI"),
|
||||
Platform::GitHub => fmt.write_str("GitHub"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CheckCategory {
|
||||
pub fn title(&self) -> &'static str {
|
||||
match self {
|
||||
@@ -322,6 +352,7 @@ impl CheckCategory {
|
||||
CheckCategory::Flake8Debugger => "flake8-debugger",
|
||||
CheckCategory::Flake8Print => "flake8-print",
|
||||
CheckCategory::Flake8Quotes => "flake8-quotes",
|
||||
CheckCategory::Flake8Return => "flake8-return",
|
||||
CheckCategory::Flake8TidyImports => "flake8-tidy-imports",
|
||||
CheckCategory::Isort => "isort",
|
||||
CheckCategory::McCabe => "mccabe",
|
||||
@@ -330,52 +361,102 @@ impl CheckCategory {
|
||||
CheckCategory::Pycodestyle => "pycodestyle",
|
||||
CheckCategory::Pydocstyle => "pydocstyle",
|
||||
CheckCategory::Pyflakes => "Pyflakes",
|
||||
CheckCategory::PygrepHooks => "pygrep-hooks",
|
||||
CheckCategory::Pylint => "Pylint",
|
||||
CheckCategory::Pyupgrade => "pyupgrade",
|
||||
CheckCategory::Ruff => "Ruff-specific rules",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn url(&self) -> Option<&'static str> {
|
||||
pub fn url(&self) -> Option<(&'static str, &'static Platform)> {
|
||||
match self {
|
||||
CheckCategory::Eradicate => Some("https://pypi.org/project/eradicate/2.1.0/"),
|
||||
CheckCategory::Flake82020 => Some("https://pypi.org/project/flake8-2020/1.7.0/"),
|
||||
CheckCategory::Flake8Annotations => {
|
||||
Some("https://pypi.org/project/flake8-annotations/2.9.1/")
|
||||
CheckCategory::Eradicate => {
|
||||
Some(("https://pypi.org/project/eradicate/2.1.0/", &Platform::PyPI))
|
||||
}
|
||||
CheckCategory::Flake8Bandit => Some("https://pypi.org/project/flake8-bandit/4.1.1/"),
|
||||
CheckCategory::Flake8BlindExcept => {
|
||||
Some("https://pypi.org/project/flake8-blind-except/0.2.1/")
|
||||
CheckCategory::Flake82020 => Some((
|
||||
"https://pypi.org/project/flake8-2020/1.7.0/",
|
||||
&Platform::PyPI,
|
||||
)),
|
||||
CheckCategory::Flake8Annotations => Some((
|
||||
"https://pypi.org/project/flake8-annotations/2.9.1/",
|
||||
&Platform::PyPI,
|
||||
)),
|
||||
CheckCategory::Flake8Bandit => Some((
|
||||
"https://pypi.org/project/flake8-bandit/4.1.1/",
|
||||
&Platform::PyPI,
|
||||
)),
|
||||
CheckCategory::Flake8BlindExcept => Some((
|
||||
"https://pypi.org/project/flake8-blind-except/0.2.1/",
|
||||
&Platform::PyPI,
|
||||
)),
|
||||
CheckCategory::Flake8BooleanTrap => Some((
|
||||
"https://pypi.org/project/flake8-boolean-trap/0.1.0/",
|
||||
&Platform::PyPI,
|
||||
)),
|
||||
CheckCategory::Flake8Bugbear => Some((
|
||||
"https://pypi.org/project/flake8-bugbear/22.10.27/",
|
||||
&Platform::PyPI,
|
||||
)),
|
||||
CheckCategory::Flake8Builtins => Some((
|
||||
"https://pypi.org/project/flake8-builtins/2.0.1/",
|
||||
&Platform::PyPI,
|
||||
)),
|
||||
CheckCategory::Flake8Comprehensions => Some((
|
||||
"https://pypi.org/project/flake8-comprehensions/3.10.1/",
|
||||
&Platform::PyPI,
|
||||
)),
|
||||
CheckCategory::Flake8Debugger => Some((
|
||||
"https://pypi.org/project/flake8-debugger/4.1.2/",
|
||||
&Platform::PyPI,
|
||||
)),
|
||||
CheckCategory::Flake8Print => Some((
|
||||
"https://pypi.org/project/flake8-print/5.0.0/",
|
||||
&Platform::PyPI,
|
||||
)),
|
||||
CheckCategory::Flake8Quotes => Some((
|
||||
"https://pypi.org/project/flake8-quotes/3.3.1/",
|
||||
&Platform::PyPI,
|
||||
)),
|
||||
CheckCategory::Flake8Return => Some((
|
||||
"https://pypi.org/project/flake8-return/1.2.0/",
|
||||
&Platform::PyPI,
|
||||
)),
|
||||
CheckCategory::Flake8TidyImports => Some((
|
||||
"https://pypi.org/project/flake8-tidy-imports/4.8.0/",
|
||||
&Platform::PyPI,
|
||||
)),
|
||||
CheckCategory::Isort => {
|
||||
Some(("https://pypi.org/project/isort/5.10.1/", &Platform::PyPI))
|
||||
}
|
||||
CheckCategory::Flake8BooleanTrap => {
|
||||
Some("https://pypi.org/project/flake8-boolean-trap/0.1.0/")
|
||||
CheckCategory::McCabe => {
|
||||
Some(("https://pypi.org/project/mccabe/0.7.0/", &Platform::PyPI))
|
||||
}
|
||||
CheckCategory::Flake8Bugbear => {
|
||||
Some("https://pypi.org/project/flake8-bugbear/22.10.27/")
|
||||
}
|
||||
CheckCategory::Flake8Builtins => {
|
||||
Some("https://pypi.org/project/flake8-builtins/2.0.1/")
|
||||
}
|
||||
CheckCategory::Flake8Comprehensions => {
|
||||
Some("https://pypi.org/project/flake8-comprehensions/3.10.1/")
|
||||
}
|
||||
CheckCategory::Flake8Debugger => {
|
||||
Some("https://pypi.org/project/flake8-debugger/4.1.2/")
|
||||
}
|
||||
CheckCategory::Flake8Print => Some("https://pypi.org/project/flake8-print/5.0.0/"),
|
||||
CheckCategory::Flake8Quotes => Some("https://pypi.org/project/flake8-quotes/3.3.1/"),
|
||||
CheckCategory::Flake8TidyImports => {
|
||||
Some("https://pypi.org/project/flake8-tidy-imports/4.8.0/")
|
||||
}
|
||||
CheckCategory::Isort => Some("https://pypi.org/project/isort/5.10.1/"),
|
||||
CheckCategory::McCabe => Some("https://pypi.org/project/mccabe/0.7.0/"),
|
||||
CheckCategory::Meta => None,
|
||||
CheckCategory::PEP8Naming => Some("https://pypi.org/project/pep8-naming/0.13.2/"),
|
||||
CheckCategory::Pycodestyle => Some("https://pypi.org/project/pycodestyle/2.9.1/"),
|
||||
CheckCategory::Pydocstyle => Some("https://pypi.org/project/pydocstyle/6.1.1/"),
|
||||
CheckCategory::Pyflakes => Some("https://pypi.org/project/pyflakes/2.5.0/"),
|
||||
CheckCategory::Pylint => Some("https://pypi.org/project/pylint/2.15.7/"),
|
||||
CheckCategory::Pyupgrade => Some("https://pypi.org/project/pyupgrade/3.2.0/"),
|
||||
CheckCategory::PEP8Naming => Some((
|
||||
"https://pypi.org/project/pep8-naming/0.13.2/",
|
||||
&Platform::PyPI,
|
||||
)),
|
||||
CheckCategory::Pycodestyle => Some((
|
||||
"https://pypi.org/project/pycodestyle/2.9.1/",
|
||||
&Platform::PyPI,
|
||||
)),
|
||||
CheckCategory::Pydocstyle => Some((
|
||||
"https://pypi.org/project/pydocstyle/6.1.1/",
|
||||
&Platform::PyPI,
|
||||
)),
|
||||
CheckCategory::Pyflakes => {
|
||||
Some(("https://pypi.org/project/pyflakes/2.5.0/", &Platform::PyPI))
|
||||
}
|
||||
CheckCategory::Pylint => {
|
||||
Some(("https://pypi.org/project/pylint/2.15.7/", &Platform::PyPI))
|
||||
}
|
||||
CheckCategory::PygrepHooks => Some((
|
||||
"https://github.com/pre-commit/pygrep-hooks",
|
||||
&Platform::GitHub,
|
||||
)),
|
||||
CheckCategory::Pyupgrade => {
|
||||
Some(("https://pypi.org/project/pyupgrade/3.2.0/", &Platform::PyPI))
|
||||
}
|
||||
CheckCategory::Ruff => None,
|
||||
}
|
||||
}
|
||||
@@ -413,6 +494,21 @@ impl fmt::Display for DeferralKeyword {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Branch {
|
||||
Elif,
|
||||
Else,
|
||||
}
|
||||
|
||||
impl fmt::Display for Branch {
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
Branch::Elif => fmt.write_str("elif"),
|
||||
Branch::Else => fmt.write_str("else"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(AsRefStr, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum CheckKind {
|
||||
// pycodestyle errors
|
||||
@@ -476,7 +572,10 @@ pub enum CheckKind {
|
||||
UnusedImport(String, bool),
|
||||
UnusedVariable(String),
|
||||
YieldOutsideFunction(DeferralKeyword),
|
||||
// pylint errors
|
||||
// pylint
|
||||
ConsiderMergingIsinstance(String, Vec<String>),
|
||||
UnnecessaryDirectLambdaCall,
|
||||
PropertyWithParameters,
|
||||
AwaitOutsideAsync,
|
||||
// flake8-builtins
|
||||
BuiltinVariableShadowing(String),
|
||||
@@ -533,6 +632,15 @@ pub enum CheckKind {
|
||||
Debugger(DebuggerUsingType),
|
||||
// flake8-tidy-imports
|
||||
BannedRelativeImport(Strictness),
|
||||
// flake8-return
|
||||
UnnecessaryReturnNone,
|
||||
ImplicitReturnValue,
|
||||
ImplicitReturn,
|
||||
UnnecessaryAssign,
|
||||
SuperfluousElseReturn(Branch),
|
||||
SuperfluousElseRaise(Branch),
|
||||
SuperfluousElseContinue(Branch),
|
||||
SuperfluousElseBreak(Branch),
|
||||
// flake8-print
|
||||
PrintFound,
|
||||
PPrintFound,
|
||||
@@ -657,6 +765,8 @@ pub enum CheckKind {
|
||||
BooleanPositionalArgInFunctionDefinition,
|
||||
BooleanDefaultValueInFunctionDefinition,
|
||||
BooleanPositionalValueInFunctionCall,
|
||||
// pygrep-hooks
|
||||
NoEval,
|
||||
// Ruff
|
||||
AmbiguousUnicodeCharacterString(char, char),
|
||||
AmbiguousUnicodeCharacterDocstring(char, char),
|
||||
@@ -759,8 +869,13 @@ impl CheckCode {
|
||||
CheckCode::F831 => CheckKind::DuplicateArgumentName,
|
||||
CheckCode::F841 => CheckKind::UnusedVariable("...".to_string()),
|
||||
CheckCode::F901 => CheckKind::RaiseNotImplemented,
|
||||
// pylint errors
|
||||
// pylint
|
||||
CheckCode::PLC3002 => CheckKind::UnnecessaryDirectLambdaCall,
|
||||
CheckCode::PLE1142 => CheckKind::AwaitOutsideAsync,
|
||||
CheckCode::PLR0206 => CheckKind::PropertyWithParameters,
|
||||
CheckCode::PLR1701 => {
|
||||
CheckKind::ConsiderMergingIsinstance("...".to_string(), vec!["...".to_string()])
|
||||
}
|
||||
// flake8-builtins
|
||||
CheckCode::A001 => CheckKind::BuiltinVariableShadowing("...".to_string()),
|
||||
CheckCode::A002 => CheckKind::BuiltinArgumentShadowing("...".to_string()),
|
||||
@@ -831,6 +946,15 @@ impl CheckCode {
|
||||
CheckCode::T100 => CheckKind::Debugger(DebuggerUsingType::Import("...".to_string())),
|
||||
// flake8-tidy-imports
|
||||
CheckCode::I252 => CheckKind::BannedRelativeImport(Strictness::All),
|
||||
// flake8-return
|
||||
CheckCode::RET501 => CheckKind::UnnecessaryReturnNone,
|
||||
CheckCode::RET502 => CheckKind::ImplicitReturnValue,
|
||||
CheckCode::RET503 => CheckKind::ImplicitReturn,
|
||||
CheckCode::RET504 => CheckKind::UnnecessaryAssign,
|
||||
CheckCode::RET505 => CheckKind::SuperfluousElseReturn(Branch::Else),
|
||||
CheckCode::RET506 => CheckKind::SuperfluousElseRaise(Branch::Else),
|
||||
CheckCode::RET507 => CheckKind::SuperfluousElseContinue(Branch::Else),
|
||||
CheckCode::RET508 => CheckKind::SuperfluousElseBreak(Branch::Else),
|
||||
// flake8-print
|
||||
CheckCode::T201 => CheckKind::PrintFound,
|
||||
CheckCode::T203 => CheckKind::PPrintFound,
|
||||
@@ -975,6 +1099,8 @@ impl CheckCode {
|
||||
CheckCode::FBT001 => CheckKind::BooleanPositionalArgInFunctionDefinition,
|
||||
CheckCode::FBT002 => CheckKind::BooleanDefaultValueInFunctionDefinition,
|
||||
CheckCode::FBT003 => CheckKind::BooleanPositionalValueInFunctionCall,
|
||||
// pygrep-hooks
|
||||
CheckCode::PGH001 => CheckKind::NoEval,
|
||||
// Ruff
|
||||
CheckCode::RUF001 => CheckKind::AmbiguousUnicodeCharacterString('𝐁', 'B'),
|
||||
CheckCode::RUF002 => CheckKind::AmbiguousUnicodeCharacterDocstring('𝐁', 'B'),
|
||||
@@ -1169,11 +1295,23 @@ impl CheckCode {
|
||||
CheckCode::N816 => CheckCategory::PEP8Naming,
|
||||
CheckCode::N817 => CheckCategory::PEP8Naming,
|
||||
CheckCode::N818 => CheckCategory::PEP8Naming,
|
||||
CheckCode::PGH001 => CheckCategory::PygrepHooks,
|
||||
CheckCode::PLC3002 => CheckCategory::Pylint,
|
||||
CheckCode::PLE1142 => CheckCategory::Pylint,
|
||||
CheckCode::PLR0206 => CheckCategory::Pylint,
|
||||
CheckCode::PLR1701 => CheckCategory::Pylint,
|
||||
CheckCode::Q000 => CheckCategory::Flake8Quotes,
|
||||
CheckCode::Q001 => CheckCategory::Flake8Quotes,
|
||||
CheckCode::Q002 => CheckCategory::Flake8Quotes,
|
||||
CheckCode::Q003 => CheckCategory::Flake8Quotes,
|
||||
CheckCode::RET501 => CheckCategory::Flake8Return,
|
||||
CheckCode::RET502 => CheckCategory::Flake8Return,
|
||||
CheckCode::RET503 => CheckCategory::Flake8Return,
|
||||
CheckCode::RET504 => CheckCategory::Flake8Return,
|
||||
CheckCode::RET505 => CheckCategory::Flake8Return,
|
||||
CheckCode::RET506 => CheckCategory::Flake8Return,
|
||||
CheckCode::RET507 => CheckCategory::Flake8Return,
|
||||
CheckCode::RET508 => CheckCategory::Flake8Return,
|
||||
CheckCode::RUF001 => CheckCategory::Ruff,
|
||||
CheckCode::RUF002 => CheckCategory::Ruff,
|
||||
CheckCode::RUF003 => CheckCategory::Ruff,
|
||||
@@ -1281,8 +1419,11 @@ impl CheckKind {
|
||||
// pycodestyle warnings
|
||||
CheckKind::NoNewLineAtEndOfFile => &CheckCode::W292,
|
||||
CheckKind::InvalidEscapeSequence(_) => &CheckCode::W605,
|
||||
// pylint errors
|
||||
// pylint
|
||||
CheckKind::AwaitOutsideAsync => &CheckCode::PLE1142,
|
||||
CheckKind::ConsiderMergingIsinstance(..) => &CheckCode::PLR1701,
|
||||
CheckKind::PropertyWithParameters => &CheckCode::PLR0206,
|
||||
CheckKind::UnnecessaryDirectLambdaCall => &CheckCode::PLC3002,
|
||||
// flake8-builtins
|
||||
CheckKind::BuiltinVariableShadowing(_) => &CheckCode::A001,
|
||||
CheckKind::BuiltinArgumentShadowing(_) => &CheckCode::A002,
|
||||
@@ -1338,6 +1479,15 @@ impl CheckKind {
|
||||
CheckKind::Debugger(_) => &CheckCode::T100,
|
||||
// flake8-tidy-imports
|
||||
CheckKind::BannedRelativeImport(_) => &CheckCode::I252,
|
||||
// flake8-return
|
||||
CheckKind::UnnecessaryReturnNone => &CheckCode::RET501,
|
||||
CheckKind::ImplicitReturnValue => &CheckCode::RET502,
|
||||
CheckKind::ImplicitReturn => &CheckCode::RET503,
|
||||
CheckKind::UnnecessaryAssign => &CheckCode::RET504,
|
||||
CheckKind::SuperfluousElseReturn(_) => &CheckCode::RET505,
|
||||
CheckKind::SuperfluousElseRaise(_) => &CheckCode::RET506,
|
||||
CheckKind::SuperfluousElseContinue(_) => &CheckCode::RET507,
|
||||
CheckKind::SuperfluousElseBreak(_) => &CheckCode::RET508,
|
||||
// flake8-print
|
||||
CheckKind::PrintFound => &CheckCode::T201,
|
||||
CheckKind::PPrintFound => &CheckCode::T203,
|
||||
@@ -1456,12 +1606,14 @@ impl CheckKind {
|
||||
CheckKind::HardcodedPasswordString(..) => &CheckCode::S105,
|
||||
CheckKind::HardcodedPasswordFuncArg(..) => &CheckCode::S106,
|
||||
CheckKind::HardcodedPasswordDefault(..) => &CheckCode::S107,
|
||||
// McCabe
|
||||
// mccabe
|
||||
CheckKind::FunctionIsTooComplex(..) => &CheckCode::C901,
|
||||
// flake8-boolean-trap
|
||||
CheckKind::BooleanPositionalArgInFunctionDefinition => &CheckCode::FBT001,
|
||||
CheckKind::BooleanDefaultValueInFunctionDefinition => &CheckCode::FBT002,
|
||||
CheckKind::BooleanPositionalValueInFunctionCall => &CheckCode::FBT003,
|
||||
// pygrep-hooks
|
||||
CheckKind::NoEval => &CheckCode::PGH001,
|
||||
// Ruff
|
||||
CheckKind::AmbiguousUnicodeCharacterString(..) => &CheckCode::RUF001,
|
||||
CheckKind::AmbiguousUnicodeCharacterDocstring(..) => &CheckCode::RUF002,
|
||||
@@ -1652,7 +1804,17 @@ impl CheckKind {
|
||||
CheckKind::InvalidEscapeSequence(char) => {
|
||||
format!("Invalid escape sequence: '\\{char}'")
|
||||
}
|
||||
// pylint errors
|
||||
// pylint
|
||||
CheckKind::ConsiderMergingIsinstance(obj, types) => {
|
||||
let types = types.join(", ");
|
||||
format!("Consider merging these isinstance calls: `isinstance({obj}, ({types}))`")
|
||||
}
|
||||
CheckKind::UnnecessaryDirectLambdaCall => "Lambda expression called directly. Execute \
|
||||
the expression inline instead."
|
||||
.to_string(),
|
||||
CheckKind::PropertyWithParameters => {
|
||||
"Cannot have defined parameters for properties".to_string()
|
||||
}
|
||||
CheckKind::AwaitOutsideAsync => {
|
||||
"`await` should be used within an async function".to_string()
|
||||
}
|
||||
@@ -1866,6 +2028,31 @@ impl CheckKind {
|
||||
}
|
||||
Strictness::All => "Relative imports are banned".to_string(),
|
||||
},
|
||||
// flake8-return
|
||||
CheckKind::UnnecessaryReturnNone => "Do not explicitly `return None` in function if \
|
||||
it is the only possible return value"
|
||||
.to_string(),
|
||||
CheckKind::ImplicitReturnValue => "Do not implicitly `return None` in function able \
|
||||
to return non-`None` value"
|
||||
.to_string(),
|
||||
CheckKind::ImplicitReturn => "Missing explicit `return` at the end of function able \
|
||||
to return non-`None` value"
|
||||
.to_string(),
|
||||
CheckKind::UnnecessaryAssign => {
|
||||
"Unnecessary variable assignment before `return` statement".to_string()
|
||||
}
|
||||
CheckKind::SuperfluousElseReturn(branch) => {
|
||||
format!("Unnecessary `{branch}` after `return` statement")
|
||||
}
|
||||
CheckKind::SuperfluousElseRaise(branch) => {
|
||||
format!("Unnecessary `{branch}` after `raise` statement")
|
||||
}
|
||||
CheckKind::SuperfluousElseContinue(branch) => {
|
||||
format!("Unnecessary `{branch}` after `continue` statement")
|
||||
}
|
||||
CheckKind::SuperfluousElseBreak(branch) => {
|
||||
format!("Unnecessary `{branch}` after `break` statement")
|
||||
}
|
||||
// flake8-print
|
||||
CheckKind::PrintFound => "`print` found".to_string(),
|
||||
CheckKind::PPrintFound => "`pprint` found".to_string(),
|
||||
@@ -2183,7 +2370,7 @@ impl CheckKind {
|
||||
}
|
||||
// flake8-blind-except
|
||||
CheckKind::BlindExcept => "Blind except Exception: statement".to_string(),
|
||||
// McCabe
|
||||
// mccabe
|
||||
CheckKind::FunctionIsTooComplex(name, complexity) => {
|
||||
format!("`{name}` is too complex ({complexity})")
|
||||
}
|
||||
@@ -2197,6 +2384,8 @@ impl CheckKind {
|
||||
CheckKind::BooleanPositionalValueInFunctionCall => {
|
||||
"Boolean positional value in function call".to_string()
|
||||
}
|
||||
// pygrep-hooks
|
||||
CheckKind::NoEval => "No builtin `eval()` allowed".to_string(),
|
||||
// Ruff
|
||||
CheckKind::AmbiguousUnicodeCharacterString(confusable, representant) => {
|
||||
format!(
|
||||
@@ -2280,6 +2469,8 @@ impl CheckKind {
|
||||
| CheckKind::DoNotAssignLambda
|
||||
| CheckKind::DuplicateHandlerException(..)
|
||||
| CheckKind::GetAttrWithConstant
|
||||
| CheckKind::ImplicitReturn
|
||||
| CheckKind::ImplicitReturnValue
|
||||
| CheckKind::IsLiteral
|
||||
| CheckKind::NewLineAfterLastParagraph
|
||||
| CheckKind::NewLineAfterSectionName(..)
|
||||
@@ -2299,6 +2490,7 @@ impl CheckKind {
|
||||
| CheckKind::PPrintFound
|
||||
| CheckKind::PrintFound
|
||||
| CheckKind::RaiseNotImplemented
|
||||
| CheckKind::RedundantOpenModes
|
||||
| CheckKind::RedundantTupleInExceptionHandler(..)
|
||||
| CheckKind::SectionNameEndsInColon(..)
|
||||
| CheckKind::SectionNotOverIndented(..)
|
||||
@@ -2313,7 +2505,6 @@ impl CheckKind {
|
||||
| CheckKind::UnnecessaryComprehension(..)
|
||||
| CheckKind::UnnecessaryEncodeUTF8
|
||||
| CheckKind::UnnecessaryFutureImport(..)
|
||||
| CheckKind::RedundantOpenModes
|
||||
| CheckKind::UnnecessaryGeneratorDict
|
||||
| CheckKind::UnnecessaryGeneratorList
|
||||
| CheckKind::UnnecessaryGeneratorSet
|
||||
@@ -2325,6 +2516,7 @@ impl CheckKind {
|
||||
| CheckKind::UnnecessaryLiteralSet(..)
|
||||
| CheckKind::UnnecessaryLiteralWithinListCall(..)
|
||||
| CheckKind::UnnecessaryLiteralWithinTupleCall(..)
|
||||
| CheckKind::UnnecessaryReturnNone
|
||||
| CheckKind::UnsortedImports
|
||||
| CheckKind::UnusedImport(_, false)
|
||||
| CheckKind::UnusedLoopControlVariable(..)
|
||||
|
||||
@@ -278,11 +278,29 @@ pub enum CheckCodePrefix {
|
||||
N816,
|
||||
N817,
|
||||
N818,
|
||||
PGH,
|
||||
PGH0,
|
||||
PGH00,
|
||||
PGH001,
|
||||
PLC,
|
||||
PLC3,
|
||||
PLC30,
|
||||
PLC300,
|
||||
PLC3002,
|
||||
PLE,
|
||||
PLE1,
|
||||
PLE11,
|
||||
PLE114,
|
||||
PLE1142,
|
||||
PLR,
|
||||
PLR0,
|
||||
PLR02,
|
||||
PLR020,
|
||||
PLR0206,
|
||||
PLR1,
|
||||
PLR17,
|
||||
PLR170,
|
||||
PLR1701,
|
||||
Q,
|
||||
Q0,
|
||||
Q00,
|
||||
@@ -290,6 +308,17 @@ pub enum CheckCodePrefix {
|
||||
Q001,
|
||||
Q002,
|
||||
Q003,
|
||||
RET,
|
||||
RET5,
|
||||
RET50,
|
||||
RET501,
|
||||
RET502,
|
||||
RET503,
|
||||
RET504,
|
||||
RET505,
|
||||
RET506,
|
||||
RET507,
|
||||
RET508,
|
||||
RUF,
|
||||
RUF0,
|
||||
RUF00,
|
||||
@@ -1148,11 +1177,29 @@ impl CheckCodePrefix {
|
||||
CheckCodePrefix::N816 => vec![CheckCode::N816],
|
||||
CheckCodePrefix::N817 => vec![CheckCode::N817],
|
||||
CheckCodePrefix::N818 => vec![CheckCode::N818],
|
||||
CheckCodePrefix::PGH => vec![CheckCode::PGH001],
|
||||
CheckCodePrefix::PGH0 => vec![CheckCode::PGH001],
|
||||
CheckCodePrefix::PGH00 => vec![CheckCode::PGH001],
|
||||
CheckCodePrefix::PGH001 => vec![CheckCode::PGH001],
|
||||
CheckCodePrefix::PLC => vec![CheckCode::PLC3002],
|
||||
CheckCodePrefix::PLC3 => vec![CheckCode::PLC3002],
|
||||
CheckCodePrefix::PLC30 => vec![CheckCode::PLC3002],
|
||||
CheckCodePrefix::PLC300 => vec![CheckCode::PLC3002],
|
||||
CheckCodePrefix::PLC3002 => vec![CheckCode::PLC3002],
|
||||
CheckCodePrefix::PLE => vec![CheckCode::PLE1142],
|
||||
CheckCodePrefix::PLE1 => vec![CheckCode::PLE1142],
|
||||
CheckCodePrefix::PLE11 => vec![CheckCode::PLE1142],
|
||||
CheckCodePrefix::PLE114 => vec![CheckCode::PLE1142],
|
||||
CheckCodePrefix::PLE1142 => vec![CheckCode::PLE1142],
|
||||
CheckCodePrefix::PLR => vec![CheckCode::PLR1701, CheckCode::PLR0206],
|
||||
CheckCodePrefix::PLR0 => vec![CheckCode::PLR0206],
|
||||
CheckCodePrefix::PLR02 => vec![CheckCode::PLR0206],
|
||||
CheckCodePrefix::PLR020 => vec![CheckCode::PLR0206],
|
||||
CheckCodePrefix::PLR0206 => vec![CheckCode::PLR0206],
|
||||
CheckCodePrefix::PLR1 => vec![CheckCode::PLR1701],
|
||||
CheckCodePrefix::PLR17 => vec![CheckCode::PLR1701],
|
||||
CheckCodePrefix::PLR170 => vec![CheckCode::PLR1701],
|
||||
CheckCodePrefix::PLR1701 => vec![CheckCode::PLR1701],
|
||||
CheckCodePrefix::Q => vec![
|
||||
CheckCode::Q000,
|
||||
CheckCode::Q001,
|
||||
@@ -1175,6 +1222,44 @@ impl CheckCodePrefix {
|
||||
CheckCodePrefix::Q001 => vec![CheckCode::Q001],
|
||||
CheckCodePrefix::Q002 => vec![CheckCode::Q002],
|
||||
CheckCodePrefix::Q003 => vec![CheckCode::Q003],
|
||||
CheckCodePrefix::RET => vec![
|
||||
CheckCode::RET501,
|
||||
CheckCode::RET502,
|
||||
CheckCode::RET503,
|
||||
CheckCode::RET504,
|
||||
CheckCode::RET505,
|
||||
CheckCode::RET506,
|
||||
CheckCode::RET507,
|
||||
CheckCode::RET508,
|
||||
],
|
||||
CheckCodePrefix::RET5 => vec![
|
||||
CheckCode::RET501,
|
||||
CheckCode::RET502,
|
||||
CheckCode::RET503,
|
||||
CheckCode::RET504,
|
||||
CheckCode::RET505,
|
||||
CheckCode::RET506,
|
||||
CheckCode::RET507,
|
||||
CheckCode::RET508,
|
||||
],
|
||||
CheckCodePrefix::RET50 => vec![
|
||||
CheckCode::RET501,
|
||||
CheckCode::RET502,
|
||||
CheckCode::RET503,
|
||||
CheckCode::RET504,
|
||||
CheckCode::RET505,
|
||||
CheckCode::RET506,
|
||||
CheckCode::RET507,
|
||||
CheckCode::RET508,
|
||||
],
|
||||
CheckCodePrefix::RET501 => vec![CheckCode::RET501],
|
||||
CheckCodePrefix::RET502 => vec![CheckCode::RET502],
|
||||
CheckCodePrefix::RET503 => vec![CheckCode::RET503],
|
||||
CheckCodePrefix::RET504 => vec![CheckCode::RET504],
|
||||
CheckCodePrefix::RET505 => vec![CheckCode::RET505],
|
||||
CheckCodePrefix::RET506 => vec![CheckCode::RET506],
|
||||
CheckCodePrefix::RET507 => vec![CheckCode::RET507],
|
||||
CheckCodePrefix::RET508 => vec![CheckCode::RET508],
|
||||
CheckCodePrefix::RUF => vec![
|
||||
CheckCode::RUF001,
|
||||
CheckCode::RUF002,
|
||||
@@ -1615,11 +1700,29 @@ impl CheckCodePrefix {
|
||||
CheckCodePrefix::N816 => SuffixLength::Three,
|
||||
CheckCodePrefix::N817 => SuffixLength::Three,
|
||||
CheckCodePrefix::N818 => SuffixLength::Three,
|
||||
CheckCodePrefix::PGH => SuffixLength::Zero,
|
||||
CheckCodePrefix::PGH0 => SuffixLength::One,
|
||||
CheckCodePrefix::PGH00 => SuffixLength::Two,
|
||||
CheckCodePrefix::PGH001 => SuffixLength::Three,
|
||||
CheckCodePrefix::PLC => SuffixLength::Zero,
|
||||
CheckCodePrefix::PLC3 => SuffixLength::One,
|
||||
CheckCodePrefix::PLC30 => SuffixLength::Two,
|
||||
CheckCodePrefix::PLC300 => SuffixLength::Three,
|
||||
CheckCodePrefix::PLC3002 => SuffixLength::Four,
|
||||
CheckCodePrefix::PLE => SuffixLength::Zero,
|
||||
CheckCodePrefix::PLE1 => SuffixLength::One,
|
||||
CheckCodePrefix::PLE11 => SuffixLength::Two,
|
||||
CheckCodePrefix::PLE114 => SuffixLength::Three,
|
||||
CheckCodePrefix::PLE1142 => SuffixLength::Four,
|
||||
CheckCodePrefix::PLR => SuffixLength::Zero,
|
||||
CheckCodePrefix::PLR0 => SuffixLength::One,
|
||||
CheckCodePrefix::PLR02 => SuffixLength::Two,
|
||||
CheckCodePrefix::PLR020 => SuffixLength::Three,
|
||||
CheckCodePrefix::PLR0206 => SuffixLength::Four,
|
||||
CheckCodePrefix::PLR1 => SuffixLength::One,
|
||||
CheckCodePrefix::PLR17 => SuffixLength::Two,
|
||||
CheckCodePrefix::PLR170 => SuffixLength::Three,
|
||||
CheckCodePrefix::PLR1701 => SuffixLength::Four,
|
||||
CheckCodePrefix::Q => SuffixLength::Zero,
|
||||
CheckCodePrefix::Q0 => SuffixLength::One,
|
||||
CheckCodePrefix::Q00 => SuffixLength::Two,
|
||||
@@ -1627,6 +1730,17 @@ impl CheckCodePrefix {
|
||||
CheckCodePrefix::Q001 => SuffixLength::Three,
|
||||
CheckCodePrefix::Q002 => SuffixLength::Three,
|
||||
CheckCodePrefix::Q003 => SuffixLength::Three,
|
||||
CheckCodePrefix::RET => SuffixLength::Zero,
|
||||
CheckCodePrefix::RET5 => SuffixLength::One,
|
||||
CheckCodePrefix::RET50 => SuffixLength::Two,
|
||||
CheckCodePrefix::RET501 => SuffixLength::Three,
|
||||
CheckCodePrefix::RET502 => SuffixLength::Three,
|
||||
CheckCodePrefix::RET503 => SuffixLength::Three,
|
||||
CheckCodePrefix::RET504 => SuffixLength::Three,
|
||||
CheckCodePrefix::RET505 => SuffixLength::Three,
|
||||
CheckCodePrefix::RET506 => SuffixLength::Three,
|
||||
CheckCodePrefix::RET507 => SuffixLength::Three,
|
||||
CheckCodePrefix::RET508 => SuffixLength::Three,
|
||||
CheckCodePrefix::RUF => SuffixLength::Zero,
|
||||
CheckCodePrefix::RUF0 => SuffixLength::One,
|
||||
CheckCodePrefix::RUF00 => SuffixLength::Two,
|
||||
@@ -1713,8 +1827,12 @@ pub const CATEGORIES: &[CheckCodePrefix] = &[
|
||||
CheckCodePrefix::I,
|
||||
CheckCodePrefix::M,
|
||||
CheckCodePrefix::N,
|
||||
CheckCodePrefix::PGH,
|
||||
CheckCodePrefix::PLC,
|
||||
CheckCodePrefix::PLE,
|
||||
CheckCodePrefix::PLR,
|
||||
CheckCodePrefix::Q,
|
||||
CheckCodePrefix::RET,
|
||||
CheckCodePrefix::RUF,
|
||||
CheckCodePrefix::S,
|
||||
CheckCodePrefix::T,
|
||||
|
||||
18
src/flake8_return/helpers.rs
Normal file
18
src/flake8_return/helpers.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
use rustpython_ast::{Constant, Expr, ExprKind, Stmt};
|
||||
|
||||
/// Return `true` if a function's return statement include at least one
|
||||
/// non-`None` value.
|
||||
pub fn result_exists(returns: &[(&Stmt, Option<&Expr>)]) -> bool {
|
||||
returns.iter().any(|(_, expr)| {
|
||||
expr.map(|expr| {
|
||||
!matches!(
|
||||
expr.node,
|
||||
ExprKind::Constant {
|
||||
value: Constant::None,
|
||||
..
|
||||
}
|
||||
)
|
||||
})
|
||||
.unwrap_or(false)
|
||||
})
|
||||
}
|
||||
37
src/flake8_return/mod.rs
Normal file
37
src/flake8_return/mod.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
mod helpers;
|
||||
pub mod plugins;
|
||||
mod visitor;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Result;
|
||||
use test_case::test_case;
|
||||
|
||||
use crate::checks::CheckCode;
|
||||
use crate::linter::test_path;
|
||||
use crate::Settings;
|
||||
|
||||
#[test_case(CheckCode::RET501, Path::new("RET501.py"); "RET501")]
|
||||
#[test_case(CheckCode::RET502, Path::new("RET502.py"); "RET502")]
|
||||
#[test_case(CheckCode::RET503, Path::new("RET503.py"); "RET503")]
|
||||
#[test_case(CheckCode::RET504, Path::new("RET504.py"); "RET504")]
|
||||
#[test_case(CheckCode::RET505, Path::new("RET505.py"); "RET505")]
|
||||
#[test_case(CheckCode::RET506, Path::new("RET506.py"); "RET506")]
|
||||
#[test_case(CheckCode::RET507, Path::new("RET507.py"); "RET507")]
|
||||
#[test_case(CheckCode::RET508, Path::new("RET508.py"); "RET508")]
|
||||
fn checks(check_code: CheckCode, path: &Path) -> Result<()> {
|
||||
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy());
|
||||
let mut checks = test_path(
|
||||
Path::new("./resources/test/fixtures/flake8_return")
|
||||
.join(path)
|
||||
.as_path(),
|
||||
&Settings::for_rule(check_code),
|
||||
true,
|
||||
)?;
|
||||
checks.sort_by_key(|check| check.location);
|
||||
insta::assert_yaml_snapshot!(snapshot, checks);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
343
src/flake8_return/plugins.rs
Normal file
343
src/flake8_return/plugins.rs
Normal file
@@ -0,0 +1,343 @@
|
||||
use itertools::Itertools;
|
||||
use rustpython_ast::{Constant, Expr, ExprKind, Location, Stmt, StmtKind};
|
||||
|
||||
use crate::ast::types::Range;
|
||||
use crate::ast::visitor::Visitor;
|
||||
use crate::ast::whitespace::indentation;
|
||||
use crate::autofix::Fix;
|
||||
use crate::check_ast::Checker;
|
||||
use crate::checks::{Branch, CheckCode, CheckKind};
|
||||
use crate::flake8_return::helpers::result_exists;
|
||||
use crate::flake8_return::visitor::{ReturnVisitor, Stack};
|
||||
use crate::Check;
|
||||
|
||||
/// RET501
|
||||
fn unnecessary_return_none(checker: &mut Checker, stack: &Stack) {
|
||||
for (stmt, expr) in &stack.returns {
|
||||
if let Some(expr) = expr {
|
||||
if matches!(
|
||||
expr.node,
|
||||
ExprKind::Constant {
|
||||
value: Constant::None,
|
||||
..
|
||||
}
|
||||
) {
|
||||
let mut check =
|
||||
Check::new(CheckKind::UnnecessaryReturnNone, Range::from_located(stmt));
|
||||
if checker.patch(&CheckCode::RET501) {
|
||||
check.amend(Fix::replacement(
|
||||
"return".to_string(),
|
||||
stmt.location,
|
||||
stmt.end_location.unwrap(),
|
||||
));
|
||||
}
|
||||
checker.add_check(check);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// RET502
|
||||
fn implicit_return_value(checker: &mut Checker, stack: &Stack) {
|
||||
for (stmt, expr) in &stack.returns {
|
||||
if expr.is_none() {
|
||||
let mut check = Check::new(CheckKind::ImplicitReturnValue, Range::from_located(stmt));
|
||||
if checker.patch(&CheckCode::RET502) {
|
||||
check.amend(Fix::replacement(
|
||||
"return None".to_string(),
|
||||
stmt.location,
|
||||
stmt.end_location.unwrap(),
|
||||
));
|
||||
}
|
||||
checker.add_check(check);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// RET503
|
||||
fn implicit_return(checker: &mut Checker, last_stmt: &Stmt) {
|
||||
match &last_stmt.node {
|
||||
StmtKind::If { body, orelse, .. } => {
|
||||
if body.is_empty() || orelse.is_empty() {
|
||||
checker.add_check(Check::new(
|
||||
CheckKind::ImplicitReturn,
|
||||
Range::from_located(last_stmt),
|
||||
));
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(last_stmt) = body.last() {
|
||||
implicit_return(checker, last_stmt);
|
||||
}
|
||||
if let Some(last_stmt) = orelse.last() {
|
||||
implicit_return(checker, last_stmt);
|
||||
}
|
||||
}
|
||||
StmtKind::For { body, orelse, .. } | StmtKind::AsyncFor { body, orelse, .. } => {
|
||||
if let Some(last_stmt) = orelse.last() {
|
||||
implicit_return(checker, last_stmt);
|
||||
} else if let Some(last_stmt) = body.last() {
|
||||
implicit_return(checker, last_stmt);
|
||||
}
|
||||
}
|
||||
StmtKind::With { body, .. } | StmtKind::AsyncWith { body, .. } => {
|
||||
if let Some(last_stmt) = body.last() {
|
||||
implicit_return(checker, last_stmt);
|
||||
}
|
||||
}
|
||||
StmtKind::Assert { test, .. }
|
||||
if matches!(
|
||||
test.node,
|
||||
ExprKind::Constant {
|
||||
value: Constant::Bool(false),
|
||||
..
|
||||
}
|
||||
) => {}
|
||||
StmtKind::Return { .. }
|
||||
| StmtKind::While { .. }
|
||||
| StmtKind::Raise { .. }
|
||||
| StmtKind::Try { .. } => {}
|
||||
_ => {
|
||||
let mut check = Check::new(CheckKind::ImplicitReturn, Range::from_located(last_stmt));
|
||||
if checker.patch(&CheckCode::RET503) {
|
||||
let mut content = String::new();
|
||||
content.push_str(&indentation(checker, last_stmt));
|
||||
content.push_str("return None");
|
||||
content.push('\n');
|
||||
check.amend(Fix::insertion(
|
||||
content,
|
||||
Location::new(last_stmt.end_location.unwrap().row() + 1, 0),
|
||||
));
|
||||
}
|
||||
checker.add_check(check);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn has_refs_before_next_assign(id: &str, return_location: Location, stack: &Stack) -> bool {
|
||||
let mut before_assign: &Location = &Location::default();
|
||||
let mut after_assign: Option<&Location> = None;
|
||||
if let Some(assigns) = stack.assigns.get(&id) {
|
||||
for location in assigns.iter().sorted() {
|
||||
if location.row() > return_location.row() {
|
||||
after_assign = Some(location);
|
||||
break;
|
||||
}
|
||||
if location.row() <= return_location.row() {
|
||||
before_assign = location;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(refs) = stack.refs.get(&id) {
|
||||
for location in refs {
|
||||
if location.row() == return_location.row() {
|
||||
continue;
|
||||
}
|
||||
if let Some(after_assign) = after_assign {
|
||||
if before_assign.row() < location.row() && location.row() <= after_assign.row() {
|
||||
return true;
|
||||
}
|
||||
} else if before_assign.row() < location.row() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn has_refs_or_assigns_within_try_or_loop(id: &str, stack: &Stack) -> bool {
|
||||
if let Some(refs) = stack.refs.get(&id) {
|
||||
for location in refs {
|
||||
for (try_location, try_end_location) in &stack.tries {
|
||||
if try_location.row() < location.row() && location.row() <= try_end_location.row() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for (loop_location, loop_end_location) in &stack.loops {
|
||||
if loop_location.row() < location.row() && location.row() <= loop_end_location.row()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(refs) = stack.assigns.get(&id) {
|
||||
for location in refs {
|
||||
for (try_location, try_end_location) in &stack.tries {
|
||||
if try_location.row() < location.row() && location.row() <= try_end_location.row() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for (loop_location, loop_end_location) in &stack.loops {
|
||||
if loop_location.row() < location.row() && location.row() <= loop_end_location.row()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// RET504
|
||||
fn unnecessary_assign(checker: &mut Checker, stack: &Stack, expr: &Expr) {
|
||||
if let ExprKind::Name { id, .. } = &expr.node {
|
||||
if !stack.assigns.contains_key(id.as_str()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if !stack.refs.contains_key(id.as_str()) {
|
||||
checker.add_check(Check::new(
|
||||
CheckKind::UnnecessaryAssign,
|
||||
Range::from_located(expr),
|
||||
));
|
||||
return;
|
||||
}
|
||||
|
||||
if has_refs_before_next_assign(id, expr.location, stack)
|
||||
|| has_refs_or_assigns_within_try_or_loop(id, stack)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
checker.add_check(Check::new(
|
||||
CheckKind::UnnecessaryAssign,
|
||||
Range::from_located(expr),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// RET505, RET506, RET507, RET508
|
||||
fn superfluous_else_node(checker: &mut Checker, stmt: &Stmt, branch: Branch) -> bool {
|
||||
if let StmtKind::If { body, .. } = &stmt.node {
|
||||
for child in body {
|
||||
if matches!(child.node, StmtKind::Return { .. }) {
|
||||
if checker.settings.enabled.contains(&CheckCode::RET505) {
|
||||
checker.add_check(Check::new(
|
||||
CheckKind::SuperfluousElseReturn(branch),
|
||||
Range::from_located(stmt),
|
||||
));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if matches!(child.node, StmtKind::Break) {
|
||||
if checker.settings.enabled.contains(&CheckCode::RET508) {
|
||||
checker.add_check(Check::new(
|
||||
CheckKind::SuperfluousElseBreak(branch),
|
||||
Range::from_located(stmt),
|
||||
));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if matches!(child.node, StmtKind::Raise { .. }) {
|
||||
if checker.settings.enabled.contains(&CheckCode::RET506) {
|
||||
checker.add_check(Check::new(
|
||||
CheckKind::SuperfluousElseRaise(branch),
|
||||
Range::from_located(stmt),
|
||||
));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if matches!(child.node, StmtKind::Continue) {
|
||||
if checker.settings.enabled.contains(&CheckCode::RET507) {
|
||||
checker.add_check(Check::new(
|
||||
CheckKind::SuperfluousElseContinue(branch),
|
||||
Range::from_located(stmt),
|
||||
));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// RET505, RET506, RET507, RET508
|
||||
fn superfluous_elif(checker: &mut Checker, stack: &Stack) -> bool {
|
||||
for stmt in &stack.elifs {
|
||||
if superfluous_else_node(checker, stmt, Branch::Elif) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// RET505, RET506, RET507, RET508
|
||||
fn superfluous_else(checker: &mut Checker, stack: &Stack) -> bool {
|
||||
for stmt in &stack.ifs {
|
||||
if let StmtKind::If { orelse, .. } = &stmt.node {
|
||||
if !orelse.is_empty() {
|
||||
if superfluous_else_node(checker, stmt, Branch::Else) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Run all checks from the `flake8-return` plugin.
|
||||
pub fn function(checker: &mut Checker, body: &[Stmt]) {
|
||||
// Skip empty functions.
|
||||
if body.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Find the last statement in the function.
|
||||
let last_stmt = body.last().unwrap();
|
||||
|
||||
// Skip functions that consist of a single return statement.
|
||||
if body.len() == 1 && matches!(last_stmt.node, StmtKind::Return { .. }) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Traverse the function body, to collect the stack.
|
||||
let stack = {
|
||||
let mut visitor = ReturnVisitor::default();
|
||||
for stmt in body {
|
||||
visitor.visit_stmt(stmt);
|
||||
}
|
||||
visitor.stack
|
||||
};
|
||||
|
||||
if checker.settings.enabled.contains(&CheckCode::RET505)
|
||||
|| checker.settings.enabled.contains(&CheckCode::RET506)
|
||||
|| checker.settings.enabled.contains(&CheckCode::RET507)
|
||||
|| checker.settings.enabled.contains(&CheckCode::RET508)
|
||||
{
|
||||
if superfluous_elif(checker, &stack) {
|
||||
return;
|
||||
}
|
||||
if superfluous_else(checker, &stack) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Skip any functions without return statements.
|
||||
if stack.returns.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
if !result_exists(&stack.returns) {
|
||||
if checker.settings.enabled.contains(&CheckCode::RET501) {
|
||||
unnecessary_return_none(checker, &stack);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if checker.settings.enabled.contains(&CheckCode::RET502) {
|
||||
implicit_return_value(checker, &stack);
|
||||
}
|
||||
if checker.settings.enabled.contains(&CheckCode::RET503) {
|
||||
implicit_return(checker, last_stmt);
|
||||
}
|
||||
|
||||
if checker.settings.enabled.contains(&CheckCode::RET504) {
|
||||
for (_, expr) in &stack.returns {
|
||||
if let Some(expr) = expr {
|
||||
unnecessary_assign(checker, &stack, expr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
source: src/flake8_return/mod.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: UnnecessaryReturnNone
|
||||
location:
|
||||
row: 4
|
||||
column: 4
|
||||
end_location:
|
||||
row: 4
|
||||
column: 15
|
||||
fix:
|
||||
content: return
|
||||
location:
|
||||
row: 4
|
||||
column: 4
|
||||
end_location:
|
||||
row: 4
|
||||
column: 15
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
source: src/flake8_return/mod.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: ImplicitReturnValue
|
||||
location:
|
||||
row: 3
|
||||
column: 8
|
||||
end_location:
|
||||
row: 3
|
||||
column: 14
|
||||
fix:
|
||||
content: return None
|
||||
location:
|
||||
row: 3
|
||||
column: 8
|
||||
end_location:
|
||||
row: 3
|
||||
column: 14
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
source: src/flake8_return/mod.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: ImplicitReturn
|
||||
location:
|
||||
row: 7
|
||||
column: 4
|
||||
end_location:
|
||||
row: 12
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind: ImplicitReturn
|
||||
location:
|
||||
row: 14
|
||||
column: 8
|
||||
end_location:
|
||||
row: 14
|
||||
column: 15
|
||||
fix:
|
||||
content: " return None\n"
|
||||
location:
|
||||
row: 15
|
||||
column: 0
|
||||
end_location:
|
||||
row: 15
|
||||
column: 0
|
||||
- kind: ImplicitReturn
|
||||
location:
|
||||
row: 23
|
||||
column: 4
|
||||
end_location:
|
||||
row: 23
|
||||
column: 11
|
||||
fix:
|
||||
content: " return None\n"
|
||||
location:
|
||||
row: 24
|
||||
column: 0
|
||||
end_location:
|
||||
row: 24
|
||||
column: 0
|
||||
- kind: ImplicitReturn
|
||||
location:
|
||||
row: 29
|
||||
column: 8
|
||||
end_location:
|
||||
row: 34
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind: ImplicitReturn
|
||||
location:
|
||||
row: 39
|
||||
column: 8
|
||||
end_location:
|
||||
row: 39
|
||||
column: 15
|
||||
fix:
|
||||
content: " return None\n"
|
||||
location:
|
||||
row: 40
|
||||
column: 0
|
||||
end_location:
|
||||
row: 40
|
||||
column: 0
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
---
|
||||
source: src/flake8_return/mod.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: UnnecessaryAssign
|
||||
location:
|
||||
row: 6
|
||||
column: 11
|
||||
end_location:
|
||||
row: 6
|
||||
column: 12
|
||||
fix: ~
|
||||
- kind: UnnecessaryAssign
|
||||
location:
|
||||
row: 12
|
||||
column: 11
|
||||
end_location:
|
||||
row: 12
|
||||
column: 12
|
||||
fix: ~
|
||||
- kind: UnnecessaryAssign
|
||||
location:
|
||||
row: 18
|
||||
column: 11
|
||||
end_location:
|
||||
row: 18
|
||||
column: 12
|
||||
fix: ~
|
||||
- kind: UnnecessaryAssign
|
||||
location:
|
||||
row: 25
|
||||
column: 11
|
||||
end_location:
|
||||
row: 25
|
||||
column: 12
|
||||
fix: ~
|
||||
- kind: UnnecessaryAssign
|
||||
location:
|
||||
row: 31
|
||||
column: 15
|
||||
end_location:
|
||||
row: 31
|
||||
column: 16
|
||||
fix: ~
|
||||
- kind: UnnecessaryAssign
|
||||
location:
|
||||
row: 43
|
||||
column: 11
|
||||
end_location:
|
||||
row: 43
|
||||
column: 17
|
||||
fix: ~
|
||||
- kind: UnnecessaryAssign
|
||||
location:
|
||||
row: 51
|
||||
column: 11
|
||||
end_location:
|
||||
row: 51
|
||||
column: 20
|
||||
fix: ~
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
---
|
||||
source: src/flake8_return/mod.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
SuperfluousElseReturn: Elif
|
||||
location:
|
||||
row: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 16
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseReturn: Elif
|
||||
location:
|
||||
row: 17
|
||||
column: 4
|
||||
end_location:
|
||||
row: 27
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseReturn: Elif
|
||||
location:
|
||||
row: 38
|
||||
column: 4
|
||||
end_location:
|
||||
row: 49
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseReturn: Else
|
||||
location:
|
||||
row: 50
|
||||
column: 4
|
||||
end_location:
|
||||
row: 58
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseReturn: Else
|
||||
location:
|
||||
row: 61
|
||||
column: 8
|
||||
end_location:
|
||||
row: 67
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseReturn: Else
|
||||
location:
|
||||
row: 73
|
||||
column: 4
|
||||
end_location:
|
||||
row: 81
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseReturn: Else
|
||||
location:
|
||||
row: 86
|
||||
column: 8
|
||||
end_location:
|
||||
row: 91
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseReturn: Else
|
||||
location:
|
||||
row: 97
|
||||
column: 4
|
||||
end_location:
|
||||
row: 109
|
||||
column: 0
|
||||
fix: ~
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
source: src/flake8_return/mod.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
SuperfluousElseRaise: Elif
|
||||
location:
|
||||
row: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 16
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseRaise: Elif
|
||||
location:
|
||||
row: 17
|
||||
column: 4
|
||||
end_location:
|
||||
row: 27
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseRaise: Else
|
||||
location:
|
||||
row: 31
|
||||
column: 4
|
||||
end_location:
|
||||
row: 39
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseRaise: Else
|
||||
location:
|
||||
row: 42
|
||||
column: 8
|
||||
end_location:
|
||||
row: 48
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseRaise: Else
|
||||
location:
|
||||
row: 54
|
||||
column: 4
|
||||
end_location:
|
||||
row: 62
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseRaise: Else
|
||||
location:
|
||||
row: 67
|
||||
column: 8
|
||||
end_location:
|
||||
row: 72
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseRaise: Else
|
||||
location:
|
||||
row: 78
|
||||
column: 4
|
||||
end_location:
|
||||
row: 90
|
||||
column: 0
|
||||
fix: ~
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
source: src/flake8_return/mod.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
SuperfluousElseContinue: Elif
|
||||
location:
|
||||
row: 6
|
||||
column: 8
|
||||
end_location:
|
||||
row: 14
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseContinue: Elif
|
||||
location:
|
||||
row: 16
|
||||
column: 8
|
||||
end_location:
|
||||
row: 26
|
||||
column: 8
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseContinue: Else
|
||||
location:
|
||||
row: 34
|
||||
column: 8
|
||||
end_location:
|
||||
row: 40
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseContinue: Else
|
||||
location:
|
||||
row: 44
|
||||
column: 12
|
||||
end_location:
|
||||
row: 50
|
||||
column: 8
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseContinue: Else
|
||||
location:
|
||||
row: 57
|
||||
column: 8
|
||||
end_location:
|
||||
row: 65
|
||||
column: 8
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseContinue: Else
|
||||
location:
|
||||
row: 71
|
||||
column: 12
|
||||
end_location:
|
||||
row: 76
|
||||
column: 8
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseContinue: Else
|
||||
location:
|
||||
row: 83
|
||||
column: 8
|
||||
end_location:
|
||||
row: 92
|
||||
column: 0
|
||||
fix: ~
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
source: src/flake8_return/mod.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
SuperfluousElseBreak: Elif
|
||||
location:
|
||||
row: 6
|
||||
column: 8
|
||||
end_location:
|
||||
row: 14
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseBreak: Elif
|
||||
location:
|
||||
row: 16
|
||||
column: 8
|
||||
end_location:
|
||||
row: 26
|
||||
column: 8
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseBreak: Else
|
||||
location:
|
||||
row: 31
|
||||
column: 8
|
||||
end_location:
|
||||
row: 37
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseBreak: Else
|
||||
location:
|
||||
row: 41
|
||||
column: 12
|
||||
end_location:
|
||||
row: 47
|
||||
column: 8
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseBreak: Else
|
||||
location:
|
||||
row: 54
|
||||
column: 8
|
||||
end_location:
|
||||
row: 62
|
||||
column: 8
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseBreak: Else
|
||||
location:
|
||||
row: 68
|
||||
column: 12
|
||||
end_location:
|
||||
row: 73
|
||||
column: 8
|
||||
fix: ~
|
||||
- kind:
|
||||
SuperfluousElseBreak: Else
|
||||
location:
|
||||
row: 80
|
||||
column: 8
|
||||
end_location:
|
||||
row: 92
|
||||
column: 0
|
||||
fix: ~
|
||||
|
||||
119
src/flake8_return/visitor.rs
Normal file
119
src/flake8_return/visitor.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
use rustc_hash::FxHashMap;
|
||||
use rustpython_ast::{Expr, ExprKind, Location, Stmt, StmtKind};
|
||||
|
||||
use crate::ast::visitor;
|
||||
use crate::ast::visitor::Visitor;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Stack<'a> {
|
||||
pub returns: Vec<(&'a Stmt, Option<&'a Expr>)>,
|
||||
pub ifs: Vec<&'a Stmt>,
|
||||
pub elifs: Vec<&'a Stmt>,
|
||||
pub refs: FxHashMap<&'a str, Vec<Location>>,
|
||||
pub assigns: FxHashMap<&'a str, Vec<Location>>,
|
||||
pub loops: Vec<(Location, Location)>,
|
||||
pub tries: Vec<(Location, Location)>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ReturnVisitor<'a> {
|
||||
pub stack: Stack<'a>,
|
||||
}
|
||||
|
||||
impl<'a> ReturnVisitor<'a> {
|
||||
fn visit_assign_target(&mut self, expr: &'a Expr) {
|
||||
match &expr.node {
|
||||
ExprKind::Tuple { elts, .. } => {
|
||||
for elt in elts {
|
||||
self.visit_assign_target(elt);
|
||||
}
|
||||
return;
|
||||
}
|
||||
ExprKind::Name { id, .. } => {
|
||||
self.stack
|
||||
.assigns
|
||||
.entry(id)
|
||||
.or_insert_with(Vec::new)
|
||||
.push(expr.location);
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
visitor::walk_expr(self, expr);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Visitor<'a> for ReturnVisitor<'a> {
|
||||
fn visit_stmt(&mut self, stmt: &'a Stmt) {
|
||||
match &stmt.node {
|
||||
StmtKind::FunctionDef { .. } | StmtKind::AsyncFunctionDef { .. } => {
|
||||
// Don't recurse.
|
||||
}
|
||||
StmtKind::Return { value } => {
|
||||
self.stack
|
||||
.returns
|
||||
.push((stmt, value.as_ref().map(|expr| &**expr)));
|
||||
visitor::walk_stmt(self, stmt);
|
||||
}
|
||||
StmtKind::If { orelse, .. } => {
|
||||
if orelse.len() == 1 && matches!(orelse.first().unwrap().node, StmtKind::If { .. })
|
||||
{
|
||||
self.stack.elifs.push(stmt);
|
||||
} else {
|
||||
self.stack.ifs.push(stmt);
|
||||
}
|
||||
visitor::walk_stmt(self, stmt);
|
||||
}
|
||||
StmtKind::Assign { targets, value, .. } => {
|
||||
if let ExprKind::Name { id, .. } = &value.node {
|
||||
self.stack
|
||||
.refs
|
||||
.entry(id)
|
||||
.or_insert_with(Vec::new)
|
||||
.push(value.location);
|
||||
}
|
||||
|
||||
visitor::walk_expr(self, value);
|
||||
|
||||
if let Some(target) = targets.first() {
|
||||
// Skip unpacking assignments, like `x, y = my_object`.
|
||||
if matches!(target.node, ExprKind::Tuple { .. })
|
||||
&& !matches!(value.node, ExprKind::Tuple { .. })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
self.visit_assign_target(target);
|
||||
}
|
||||
}
|
||||
StmtKind::For { .. } | StmtKind::AsyncFor { .. } | StmtKind::While { .. } => {
|
||||
self.stack
|
||||
.loops
|
||||
.push((stmt.location, stmt.end_location.unwrap()));
|
||||
visitor::walk_stmt(self, stmt);
|
||||
}
|
||||
StmtKind::Try { .. } => {
|
||||
self.stack
|
||||
.tries
|
||||
.push((stmt.location, stmt.end_location.unwrap()));
|
||||
visitor::walk_stmt(self, stmt);
|
||||
}
|
||||
_ => {
|
||||
visitor::walk_stmt(self, stmt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_expr(&mut self, expr: &'a Expr) {
|
||||
match &expr.node {
|
||||
ExprKind::Name { id, .. } => {
|
||||
self.stack
|
||||
.refs
|
||||
.entry(id)
|
||||
.or_insert_with(Vec::new)
|
||||
.push(expr.location);
|
||||
}
|
||||
_ => visitor::walk_expr(self, expr),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,7 @@ mod flake8_comprehensions;
|
||||
mod flake8_debugger;
|
||||
mod flake8_print;
|
||||
pub mod flake8_quotes;
|
||||
mod flake8_return;
|
||||
pub mod flake8_tidy_imports;
|
||||
pub mod fs;
|
||||
mod isort;
|
||||
@@ -65,6 +66,7 @@ pub mod printer;
|
||||
mod pycodestyle;
|
||||
mod pydocstyle;
|
||||
mod pyflakes;
|
||||
mod pygrep_hooks;
|
||||
mod pylint;
|
||||
mod python;
|
||||
mod pyupgrade;
|
||||
|
||||
46
src/noqa.rs
46
src/noqa.rs
@@ -10,7 +10,7 @@ use regex::Regex;
|
||||
|
||||
use crate::checks::{Check, CheckCode};
|
||||
|
||||
static NO_QA_REGEX: Lazy<Regex> = Lazy::new(|| {
|
||||
static NO_QA_LINE_REGEX: Lazy<Regex> = Lazy::new(|| {
|
||||
Regex::new(
|
||||
r"(?P<spaces>\s*)(?P<noqa>(?i:# noqa)(?::\s?(?P<codes>([A-Z]+[0-9]+(?:[,\s]+)?)+))?)",
|
||||
)
|
||||
@@ -18,6 +18,18 @@ static NO_QA_REGEX: Lazy<Regex> = Lazy::new(|| {
|
||||
});
|
||||
static SPLIT_COMMA_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"[,\s]").unwrap());
|
||||
|
||||
/// Return `true` if a file is exempt from checking based on the contents of the
|
||||
/// given line.
|
||||
pub fn is_file_exempt(line: &str) -> bool {
|
||||
let line = line.trim_start();
|
||||
line.starts_with("# flake8: noqa")
|
||||
|| line.starts_with("# flake8: NOQA")
|
||||
|| line.starts_with("# flake8: NoQA")
|
||||
|| line.starts_with("# ruff: noqa")
|
||||
|| line.starts_with("# ruff: NOQA")
|
||||
|| line.starts_with("# ruff: NoQA")
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Directive<'a> {
|
||||
None,
|
||||
@@ -26,7 +38,7 @@ pub enum Directive<'a> {
|
||||
}
|
||||
|
||||
pub fn extract_noqa_directive(line: &str) -> Directive {
|
||||
match NO_QA_REGEX.captures(line) {
|
||||
match NO_QA_LINE_REGEX.captures(line) {
|
||||
Some(caps) => match caps.name("spaces") {
|
||||
Some(spaces) => match caps.name("noqa") {
|
||||
Some(noqa) => match caps.name("codes") {
|
||||
@@ -70,9 +82,13 @@ fn add_noqa_inner(
|
||||
noqa_line_for: &IntMap<usize, usize>,
|
||||
external: &BTreeSet<String>,
|
||||
) -> (usize, String) {
|
||||
let lines: Vec<&str> = contents.lines().collect();
|
||||
let mut matches_by_line: BTreeMap<usize, BTreeSet<&CheckCode>> = BTreeMap::new();
|
||||
for lineno in 0..lines.len() {
|
||||
for (lineno, line) in contents.lines().enumerate() {
|
||||
// If we hit an exemption for the entire file, bail.
|
||||
if is_file_exempt(line) {
|
||||
return (0, contents.to_string());
|
||||
}
|
||||
|
||||
let mut codes: BTreeSet<&CheckCode> = BTreeSet::new();
|
||||
for check in checks {
|
||||
if check.location.row() == lineno + 1 {
|
||||
@@ -93,7 +109,7 @@ fn add_noqa_inner(
|
||||
|
||||
let mut count: usize = 0;
|
||||
let mut output = String::new();
|
||||
for (lineno, line) in lines.iter().enumerate() {
|
||||
for (lineno, line) in contents.lines().enumerate() {
|
||||
match matches_by_line.get(&lineno) {
|
||||
None => {
|
||||
output.push_str(line);
|
||||
@@ -155,7 +171,7 @@ fn add_noqa_inner(
|
||||
output.push('\n');
|
||||
|
||||
// Only count if the new line is an actual edit.
|
||||
if &formatted != line {
|
||||
if formatted != line {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
@@ -176,20 +192,20 @@ mod tests {
|
||||
|
||||
use crate::ast::types::Range;
|
||||
use crate::checks::{Check, CheckKind};
|
||||
use crate::noqa::{add_noqa_inner, NO_QA_REGEX};
|
||||
use crate::noqa::{add_noqa_inner, NO_QA_LINE_REGEX};
|
||||
|
||||
#[test]
|
||||
fn regex() {
|
||||
assert!(NO_QA_REGEX.is_match("# noqa"));
|
||||
assert!(NO_QA_REGEX.is_match("# NoQA"));
|
||||
assert!(NO_QA_LINE_REGEX.is_match("# noqa"));
|
||||
assert!(NO_QA_LINE_REGEX.is_match("# NoQA"));
|
||||
|
||||
assert!(NO_QA_REGEX.is_match("# noqa: F401"));
|
||||
assert!(NO_QA_REGEX.is_match("# NoQA: F401"));
|
||||
assert!(NO_QA_REGEX.is_match("# noqa: F401, E501"));
|
||||
assert!(NO_QA_LINE_REGEX.is_match("# noqa: F401"));
|
||||
assert!(NO_QA_LINE_REGEX.is_match("# NoQA: F401"));
|
||||
assert!(NO_QA_LINE_REGEX.is_match("# noqa: F401, E501"));
|
||||
|
||||
assert!(NO_QA_REGEX.is_match("# noqa:F401"));
|
||||
assert!(NO_QA_REGEX.is_match("# NoQA:F401"));
|
||||
assert!(NO_QA_REGEX.is_match("# noqa:F401, E501"));
|
||||
assert!(NO_QA_LINE_REGEX.is_match("# noqa:F401"));
|
||||
assert!(NO_QA_LINE_REGEX.is_match("# NoQA:F401"));
|
||||
assert!(NO_QA_LINE_REGEX.is_match("# noqa:F401, E501"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
15
src/pygrep_hooks/checks.rs
Normal file
15
src/pygrep_hooks/checks.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
use rustpython_ast::{Expr, ExprKind};
|
||||
|
||||
use crate::ast::types::Range;
|
||||
use crate::check_ast::Checker;
|
||||
use crate::checks::{Check, CheckKind};
|
||||
|
||||
pub fn no_eval(checker: &mut Checker, func: &Expr) {
|
||||
if let ExprKind::Name { id, .. } = &func.node {
|
||||
if id == "eval" {
|
||||
if checker.is_builtin("eval") {
|
||||
checker.add_check(Check::new(CheckKind::NoEval, Range::from_located(func)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
30
src/pygrep_hooks/mod.rs
Normal file
30
src/pygrep_hooks/mod.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
pub mod checks;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::convert::AsRef;
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Result;
|
||||
use test_case::test_case;
|
||||
|
||||
use crate::checks::CheckCode;
|
||||
use crate::linter::test_path;
|
||||
use crate::settings;
|
||||
|
||||
#[test_case(CheckCode::PGH001, Path::new("PGH001_0.py"); "PGH001_0")]
|
||||
#[test_case(CheckCode::PGH001, Path::new("PGH001_1.py"); "PGH001_1")]
|
||||
fn checks(check_code: CheckCode, path: &Path) -> Result<()> {
|
||||
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy());
|
||||
let mut checks = test_path(
|
||||
Path::new("./resources/test/fixtures/pygrep-hooks")
|
||||
.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(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
source: src/pygrep_hooks/mod.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: NoEval
|
||||
location:
|
||||
row: 3
|
||||
column: 0
|
||||
end_location:
|
||||
row: 3
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind: NoEval
|
||||
location:
|
||||
row: 9
|
||||
column: 4
|
||||
end_location:
|
||||
row: 9
|
||||
column: 8
|
||||
fix: ~
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: src/pygrep_hooks/mod.rs
|
||||
expression: checks
|
||||
---
|
||||
[]
|
||||
|
||||
@@ -11,14 +11,17 @@ mod tests {
|
||||
use crate::linter::test_path;
|
||||
use crate::Settings;
|
||||
|
||||
#[test_case(Path::new("await_outside_async.py"))]
|
||||
fn checks(path: &Path) -> Result<()> {
|
||||
#[test_case(CheckCode::PLC3002, Path::new("unnecessary_direct_lambda_call.py"); "PLC3002")]
|
||||
#[test_case(CheckCode::PLE1142, Path::new("await_outside_async.py"); "PLE1142")]
|
||||
#[test_case(CheckCode::PLR0206, Path::new("property_with_parameters.py"); "PLR0206")]
|
||||
#[test_case(CheckCode::PLR1701, Path::new("consider_merging_isinstance.py"); "PLR1701")]
|
||||
fn checks(check_code: CheckCode, path: &Path) -> Result<()> {
|
||||
let snapshot = format!("{}", path.to_string_lossy());
|
||||
let mut checks = test_path(
|
||||
Path::new("./resources/test/fixtures/pylint")
|
||||
.join(path)
|
||||
.as_path(),
|
||||
&Settings::for_rules(vec![CheckCode::PLE1142]),
|
||||
&Settings::for_rules(vec![check_code]),
|
||||
true,
|
||||
)?;
|
||||
checks.sort_by_key(|check| check.location);
|
||||
|
||||
@@ -1,10 +1,22 @@
|
||||
use rustpython_ast::Expr;
|
||||
use itertools::Itertools;
|
||||
use rustc_hash::{FxHashMap, FxHashSet};
|
||||
use rustpython_ast::{Arguments, Boolop, Expr, ExprKind, Stmt};
|
||||
|
||||
use crate::ast::types::{FunctionScope, Range, ScopeKind};
|
||||
use crate::check_ast::Checker;
|
||||
use crate::checks::CheckKind;
|
||||
use crate::Check;
|
||||
|
||||
/// PLC3002
|
||||
pub fn unnecessary_direct_lambda_call(checker: &mut Checker, expr: &Expr, func: &Expr) {
|
||||
if let ExprKind::Lambda { .. } = &func.node {
|
||||
checker.add_check(Check::new(
|
||||
CheckKind::UnnecessaryDirectLambdaCall,
|
||||
Range::from_located(expr),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// PLE1142
|
||||
pub fn await_outside_async(checker: &mut Checker, expr: &Expr) {
|
||||
if !checker
|
||||
@@ -24,3 +36,73 @@ pub fn await_outside_async(checker: &mut Checker, expr: &Expr) {
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// PLR0206
|
||||
pub fn property_with_parameters(
|
||||
checker: &mut Checker,
|
||||
stmt: &Stmt,
|
||||
decorator_list: &[Expr],
|
||||
args: &Arguments,
|
||||
) {
|
||||
if decorator_list
|
||||
.iter()
|
||||
.any(|d| matches!(&d.node, ExprKind::Name { id, .. } if id == "property"))
|
||||
{
|
||||
if checker.is_builtin("property")
|
||||
&& args
|
||||
.args
|
||||
.iter()
|
||||
.chain(args.posonlyargs.iter())
|
||||
.chain(args.kwonlyargs.iter())
|
||||
.count()
|
||||
> 1
|
||||
{
|
||||
checker.add_check(Check::new(
|
||||
CheckKind::PropertyWithParameters,
|
||||
Range::from_located(stmt),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// PLR1701
|
||||
pub fn consider_merging_isinstance(
|
||||
checker: &mut Checker,
|
||||
expr: &Expr,
|
||||
op: &Boolop,
|
||||
values: &[Expr],
|
||||
) {
|
||||
if !matches!(op, Boolop::Or) || !checker.is_builtin("isinstance") {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut obj_to_types: FxHashMap<String, FxHashSet<String>> = FxHashMap::default();
|
||||
for value in values {
|
||||
if let ExprKind::Call { func, args, .. } = &value.node {
|
||||
if matches!(&func.node, ExprKind::Name { id, .. } if id == "isinstance") {
|
||||
if let [obj, types] = &args[..] {
|
||||
obj_to_types
|
||||
.entry(obj.to_string())
|
||||
.or_insert_with(FxHashSet::default)
|
||||
.extend(match &types.node {
|
||||
ExprKind::Tuple { elts, .. } => {
|
||||
elts.iter().map(std::string::ToString::to_string).collect()
|
||||
}
|
||||
_ => {
|
||||
vec![types.to_string()]
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (obj, types) in obj_to_types {
|
||||
if types.len() > 1 {
|
||||
checker.add_check(Check::new(
|
||||
CheckKind::ConsiderMergingIsinstance(obj, types.into_iter().sorted().collect()),
|
||||
Range::from_located(expr),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
---
|
||||
source: src/pylint/mod.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
ConsiderMergingIsinstance:
|
||||
- "var[3]"
|
||||
- - float
|
||||
- int
|
||||
location:
|
||||
row: 15
|
||||
column: 31
|
||||
end_location:
|
||||
row: 15
|
||||
column: 96
|
||||
fix: ~
|
||||
- kind:
|
||||
ConsiderMergingIsinstance:
|
||||
- "var[4]"
|
||||
- - float
|
||||
- int
|
||||
location:
|
||||
row: 17
|
||||
column: 37
|
||||
end_location:
|
||||
row: 17
|
||||
column: 103
|
||||
fix: ~
|
||||
- kind:
|
||||
ConsiderMergingIsinstance:
|
||||
- "var[5]"
|
||||
- - float
|
||||
- int
|
||||
location:
|
||||
row: 19
|
||||
column: 37
|
||||
end_location:
|
||||
row: 19
|
||||
column: 73
|
||||
fix: ~
|
||||
- kind:
|
||||
ConsiderMergingIsinstance:
|
||||
- "var[10]"
|
||||
- - list
|
||||
- str
|
||||
location:
|
||||
row: 23
|
||||
column: 38
|
||||
end_location:
|
||||
row: 23
|
||||
column: 158
|
||||
fix: ~
|
||||
- kind:
|
||||
ConsiderMergingIsinstance:
|
||||
- "var[11]"
|
||||
- - float
|
||||
- int
|
||||
location:
|
||||
row: 24
|
||||
column: 38
|
||||
end_location:
|
||||
row: 24
|
||||
column: 95
|
||||
fix: ~
|
||||
- kind:
|
||||
ConsiderMergingIsinstance:
|
||||
- "var[12]"
|
||||
- - float
|
||||
- int
|
||||
- list
|
||||
location:
|
||||
row: 30
|
||||
column: 47
|
||||
end_location:
|
||||
row: 30
|
||||
column: 75
|
||||
fix: ~
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
source: src/pylint/mod.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: PropertyWithParameters
|
||||
location:
|
||||
row: 7
|
||||
column: 4
|
||||
end_location:
|
||||
row: 10
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind: PropertyWithParameters
|
||||
location:
|
||||
row: 11
|
||||
column: 4
|
||||
end_location:
|
||||
row: 14
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind: PropertyWithParameters
|
||||
location:
|
||||
row: 15
|
||||
column: 4
|
||||
end_location:
|
||||
row: 19
|
||||
column: 0
|
||||
fix: ~
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
source: src/pylint/mod.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: UnnecessaryDirectLambdaCall
|
||||
location:
|
||||
row: 4
|
||||
column: 4
|
||||
end_location:
|
||||
row: 4
|
||||
column: 33
|
||||
fix: ~
|
||||
- kind: UnnecessaryDirectLambdaCall
|
||||
location:
|
||||
row: 5
|
||||
column: 8
|
||||
end_location:
|
||||
row: 5
|
||||
column: 27
|
||||
fix: ~
|
||||
- kind: UnnecessaryDirectLambdaCall
|
||||
location:
|
||||
row: 5
|
||||
column: 29
|
||||
end_location:
|
||||
row: 5
|
||||
column: 47
|
||||
fix: ~
|
||||
|
||||
@@ -50,4 +50,28 @@ mod tests {
|
||||
insta::assert_yaml_snapshot!(checks);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flake8_noqa() -> Result<()> {
|
||||
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);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruff_noqa() -> Result<()> {
|
||||
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);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
6
src/rules/snapshots/ruff__rules__tests__flake8_noqa.snap
Normal file
6
src/rules/snapshots/ruff__rules__tests__flake8_noqa.snap
Normal file
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: src/rules/mod.rs
|
||||
expression: checks
|
||||
---
|
||||
[]
|
||||
|
||||
6
src/rules/snapshots/ruff__rules__tests__ruff_noqa.snap
Normal file
6
src/rules/snapshots/ruff__rules__tests__ruff_noqa.snap
Normal file
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: src/rules/mod.rs
|
||||
expression: checks
|
||||
---
|
||||
[]
|
||||
|
||||
Reference in New Issue
Block a user