Compare commits
70 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4f571ea61 | ||
|
|
4ed88dd245 | ||
|
|
09b926fd59 | ||
|
|
a4869e4974 | ||
|
|
f53c4fc221 | ||
|
|
3892a49a97 | ||
|
|
27cc7e236c | ||
|
|
fa0954fe47 | ||
|
|
a0b50d7ebc | ||
|
|
afe7a04211 | ||
|
|
14806c62ca | ||
|
|
0d0c8730fa | ||
|
|
cf6a23b83c | ||
|
|
9e0daac561 | ||
|
|
f2fd7335ce | ||
|
|
b8f878df5e | ||
|
|
9bdb922c75 | ||
|
|
edecc1bba6 | ||
|
|
8e903153f6 | ||
|
|
3937885f37 | ||
|
|
24de97d951 | ||
|
|
06e5b3e457 | ||
|
|
68a0e6dc19 | ||
|
|
9d4a4478f7 | ||
|
|
6bbf3f46c4 | ||
|
|
4ac4e8c991 | ||
|
|
0091a3ae5f | ||
|
|
17b3109a8b | ||
|
|
71520213c1 | ||
|
|
f24e7a0052 | ||
|
|
507e9f7ec3 | ||
|
|
592c53c8bf | ||
|
|
a2df89dedd | ||
|
|
b8f12d2e79 | ||
|
|
67b1d0463a | ||
|
|
d008a181ec | ||
|
|
6d612a428a | ||
|
|
c0cb73ab16 | ||
|
|
2e1eb84cbf | ||
|
|
b03a8728b5 | ||
|
|
1dd3350a30 | ||
|
|
bda34945a5 | ||
|
|
85dcaa8d3c | ||
|
|
4ac74ed0ad | ||
|
|
b7e2a4b9a9 | ||
|
|
53a7758248 | ||
|
|
2ba767957d | ||
|
|
08152787e1 | ||
|
|
5f77b420cd | ||
|
|
90f9e60517 | ||
|
|
320737f6e4 | ||
|
|
dfba1416b2 | ||
|
|
2ca3f35bd1 | ||
|
|
b1c40d5fa7 | ||
|
|
a129e27b3e | ||
|
|
ad7daa008e | ||
|
|
062d7081a0 | ||
|
|
40c1e7e005 | ||
|
|
3cbd05ddff | ||
|
|
9414090617 | ||
|
|
825777edc1 | ||
|
|
4e0807e908 | ||
|
|
546be5692a | ||
|
|
43e1f20b28 | ||
|
|
97388cefda | ||
|
|
63ce579989 | ||
|
|
5f4a62aa40 | ||
|
|
02ab52b3e2 | ||
|
|
549732b1da | ||
|
|
c4565fe0f5 |
24
.github/workflows/release.yaml
vendored
24
.github/workflows/release.yaml
vendored
@@ -16,7 +16,7 @@ env:
|
||||
PYTHON_VERSION: "3.7" # to build abi3 wheels
|
||||
|
||||
jobs:
|
||||
macos:
|
||||
macos-x86_64:
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
@@ -39,6 +39,25 @@ jobs:
|
||||
- name: Install built wheel - x86_64
|
||||
run: |
|
||||
pip install dist/${{ env.PACKAGE_NAME }}-*.whl --force-reinstall
|
||||
- name: Upload wheels
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: wheels
|
||||
path: dist
|
||||
macos-universal:
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
architecture: x64
|
||||
- name: Install Rust toolchain
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
default: true
|
||||
- name: Build wheels - universal2
|
||||
uses: messense/maturin-action@v1
|
||||
with:
|
||||
@@ -261,7 +280,8 @@ jobs:
|
||||
name: Release
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- macos
|
||||
- macos-universal
|
||||
- macos-x86_64
|
||||
- windows
|
||||
- linux
|
||||
- linux-cross
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
repos:
|
||||
- repo: https://github.com/charliermarsh/ruff
|
||||
rev: v0.0.33
|
||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||
rev: v0.0.40
|
||||
hooks:
|
||||
- id: lint
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
- id: lint
|
||||
name: ruff lint
|
||||
description: Run ruff to lint Python files.
|
||||
entry: ruff
|
||||
language: python
|
||||
types_or: [python]
|
||||
pass_filenames: true
|
||||
87
Cargo.lock
generated
87
Cargo.lock
generated
@@ -458,6 +458,19 @@ dependencies = [
|
||||
"cache-padded",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "console"
|
||||
version = "0.15.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "89eab4d20ce20cea182308bca13088fecea9c05f6776cf287205d41a0ed3c847"
|
||||
dependencies = [
|
||||
"encode_unicode",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"terminal_size",
|
||||
"winapi 0.3.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation"
|
||||
version = "0.9.3"
|
||||
@@ -652,6 +665,12 @@ dependencies = [
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "encode_unicode"
|
||||
version = "0.3.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f"
|
||||
|
||||
[[package]]
|
||||
name = "event-listener"
|
||||
version = "2.5.3"
|
||||
@@ -1011,6 +1030,20 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "insta"
|
||||
version = "1.19.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc61e98be01e89296f3343a878e9f8ca75a494cb5aaf29df65ef55734aeb85f5"
|
||||
dependencies = [
|
||||
"console",
|
||||
"linked-hash-map",
|
||||
"once_cell",
|
||||
"serde",
|
||||
"similar",
|
||||
"yaml-rust",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "instant"
|
||||
version = "0.1.12"
|
||||
@@ -1122,6 +1155,12 @@ version = "0.2.127"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "505e71a4706fa491e9b1b55f51b95d4037d0821ee40131190475f692b35b009b"
|
||||
|
||||
[[package]]
|
||||
name = "linked-hash-map"
|
||||
version = "0.5.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.7"
|
||||
@@ -1393,6 +1432,24 @@ dependencies = [
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "path-absolutize"
|
||||
version = "3.0.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3de4b40bd9736640f14c438304c09538159802388febb02c8abaae0846c1f13"
|
||||
dependencies = [
|
||||
"path-dedot",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "path-dedot"
|
||||
version = "3.0.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d611d5291372b3738a34ebf0d1f849e58b1dcc1101032f76a346eaa1f8ddbb5b"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.1.0"
|
||||
@@ -1744,7 +1801,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ruff"
|
||||
version = "0.0.33"
|
||||
version = "0.0.43"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bincode",
|
||||
@@ -1758,11 +1815,12 @@ dependencies = [
|
||||
"fern",
|
||||
"filetime",
|
||||
"glob",
|
||||
"insta",
|
||||
"itertools",
|
||||
"lazy_static",
|
||||
"log",
|
||||
"notify",
|
||||
"once_cell",
|
||||
"path-absolutize",
|
||||
"rayon",
|
||||
"regex",
|
||||
"rustpython-parser",
|
||||
@@ -1978,6 +2036,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "similar"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "62ac7f900db32bf3fd12e0117dd3dc4da74bc52ebaac97f39668446d89694803"
|
||||
|
||||
[[package]]
|
||||
name = "siphasher"
|
||||
version = "0.3.10"
|
||||
@@ -2100,6 +2164,16 @@ dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "terminal_size"
|
||||
version = "0.1.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "633c1a546cee861a1a6d0dc69ebeca693bf4296661ba7852b9d21d159e0506df"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"winapi 0.3.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "terminfo"
|
||||
version = "0.7.3"
|
||||
@@ -2595,3 +2669,12 @@ dependencies = [
|
||||
"winapi 0.2.8",
|
||||
"winapi-build",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yaml-rust"
|
||||
version = "0.4.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
|
||||
dependencies = [
|
||||
"linked-hash-map",
|
||||
]
|
||||
|
||||
15
Cargo.toml
15
Cargo.toml
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ruff"
|
||||
version = "0.0.33"
|
||||
version = "0.0.43"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
@@ -18,12 +18,12 @@ common-path = { version = "1.0.0" }
|
||||
dirs = { version = "4.0.0" }
|
||||
fern = { version = "0.6.1" }
|
||||
filetime = { version = "0.2.17" }
|
||||
glob = { version = "0.3.0" }
|
||||
glob = "0.3.0"
|
||||
itertools = "0.10.3"
|
||||
lazy_static = "1.4.0"
|
||||
log = { version = "0.4.17" }
|
||||
notify = { version = "4.0.17" }
|
||||
once_cell = { version = "1.13.1" }
|
||||
path-absolutize = { version = "3.0.13", features = ["once_cell_cache"] }
|
||||
rayon = { version = "1.5.3" }
|
||||
regex = { version = "1.6.0" }
|
||||
rustpython-parser = { features = ["lalrpop"], git = "https://github.com/charliermarsh/RustPython.git", rev = "7d21c6923a506e79cc041708d83cef925efd33f4" }
|
||||
@@ -33,6 +33,9 @@ toml = { version = "0.5.9" }
|
||||
update-informer = { version = "0.5.0", default_features = false, features = ["pypi"], optional = true }
|
||||
walkdir = { version = "2.3.2" }
|
||||
|
||||
[dev-dependencies]
|
||||
insta = { version = "1.19.1", features = ["yaml"] }
|
||||
|
||||
[features]
|
||||
default = ["update-informer"]
|
||||
update-informer = ["dep:update-informer"]
|
||||
@@ -42,3 +45,9 @@ panic = "abort"
|
||||
lto = "thin"
|
||||
codegen-units = 1
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.insta]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.similar]
|
||||
opt-level = 3
|
||||
|
||||
185
README.md
185
README.md
@@ -1,7 +1,9 @@
|
||||
# ruff
|
||||
|
||||
[](https://pypi.python.org/pypi/ruff)
|
||||
[](https://pypi.python.org/pypi/ruff)
|
||||
[](https://pypi.python.org/pypi/ruff)
|
||||
[](https://github.com/charliermarsh/ruff/actions)
|
||||
[](https://badge.fury.io/py/ruff)
|
||||
|
||||
An extremely fast Python linter, written in Rust.
|
||||
|
||||
@@ -52,14 +54,14 @@ You can run ruff in `--watch` mode to automatically re-run on-change:
|
||||
ruff path/to/code/ --watch
|
||||
```
|
||||
|
||||
ruff also works with [Pre-Commit](https://pre-commit.com) (requires Cargo on system):
|
||||
ruff also works with [pre-commit](https://pre-commit.com):
|
||||
|
||||
```yaml
|
||||
repos:
|
||||
- repo: https://github.com/charliermarsh/ruff
|
||||
rev: v0.0.33
|
||||
hooks:
|
||||
- id: lint
|
||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||
rev: v0.0.40
|
||||
hooks:
|
||||
- id: lint
|
||||
```
|
||||
|
||||
## Configuration
|
||||
@@ -86,7 +88,7 @@ ruff path/to/code/ --select F401 F403
|
||||
See `ruff --help` for more:
|
||||
|
||||
```shell
|
||||
ruff (v0.0.33)
|
||||
ruff (v0.0.43)
|
||||
An extremely fast Python linter.
|
||||
|
||||
USAGE:
|
||||
@@ -96,19 +98,44 @@ ARGS:
|
||||
<FILES>...
|
||||
|
||||
OPTIONS:
|
||||
-e, --exit-zero Exit with status code "0", even upon detecting errors
|
||||
--exclude <EXCLUDE>... List of file and/or directory patterns to exclude from checks
|
||||
-f, --fix Attempt to automatically fix lint errors
|
||||
-h, --help Print help information
|
||||
--ignore <IGNORE>... List of error codes to ignore
|
||||
-n, --no-cache Disable cache reads
|
||||
-q, --quiet Disable all logging (but still exit with status code "1" upon
|
||||
detecting errors)
|
||||
--select <SELECT>... List of error codes to enable
|
||||
-v, --verbose Enable verbose logging
|
||||
-w, --watch Run in watch mode by re-running whenever files change
|
||||
-e, --exit-zero
|
||||
Exit with status code "0", even upon detecting errors
|
||||
--exclude <EXCLUDE>...
|
||||
List of paths, used to exclude files and/or directories from checks
|
||||
--extend-exclude <EXTEND_EXCLUDE>...
|
||||
Like --exclude, but adds additional files and directories on top of the excluded ones
|
||||
-f, --fix
|
||||
Attempt to automatically fix lint errors
|
||||
--format <FORMAT>
|
||||
Output serialization format for error messages [default: text] [possible values: text,
|
||||
json]
|
||||
-h, --help
|
||||
Print help information
|
||||
--ignore <IGNORE>...
|
||||
List of error codes to ignore
|
||||
-n, --no-cache
|
||||
Disable cache reads
|
||||
-q, --quiet
|
||||
Disable all logging (but still exit with status code "1" upon detecting errors)
|
||||
--select <SELECT>...
|
||||
List of error codes to enable
|
||||
-v, --verbose
|
||||
Enable verbose logging
|
||||
-V, --version
|
||||
Print version information
|
||||
-w, --watch
|
||||
Run in watch mode by re-running whenever files change
|
||||
```
|
||||
|
||||
Exclusions are based on globs, and can be either:
|
||||
|
||||
- Single-path patterns, like `.mypy_cache` (to exclude any directory named `.mypy_cache` in the
|
||||
tree), `foo.py` (to exclude any file named `foo.py`), or `foo_*.py` (to exclude any file matching
|
||||
`foo_*.py` ).
|
||||
- Relative patterns, like `directory/foo.py` (to exclude that specific file) or `directory/*.py`
|
||||
(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`).
|
||||
|
||||
### Compatibility with Black
|
||||
|
||||
ruff is intended to be compatible with [Black](https://github.com/psf/black), and should be
|
||||
@@ -123,18 +150,15 @@ ruff's goal is to achieve feature-parity with Flake8 when used (1) without any p
|
||||
(2) alongside Black, and (3) on Python 3 code. (Using Black obviates the need for many of Flake8's
|
||||
stylistic checks; limiting to Python 3 obviates the need for certain compatibility checks.)
|
||||
|
||||
Under those conditions, Flake8 implements about 58 rules, give or take. At time of writing, ruff
|
||||
implements 28 rules. (Note that these 28 rules likely cover a disproportionate share of errors:
|
||||
Under those conditions, Flake8 implements about 60 rules, give or take. At time of writing, ruff
|
||||
implements 42 rules. (Note that these 42 rules likely cover a disproportionate share of errors:
|
||||
unused imports, undefined variables, etc.)
|
||||
|
||||
Of the unimplemented rules, ruff is missing:
|
||||
The unimplemented rules are tracked in #170, and include:
|
||||
|
||||
- 15 rules related to string `.format` calls.
|
||||
- 6 rules related to misplaced `yield`, `break`, and `return` statements.
|
||||
- 3 rules related to syntax errors in doctests and annotations.
|
||||
- 2 rules related to redefining unused names.
|
||||
|
||||
...along with a variety of others that don't fit neatly into any specific category.
|
||||
- 14 rules related to string `.format` calls.
|
||||
- 4 logical rules.
|
||||
- 1 rule related to parsing.
|
||||
|
||||
Beyond rule-set parity, ruff suffers from the following limitations vis-à-vis Flake8:
|
||||
|
||||
@@ -147,25 +171,39 @@ Beyond rule-set parity, ruff suffers from the following limitations vis-à-vis F
|
||||
| Code | Name | Message |
|
||||
| ---- | ----- | ------- |
|
||||
| E402 | ModuleImportNotAtTopOfFile | Module level import not at top of file |
|
||||
| E501 | LineTooLong | Line too long |
|
||||
| E501 | LineTooLong | Line too long (89 > 88 characters) |
|
||||
| E711 | NoneComparison | Comparison to `None` should be `cond is None` |
|
||||
| E712 | TrueFalseComparison | Comparison to `True` should be `cond is True` |
|
||||
| E713 | NotInTest | Test for membership should be `not in` |
|
||||
| E714 | NotIsTest | Test for object identity should be `is not` |
|
||||
| E721 | TypeComparison | do not compare types, use `isinstance()` |
|
||||
| E722 | DoNotUseBareExcept | Do not use bare `except` |
|
||||
| E731 | DoNotAssignLambda | Do not assign a lambda expression, use a def |
|
||||
| E741 | AmbiguousVariableName | ambiguous variable name '...' |
|
||||
| E742 | AmbiguousClassName | ambiguous class name '...' |
|
||||
| E743 | AmbiguousFunctionName | ambiguous function name '...' |
|
||||
| E902 | IOError | No such file or directory: `...` |
|
||||
| E999 | SyntaxError | SyntaxError: ... |
|
||||
| F401 | UnusedImport | `...` imported but unused |
|
||||
| F403 | ImportStarUsage | Unable to detect undefined names |
|
||||
| F403 | ImportStarUsage | `from ... import *` used; unable to detect undefined names |
|
||||
| F404 | LateFutureImport | from __future__ imports must occur at the beginning of the file |
|
||||
| F406 | ImportStarNotPermitted | `from ... import *` only allowed at module level |
|
||||
| F407 | FutureFeatureNotDefined | future feature '...' is not defined |
|
||||
| F541 | FStringMissingPlaceholders | f-string without any placeholders |
|
||||
| F601 | MultiValueRepeatedKeyLiteral | Dictionary key literal repeated |
|
||||
| F602 | MultiValueRepeatedKeyVariable | Dictionary key `...` repeated |
|
||||
| F621 | TooManyExpressionsInStarredAssignment | too many expressions in star-unpacking assignment |
|
||||
| F622 | TwoStarredExpressions | two starred expressions in assignment |
|
||||
| F631 | AssertTuple | Assert test is a non-empty tuple, which is always `True` |
|
||||
| F632 | IsLiteral | use ==/!= to compare constant literals |
|
||||
| F633 | InvalidPrintSyntax | use of >> is invalid with print function |
|
||||
| F634 | IfTuple | If test is a tuple, which is always `True` |
|
||||
| F701 | BreakOutsideLoop | `break` outside loop |
|
||||
| F702 | ContinueOutsideLoop | `continue` not properly in loop |
|
||||
| F704 | YieldOutsideFunction | a `yield` or `yield from` statement outside of a function/method |
|
||||
| F706 | ReturnOutsideFunction | a `return` statement outside of a function/method |
|
||||
| F707 | DefaultExceptNotLast | an `except:` block as not the last exception handler |
|
||||
| F722 | ForwardAnnotationSyntaxError | syntax error in forward annotation '...' |
|
||||
| F821 | UndefinedName | Undefined name `...` |
|
||||
| F822 | UndefinedExport | Undefined name `...` in `__all__` |
|
||||
| F823 | UndefinedLocal | Local variable `...` referenced before assignment |
|
||||
@@ -209,7 +247,7 @@ Add this `pyproject.toml` to the CPython directory:
|
||||
```toml
|
||||
[tool.ruff]
|
||||
line-length = 88
|
||||
exclude = [
|
||||
extend-exclude = [
|
||||
"Lib/lib2to3/tests/data/bom.py",
|
||||
"Lib/lib2to3/tests/data/crlf.py",
|
||||
"Lib/lib2to3/tests/data/different_encoding.py",
|
||||
@@ -240,17 +278,21 @@ Next, to benchmark the release build:
|
||||
```shell
|
||||
cargo build --release
|
||||
|
||||
hyperfine --ignore-failure --warmup 1 \
|
||||
hyperfine --ignore-failure --warmup 10 --runs 100 \
|
||||
"./target/release/ruff ./resources/test/cpython/ --no-cache" \
|
||||
"./target/release/ruff ./resources/test/cpython/"
|
||||
|
||||
Benchmark 1: ./target/release/ruff ./resources/test/cpython/ --no-cache
|
||||
Time (mean ± σ): 353.6 ms ± 7.6 ms [User: 2868.8 ms, System: 171.5 ms]
|
||||
Range (min … max): 344.4 ms … 367.3 ms 10 runs
|
||||
Time (mean ± σ): 297.4 ms ± 4.9 ms [User: 2460.0 ms, System: 67.2 ms]
|
||||
Range (min … max): 287.7 ms … 312.1 ms 100 runs
|
||||
|
||||
Warning: Ignoring non-zero exit code.
|
||||
|
||||
Benchmark 2: ./target/release/ruff ./resources/test/cpython/
|
||||
Time (mean ± σ): 59.6 ms ± 2.5 ms [User: 36.4 ms, System: 345.6 ms]
|
||||
Range (min … max): 55.9 ms … 67.0 ms 48 runs
|
||||
Time (mean ± σ): 79.6 ms ± 7.3 ms [User: 59.7 ms, System: 356.1 ms]
|
||||
Range (min … max): 62.4 ms … 111.2 ms 100 runs
|
||||
|
||||
Warning: Ignoring non-zero exit code.
|
||||
```
|
||||
|
||||
To benchmark against the ecosystem's existing tools:
|
||||
@@ -262,11 +304,8 @@ hyperfine --ignore-failure --warmup 5 \
|
||||
"pyflakes resources/test/cpython" \
|
||||
"autoflake --recursive --expand-star-imports --remove-all-unused-imports --remove-unused-variables --remove-duplicate-keys resources/test/cpython" \
|
||||
"pycodestyle resources/test/cpython" \
|
||||
"pycodestyle --select E501 resources/test/cpython" \
|
||||
"flake8 resources/test/cpython" \
|
||||
"flake8 --select=F831,F541,F634,F403,F706,F901,E501 resources/test/cpython" \
|
||||
"python -m scripts.run_flake8 resources/test/cpython" \
|
||||
"python -m scripts.run_flake8 resources/test/cpython --select=F831,F541,F634,F403,F706,F901,E501"
|
||||
"python -m scripts.run_flake8 resources/test/cpython"
|
||||
```
|
||||
|
||||
In order, these evaluate:
|
||||
@@ -276,66 +315,58 @@ In order, these evaluate:
|
||||
- PyFlakes
|
||||
- autoflake
|
||||
- pycodestyle
|
||||
- pycodestyle, limited to the checks supported by ruff
|
||||
- Flake8
|
||||
- Flake8, limited to the checks supported by ruff
|
||||
- Flake8, with a hack to enable multiprocessing on macOS
|
||||
- Flake8, with a hack to enable multiprocessing on macOS, limited to the checks supported by ruff
|
||||
|
||||
(You can `poetry install` from `./scripts` to create a working environment for the above.)
|
||||
|
||||
```shell
|
||||
Benchmark 1: ./target/release/ruff ./resources/test/cpython/ --no-cache
|
||||
Time (mean ± σ): 469.3 ms ± 16.3 ms [User: 2663.0 ms, System: 972.5 ms]
|
||||
Range (min … max): 445.2 ms … 494.8 ms 10 runs
|
||||
Time (mean ± σ): 297.9 ms ± 7.0 ms [User: 2436.6 ms, System: 65.9 ms]
|
||||
Range (min … max): 289.9 ms … 314.6 ms 10 runs
|
||||
|
||||
Warning: Ignoring non-zero exit code.
|
||||
|
||||
Benchmark 2: pylint --recursive=y resources/test/cpython/
|
||||
Time (mean ± σ): 27.211 s ± 0.097 s [User: 26.405 s, System: 0.799 s]
|
||||
Range (min … max): 27.056 s … 27.349 s 10 runs
|
||||
Time (mean ± σ): 37.634 s ± 0.225 s [User: 36.728 s, System: 0.853 s]
|
||||
Range (min … max): 37.201 s … 38.106 s 10 runs
|
||||
|
||||
Warning: Ignoring non-zero exit code.
|
||||
|
||||
Benchmark 3: pyflakes resources/test/cpython
|
||||
Time (mean ± σ): 27.309 s ± 0.033 s [User: 27.137 s, System: 0.169 s]
|
||||
Range (min … max): 27.267 s … 27.372 s 10 runs
|
||||
Time (mean ± σ): 40.950 s ± 0.449 s [User: 40.688 s, System: 0.229 s]
|
||||
Range (min … max): 40.348 s … 41.671 s 10 runs
|
||||
|
||||
Warning: Ignoring non-zero exit code.
|
||||
|
||||
Benchmark 4: autoflake --recursive --expand-star-imports --remove-all-unused-imports --remove-unused-variables --remove-duplicate-keys resources/test/cpython
|
||||
Time (mean ± σ): 8.027 s ± 0.024 s [User: 74.255 s, System: 0.953 s]
|
||||
Range (min … max): 7.969 s … 8.052 s 10 runs
|
||||
Time (mean ± σ): 11.562 s ± 0.160 s [User: 107.022 s, System: 1.143 s]
|
||||
Range (min … max): 11.417 s … 11.917 s 10 runs
|
||||
|
||||
Benchmark 5: pycodestyle resources/test/cpython
|
||||
Time (mean ± σ): 41.666 s ± 0.266 s [User: 41.531 s, System: 0.132 s]
|
||||
Range (min … max): 41.295 s … 41.980 s 10 runs
|
||||
Time (mean ± σ): 67.428 s ± 0.985 s [User: 67.199 s, System: 0.203 s]
|
||||
Range (min … max): 65.313 s … 68.496 s 10 runs
|
||||
|
||||
Benchmark 6: pycodestyle --select E501 resources/test/cpython
|
||||
Time (mean ± σ): 14.547 s ± 0.077 s [User: 14.466 s, System: 0.079 s]
|
||||
Range (min … max): 14.429 s … 14.695 s 10 runs
|
||||
Warning: Ignoring non-zero exit code.
|
||||
|
||||
Benchmark 7: flake8 resources/test/cpython
|
||||
Time (mean ± σ): 75.700 s ± 0.152 s [User: 75.254 s, System: 0.440 s]
|
||||
Range (min … max): 75.513 s … 76.014 s 10 runs
|
||||
Benchmark 6: flake8 resources/test/cpython
|
||||
Time (mean ± σ): 116.099 s ± 1.178 s [User: 115.217 s, System: 0.845 s]
|
||||
Range (min … max): 114.180 s … 117.724 s 10 runs
|
||||
|
||||
Benchmark 8: flake8 --select=F831,F541,F634,F403,F706,F901,E501 resources/test/cpython
|
||||
Time (mean ± σ): 75.122 s ± 0.532 s [User: 74.677 s, System: 0.440 s]
|
||||
Range (min … max): 74.130 s … 75.606 s 10 runs
|
||||
Warning: Ignoring non-zero exit code.
|
||||
|
||||
Benchmark 9: python -m scripts.run_flake8 resources/test/cpython
|
||||
Time (mean ± σ): 12.794 s ± 0.147 s [User: 90.792 s, System: 0.738 s]
|
||||
Range (min … max): 12.606 s … 13.030 s 10 runs
|
||||
|
||||
Benchmark 10: python -m scripts.run_flake8 resources/test/cpython --select=F831,F541,F634,F403,F706,F901,E501
|
||||
Time (mean ± σ): 12.487 s ± 0.118 s [User: 90.052 s, System: 0.714 s]
|
||||
Range (min … max): 12.265 s … 12.665 s 10 runs
|
||||
Benchmark 7: python -m scripts.run_flake8 resources/test/cpython
|
||||
Time (mean ± σ): 20.477 s ± 0.349 s [User: 142.372 s, System: 1.504 s]
|
||||
Range (min … max): 20.107 s … 21.183 s 10 runs
|
||||
|
||||
Summary
|
||||
'./target/release/ruff ./resources/test/cpython/ --no-cache' ran
|
||||
17.10 ± 0.60 times faster than 'autoflake --recursive --expand-star-imports --remove-all-unused-imports --remove-unused-variables --remove-duplicate-keys resources/test/cpython'
|
||||
26.60 ± 0.96 times faster than 'python -m scripts.run_flake8 resources/test/cpython --select=F831,F541,F634,F403,F706,F901,E501'
|
||||
27.26 ± 1.00 times faster than 'python -m scripts.run_flake8 resources/test/cpython'
|
||||
30.99 ± 1.09 times faster than 'pycodestyle --select E501 resources/test/cpython'
|
||||
57.98 ± 2.03 times faster than 'pylint --recursive=y resources/test/cpython/'
|
||||
58.19 ± 2.02 times faster than 'pyflakes resources/test/cpython'
|
||||
88.77 ± 3.14 times faster than 'pycodestyle resources/test/cpython'
|
||||
160.06 ± 5.68 times faster than 'flake8 --select=F831,F541,F634,F403,F706,F901,E501 resources/test/cpython'
|
||||
161.29 ± 5.61 times faster than 'flake8 resources/test/cpython'
|
||||
38.81 ± 1.05 times faster than 'autoflake --recursive --expand-star-imports --remove-all-unused-imports --remove-unused-variables --remove-duplicate-keys resources/test/cpython'
|
||||
68.74 ± 1.99 times faster than 'python -m scripts.run_flake8 resources/test/cpython'
|
||||
126.33 ± 3.05 times faster than 'pylint --recursive=y resources/test/cpython/'
|
||||
137.46 ± 3.55 times faster than 'pyflakes resources/test/cpython'
|
||||
226.35 ± 6.23 times faster than 'pycodestyle resources/test/cpython'
|
||||
389.73 ± 9.92 times faster than 'flake8 resources/test/cpython'
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
@@ -1,42 +1,14 @@
|
||||
/// Generate a Markdown-compatible table of supported lint rules.
|
||||
use ruff::checks::{CheckKind, RejectedCmpop};
|
||||
use ruff::checks::{CheckCode, ALL_CHECK_CODES};
|
||||
|
||||
fn main() {
|
||||
let mut check_kinds: Vec<CheckKind> = vec![
|
||||
CheckKind::AssertTuple,
|
||||
CheckKind::DefaultExceptNotLast,
|
||||
CheckKind::DoNotAssignLambda,
|
||||
CheckKind::DuplicateArgumentName,
|
||||
CheckKind::FStringMissingPlaceholders,
|
||||
CheckKind::IOError("...".to_string()),
|
||||
CheckKind::IfTuple,
|
||||
CheckKind::ImportStarUsage,
|
||||
CheckKind::LineTooLong,
|
||||
CheckKind::ModuleImportNotAtTopOfFile,
|
||||
CheckKind::MultiValueRepeatedKeyLiteral,
|
||||
CheckKind::MultiValueRepeatedKeyVariable("...".to_string()),
|
||||
CheckKind::NoAssertEquals,
|
||||
CheckKind::NoneComparison(RejectedCmpop::Eq),
|
||||
CheckKind::NotInTest,
|
||||
CheckKind::NotIsTest,
|
||||
CheckKind::RaiseNotImplemented,
|
||||
CheckKind::ReturnOutsideFunction,
|
||||
CheckKind::TooManyExpressionsInStarredAssignment,
|
||||
CheckKind::TrueFalseComparison(true, RejectedCmpop::Eq),
|
||||
CheckKind::TwoStarredExpressions,
|
||||
CheckKind::UndefinedExport("...".to_string()),
|
||||
CheckKind::UndefinedLocal("...".to_string()),
|
||||
CheckKind::UndefinedName("...".to_string()),
|
||||
CheckKind::UnusedImport("...".to_string()),
|
||||
CheckKind::UnusedVariable("...".to_string()),
|
||||
CheckKind::UselessObjectInheritance("...".to_string()),
|
||||
CheckKind::YieldOutsideFunction,
|
||||
];
|
||||
check_kinds.sort_by_key(|check_kind| check_kind.code());
|
||||
let mut check_codes: Vec<CheckCode> = ALL_CHECK_CODES.to_vec();
|
||||
check_codes.sort();
|
||||
|
||||
println!("| Code | Name | Message |");
|
||||
println!("| ---- | ----- | ------- |");
|
||||
for check_kind in check_kinds {
|
||||
for check_code in check_codes {
|
||||
let check_kind = check_code.kind();
|
||||
println!(
|
||||
"| {} | {} | {} |",
|
||||
check_kind.code().as_str(),
|
||||
|
||||
@@ -19,10 +19,12 @@ classifiers = [
|
||||
]
|
||||
author = "Charlie Marsh"
|
||||
author_email = "charlie.r.marsh@gmail.com"
|
||||
url = "https://github.com/charliermarsh/ruff"
|
||||
description = "An extremely fast Python linter, written in Rust."
|
||||
requires-python = ">=3.7"
|
||||
|
||||
[project.urls]
|
||||
repository = "https://github.com/charliermarsh/ruff"
|
||||
|
||||
[build-system]
|
||||
requires = ["maturin>=0.13,<0.14"]
|
||||
build-backend = "maturin"
|
||||
|
||||
3
resources/test/fixtures/E501.py
vendored
3
resources/test/fixtures/E501.py
vendored
@@ -4,3 +4,6 @@
|
||||
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
|
||||
"""
|
||||
|
||||
_ = "---------------------------------------------------------------------------AAAAAAA"
|
||||
_ = "---------------------------------------------------------------------------亜亜亜亜亜亜亜"
|
||||
|
||||
47
resources/test/fixtures/E711.py
vendored
47
resources/test/fixtures/E711.py
vendored
@@ -1,11 +1,50 @@
|
||||
if var == None:
|
||||
#: E711
|
||||
if res == None:
|
||||
pass
|
||||
#: E711
|
||||
if res != None:
|
||||
pass
|
||||
#: E711
|
||||
if None == res:
|
||||
pass
|
||||
#: E711
|
||||
if None != res:
|
||||
pass
|
||||
#: E711
|
||||
if res[1] == None:
|
||||
pass
|
||||
#: E711
|
||||
if res[1] != None:
|
||||
pass
|
||||
#: E711
|
||||
if None != res[1]:
|
||||
pass
|
||||
#: E711
|
||||
if None == res[1]:
|
||||
pass
|
||||
|
||||
if None != var:
|
||||
#: Okay
|
||||
if x not in y:
|
||||
pass
|
||||
|
||||
if var is None:
|
||||
if not (X in Y or X is Z):
|
||||
pass
|
||||
|
||||
if None is not var:
|
||||
if not (X in Y):
|
||||
pass
|
||||
|
||||
if x is not y:
|
||||
pass
|
||||
|
||||
if X is not Y is not Z:
|
||||
pass
|
||||
|
||||
if TrueElement.get_element(True) == TrueElement.get_element(False):
|
||||
pass
|
||||
|
||||
if (True) == TrueElement or x == TrueElement:
|
||||
pass
|
||||
|
||||
assert (not foo) in bar
|
||||
assert {"x": not foo} in bar
|
||||
assert [42, not foo] in bar
|
||||
|
||||
42
resources/test/fixtures/E712.py
vendored
42
resources/test/fixtures/E712.py
vendored
@@ -1,14 +1,46 @@
|
||||
if var == True:
|
||||
#: E712
|
||||
if res == True:
|
||||
pass
|
||||
#: E712
|
||||
if res != False:
|
||||
pass
|
||||
#: E712
|
||||
if True != res:
|
||||
pass
|
||||
#: E712
|
||||
if False == res:
|
||||
pass
|
||||
#: E712
|
||||
if res[1] == True:
|
||||
pass
|
||||
#: E712
|
||||
if res[1] != False:
|
||||
pass
|
||||
#: E712
|
||||
var = 1 if cond == True else -1 if cond == False else cond
|
||||
#: E712
|
||||
if (True) == TrueElement or x == TrueElement:
|
||||
pass
|
||||
|
||||
if False != var:
|
||||
#: Okay
|
||||
if x not in y:
|
||||
pass
|
||||
|
||||
if var != False != True:
|
||||
if not (X in Y or X is Z):
|
||||
pass
|
||||
|
||||
if var is True:
|
||||
if not (X in Y):
|
||||
pass
|
||||
|
||||
if False is not var:
|
||||
if x is not y:
|
||||
pass
|
||||
|
||||
if X is not Y is not Z:
|
||||
pass
|
||||
|
||||
if TrueElement.get_element(True) == TrueElement.get_element(False):
|
||||
pass
|
||||
|
||||
assert (not foo) in bar
|
||||
assert {"x": not foo} in bar
|
||||
assert [42, not foo] in bar
|
||||
|
||||
43
resources/test/fixtures/E713.py
vendored
43
resources/test/fixtures/E713.py
vendored
@@ -1,7 +1,38 @@
|
||||
my_list = [1, 2, 3]
|
||||
if not num in my_list:
|
||||
print(num)
|
||||
#: E713
|
||||
if not X in Y:
|
||||
pass
|
||||
#: E713
|
||||
if not X.B in Y:
|
||||
pass
|
||||
#: E713
|
||||
if not X in Y and Z == "zero":
|
||||
pass
|
||||
#: E713
|
||||
if X == "zero" or not Y in Z:
|
||||
pass
|
||||
#: E713
|
||||
if not (X in Y):
|
||||
pass
|
||||
|
||||
my_list = [1, 2, 3]
|
||||
if num not in my_list:
|
||||
print(num)
|
||||
#: Okay
|
||||
if x not in y:
|
||||
pass
|
||||
|
||||
if not (X in Y or X is Z):
|
||||
pass
|
||||
|
||||
if x is not y:
|
||||
pass
|
||||
|
||||
if X is not Y is not Z:
|
||||
pass
|
||||
|
||||
if TrueElement.get_element(True) == TrueElement.get_element(False):
|
||||
pass
|
||||
|
||||
if (True) == TrueElement or x == TrueElement:
|
||||
pass
|
||||
|
||||
assert (not foo) in bar
|
||||
assert {"x": not foo} in bar
|
||||
assert [42, not foo] in bar
|
||||
|
||||
41
resources/test/fixtures/E714.py
vendored
41
resources/test/fixtures/E714.py
vendored
@@ -1,5 +1,38 @@
|
||||
if not user is None:
|
||||
print(user.name)
|
||||
#: E714
|
||||
if not X is Y:
|
||||
pass
|
||||
#: E714
|
||||
if not X.B is Y:
|
||||
pass
|
||||
#: E714
|
||||
if not X is Y is not Z:
|
||||
pass
|
||||
|
||||
if user is not None:
|
||||
print(user.name)
|
||||
#: Okay
|
||||
if not X is not Y:
|
||||
pass
|
||||
|
||||
if x not in y:
|
||||
pass
|
||||
|
||||
if not (X in Y or X is Z):
|
||||
pass
|
||||
|
||||
if not (X in Y):
|
||||
pass
|
||||
|
||||
if x is not y:
|
||||
pass
|
||||
|
||||
if X is not Y is not Z:
|
||||
pass
|
||||
|
||||
if TrueElement.get_element(True) == TrueElement.get_element(False):
|
||||
pass
|
||||
|
||||
if (True) == TrueElement or x == TrueElement:
|
||||
pass
|
||||
|
||||
assert (not foo) in bar
|
||||
assert {"x": not foo} in bar
|
||||
assert [42, not foo] in bar
|
||||
|
||||
54
resources/test/fixtures/E721.py
vendored
Normal file
54
resources/test/fixtures/E721.py
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
#: E721
|
||||
if type(res) == type(42):
|
||||
pass
|
||||
#: E721
|
||||
if type(res) != type(""):
|
||||
pass
|
||||
#: E721
|
||||
import types
|
||||
|
||||
if res == types.IntType:
|
||||
pass
|
||||
#: E721
|
||||
import types
|
||||
|
||||
if type(res) is not types.ListType:
|
||||
pass
|
||||
#: E721
|
||||
assert type(res) == type(False) or type(res) == type(None)
|
||||
#: E721
|
||||
assert type(res) == type([])
|
||||
#: E721
|
||||
assert type(res) == type(())
|
||||
#: E721
|
||||
assert type(res) == type((0,))
|
||||
#: E721
|
||||
assert type(res) == type((0))
|
||||
#: E721
|
||||
assert type(res) != type((1,))
|
||||
#: E721
|
||||
assert type(res) is type((1,))
|
||||
#: E721
|
||||
assert type(res) is not type((1,))
|
||||
#: E211 E721
|
||||
assert type(res) == type(
|
||||
[
|
||||
2,
|
||||
]
|
||||
)
|
||||
#: E201 E201 E202 E721
|
||||
assert type(res) == type(())
|
||||
#: E201 E202 E721
|
||||
assert type(res) == type((0,))
|
||||
|
||||
#: Okay
|
||||
import types
|
||||
|
||||
if isinstance(res, int):
|
||||
pass
|
||||
if isinstance(res, str):
|
||||
pass
|
||||
if isinstance(res, types.MethodType):
|
||||
pass
|
||||
if type(a) != type(b) or type(a) == type(ccc):
|
||||
pass
|
||||
33
resources/test/fixtures/E722.py
vendored
Normal file
33
resources/test/fixtures/E722.py
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
#: E722
|
||||
try:
|
||||
pass
|
||||
except:
|
||||
pass
|
||||
#: E722
|
||||
try:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
except:
|
||||
pass
|
||||
#: E722
|
||||
try:
|
||||
pass
|
||||
except:
|
||||
pass
|
||||
#: Okay
|
||||
fake_code = """"
|
||||
try:
|
||||
do_something()
|
||||
except:
|
||||
pass
|
||||
"""
|
||||
try:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
#: Okay
|
||||
from . import compute_type
|
||||
|
||||
if compute_type(foo) == 5:
|
||||
pass
|
||||
25
resources/test/fixtures/E731.py
vendored
25
resources/test/fixtures/E731.py
vendored
@@ -1,6 +1,21 @@
|
||||
from typing import Callable, Iterable
|
||||
#: E731
|
||||
f = lambda x: 2 * x
|
||||
#: E731
|
||||
f = lambda x: 2 * x
|
||||
#: E731
|
||||
while False:
|
||||
this = lambda y, z: 2 * x
|
||||
|
||||
a = lambda x: x**2
|
||||
b = map(lambda x: 2 * x, range(3))
|
||||
c: Callable = lambda x: x**2
|
||||
d: Iterable = map(lambda x: 2 * x, range(3))
|
||||
|
||||
f = object()
|
||||
#: E731
|
||||
f.method = lambda: "Method"
|
||||
|
||||
f = {}
|
||||
#: E731
|
||||
f["a"] = lambda x: x ** 2
|
||||
|
||||
f = []
|
||||
f.append(lambda x: x ** 2)
|
||||
|
||||
lambda: "no-op"
|
||||
|
||||
75
resources/test/fixtures/E741.py
vendored
Normal file
75
resources/test/fixtures/E741.py
vendored
Normal file
@@ -0,0 +1,75 @@
|
||||
from contextlib import contextmanager
|
||||
|
||||
l = 0
|
||||
I = 0
|
||||
O = 0
|
||||
l: int = 0
|
||||
|
||||
a, l = 0, 1
|
||||
[a, l] = 0, 1
|
||||
a, *l = 0, 1, 2
|
||||
a = l = 0
|
||||
|
||||
o = 0
|
||||
i = 0
|
||||
|
||||
for l in range(3):
|
||||
pass
|
||||
|
||||
|
||||
for a, l in zip(range(3), range(3)):
|
||||
pass
|
||||
|
||||
|
||||
def f1():
|
||||
global l
|
||||
l = 0
|
||||
|
||||
|
||||
def f2():
|
||||
l = 0
|
||||
|
||||
def f3():
|
||||
nonlocal l
|
||||
l = 1
|
||||
|
||||
f3()
|
||||
return l
|
||||
|
||||
|
||||
def f4(l, /, I):
|
||||
return l, I, O
|
||||
|
||||
|
||||
def f5(l=0, *, I=1):
|
||||
return l, I
|
||||
|
||||
|
||||
def f6(*l, **I):
|
||||
return l, I
|
||||
|
||||
|
||||
@contextmanager
|
||||
def ctx1():
|
||||
yield 0
|
||||
|
||||
|
||||
with ctx1() as l:
|
||||
pass
|
||||
|
||||
|
||||
@contextmanager
|
||||
def ctx2():
|
||||
yield 0, 1
|
||||
|
||||
|
||||
with ctx2() as (a, l):
|
||||
pass
|
||||
|
||||
try:
|
||||
pass
|
||||
except ValueError as l:
|
||||
pass
|
||||
|
||||
if (l := 5) > 0:
|
||||
pass
|
||||
14
resources/test/fixtures/E742.py
vendored
Normal file
14
resources/test/fixtures/E742.py
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
class l:
|
||||
pass
|
||||
|
||||
|
||||
class I:
|
||||
pass
|
||||
|
||||
|
||||
class O:
|
||||
pass
|
||||
|
||||
|
||||
class X:
|
||||
pass
|
||||
15
resources/test/fixtures/E743.py
vendored
Normal file
15
resources/test/fixtures/E743.py
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
def l():
|
||||
pass
|
||||
|
||||
|
||||
def I():
|
||||
pass
|
||||
|
||||
|
||||
class X:
|
||||
def O(self):
|
||||
pass
|
||||
|
||||
|
||||
def x():
|
||||
pass
|
||||
2
resources/test/fixtures/E999.py
vendored
Normal file
2
resources/test/fixtures/E999.py
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
def x():
|
||||
|
||||
7
resources/test/fixtures/F404.py
vendored
Normal file
7
resources/test/fixtures/F404.py
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
from __future__ import print_function
|
||||
"""Docstring"""
|
||||
from __future__ import absolute_import
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
from __future__ import print_function
|
||||
9
resources/test/fixtures/F406.py
vendored
Normal file
9
resources/test/fixtures/F406.py
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
from F634 import *
|
||||
|
||||
|
||||
def f():
|
||||
from F634 import *
|
||||
|
||||
|
||||
class F:
|
||||
from F634 import *
|
||||
2
resources/test/fixtures/F407.py
vendored
Normal file
2
resources/test/fixtures/F407.py
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
from __future__ import print_function
|
||||
from __future__ import non_existent_feature
|
||||
5
resources/test/fixtures/F632.py
vendored
Normal file
5
resources/test/fixtures/F632.py
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
if x is "abc":
|
||||
pass
|
||||
|
||||
if 123 is not y:
|
||||
pass
|
||||
4
resources/test/fixtures/F633.py
vendored
Normal file
4
resources/test/fixtures/F633.py
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
from __future__ import print_function
|
||||
import sys
|
||||
|
||||
print >> sys.stderr, "Hello"
|
||||
23
resources/test/fixtures/F701.py
vendored
Normal file
23
resources/test/fixtures/F701.py
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
for i in range(10):
|
||||
break
|
||||
else:
|
||||
break
|
||||
|
||||
i = 0
|
||||
while i < 10:
|
||||
i += 1
|
||||
break
|
||||
|
||||
|
||||
def f():
|
||||
for i in range(10):
|
||||
break
|
||||
|
||||
break
|
||||
|
||||
|
||||
class Foo:
|
||||
break
|
||||
|
||||
|
||||
break
|
||||
23
resources/test/fixtures/F702.py
vendored
Normal file
23
resources/test/fixtures/F702.py
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
for i in range(10):
|
||||
continue
|
||||
else:
|
||||
continue
|
||||
|
||||
i = 0
|
||||
while i < 10:
|
||||
i += 1
|
||||
continue
|
||||
|
||||
|
||||
def f():
|
||||
for i in range(10):
|
||||
continue
|
||||
|
||||
continue
|
||||
|
||||
|
||||
class Foo:
|
||||
continue
|
||||
|
||||
|
||||
continue
|
||||
10
resources/test/fixtures/F722.py
vendored
Normal file
10
resources/test/fixtures/F722.py
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
class A:
|
||||
pass
|
||||
|
||||
|
||||
def f() -> "A":
|
||||
pass
|
||||
|
||||
|
||||
def g() -> "///":
|
||||
pass
|
||||
5
resources/test/fixtures/F821.py
vendored
5
resources/test/fixtures/F821.py
vendored
@@ -77,3 +77,8 @@ class Ticket:
|
||||
|
||||
def set_status(self, status: Status):
|
||||
self.status = status
|
||||
|
||||
|
||||
def update_tomato():
|
||||
print(TOMATO)
|
||||
TOMATO = "cherry tomato"
|
||||
|
||||
15
resources/test/fixtures/F841.py
vendored
15
resources/test/fixtures/F841.py
vendored
@@ -14,3 +14,18 @@ def f():
|
||||
x = 1
|
||||
y = 2
|
||||
z = x + y
|
||||
|
||||
|
||||
def g():
|
||||
foo = (1, 2)
|
||||
(a, b) = (1, 2)
|
||||
|
||||
bar = (1, 2)
|
||||
(c, d) = bar
|
||||
|
||||
(x, y) = baz = bar
|
||||
|
||||
|
||||
def h():
|
||||
locals()
|
||||
x = 1
|
||||
|
||||
3
resources/test/fixtures/__init__.py
vendored
3
resources/test/fixtures/__init__.py
vendored
@@ -0,0 +1,3 @@
|
||||
print(__path__)
|
||||
|
||||
__all__ = ["a", "b", "c"]
|
||||
|
||||
9
resources/test/fixtures/directory/also_excluded.py
vendored
Normal file
9
resources/test/fixtures/directory/also_excluded.py
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
a = "abc"
|
||||
b = f"ghi{'jkl'}"
|
||||
|
||||
c = f"def"
|
||||
d = f"def" + "ghi"
|
||||
e = (
|
||||
f"def" +
|
||||
"ghi"
|
||||
)
|
||||
27
resources/test/fixtures/future_annotations.py
vendored
Normal file
27
resources/test/fixtures/future_annotations.py
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from models import Fruit, Nut
|
||||
|
||||
|
||||
@dataclass
|
||||
class Foo:
|
||||
x: int
|
||||
y: int
|
||||
|
||||
@classmethod
|
||||
def a(cls) -> Foo:
|
||||
return cls(x=0, y=0)
|
||||
|
||||
@classmethod
|
||||
def b(cls) -> "Foo":
|
||||
return cls(x=0, y=0)
|
||||
|
||||
@classmethod
|
||||
def c(cls) -> Bar:
|
||||
return cls(x=0, y=0)
|
||||
|
||||
@classmethod
|
||||
def d(cls) -> Fruit:
|
||||
return cls(x=0, y=0)
|
||||
34
resources/test/fixtures/pyproject.toml
vendored
34
resources/test/fixtures/pyproject.toml
vendored
@@ -1,33 +1,7 @@
|
||||
[tool.ruff]
|
||||
line-length = 88
|
||||
exclude = ["excluded.py", "**/migrations"]
|
||||
select = [
|
||||
"E402",
|
||||
"E501",
|
||||
"E711",
|
||||
"E712",
|
||||
"E713",
|
||||
"E714",
|
||||
"E731",
|
||||
"E902",
|
||||
"F401",
|
||||
"F403",
|
||||
"F541",
|
||||
"F601",
|
||||
"F602",
|
||||
"F621",
|
||||
"F622",
|
||||
"F631",
|
||||
"F634",
|
||||
"F704",
|
||||
"F706",
|
||||
"F707",
|
||||
"F821",
|
||||
"F822",
|
||||
"F823",
|
||||
"F831",
|
||||
"F841",
|
||||
"F901",
|
||||
"R001",
|
||||
"R002",
|
||||
extend-exclude = [
|
||||
"excluded.py",
|
||||
"migrations",
|
||||
"directory/also_excluded.py",
|
||||
]
|
||||
|
||||
@@ -3,11 +3,11 @@ use std::collections::BTreeSet;
|
||||
use itertools::izip;
|
||||
use rustpython_parser::ast::{
|
||||
Arg, Arguments, Cmpop, Constant, Excepthandler, ExcepthandlerKind, Expr, ExprKind, Keyword,
|
||||
Location, Stmt, Unaryop,
|
||||
Location, Stmt, StmtKind, Unaryop,
|
||||
};
|
||||
|
||||
use crate::ast::operations::SourceCodeLocator;
|
||||
use crate::ast::types::{Binding, BindingKind, Scope};
|
||||
use crate::ast::types::{Binding, BindingKind, FunctionScope, Scope, ScopeKind};
|
||||
use crate::autofix::{fixer, fixes};
|
||||
use crate::checks::{Check, CheckKind, Fix, RejectedCmpop};
|
||||
|
||||
@@ -42,18 +42,20 @@ pub fn check_not_tests(
|
||||
|
||||
if matches!(op, Unaryop::Not) {
|
||||
if let ExprKind::Compare { ops, .. } = &operand.node {
|
||||
match ops[..] {
|
||||
[Cmpop::In] => {
|
||||
if check_not_in {
|
||||
checks.push(Check::new(CheckKind::NotInTest, operand.location));
|
||||
for op in ops {
|
||||
match op {
|
||||
Cmpop::In => {
|
||||
if check_not_in {
|
||||
checks.push(Check::new(CheckKind::NotInTest, operand.location));
|
||||
}
|
||||
}
|
||||
}
|
||||
[Cmpop::Is] => {
|
||||
if check_not_is {
|
||||
checks.push(Check::new(CheckKind::NotIsTest, operand.location));
|
||||
Cmpop::Is => {
|
||||
if check_not_is {
|
||||
checks.push(Check::new(CheckKind::NotIsTest, operand.location));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -65,6 +67,13 @@ pub fn check_not_tests(
|
||||
pub fn check_unused_variables(scope: &Scope) -> Vec<Check> {
|
||||
let mut checks: Vec<Check> = vec![];
|
||||
|
||||
if matches!(
|
||||
scope.kind,
|
||||
ScopeKind::Function(FunctionScope { uses_locals: true })
|
||||
) {
|
||||
return checks;
|
||||
}
|
||||
|
||||
for (name, binding) in scope.values.iter() {
|
||||
// TODO(charlie): Ignore if using `locals`.
|
||||
if binding.used.is_none()
|
||||
@@ -93,6 +102,46 @@ pub fn check_do_not_assign_lambda(value: &Expr, location: Location) -> Option<Ch
|
||||
}
|
||||
}
|
||||
|
||||
fn is_ambiguous_name(name: &str) -> bool {
|
||||
name == "l" || name == "I" || name == "O"
|
||||
}
|
||||
|
||||
/// Check AmbiguousVariableName compliance.
|
||||
pub fn check_ambiguous_variable_name(name: &str, location: Location) -> Option<Check> {
|
||||
if is_ambiguous_name(name) {
|
||||
Some(Check::new(
|
||||
CheckKind::AmbiguousVariableName(name.to_string()),
|
||||
location,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Check AmbiguousClassName compliance.
|
||||
pub fn check_ambiguous_class_name(name: &str, location: Location) -> Option<Check> {
|
||||
if is_ambiguous_name(name) {
|
||||
Some(Check::new(
|
||||
CheckKind::AmbiguousClassName(name.to_string()),
|
||||
location,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Check AmbiguousFunctionName compliance.
|
||||
pub fn check_ambiguous_function_name(name: &str, location: Location) -> Option<Check> {
|
||||
if is_ambiguous_name(name) {
|
||||
Some(Check::new(
|
||||
CheckKind::AmbiguousFunctionName(name.to_string()),
|
||||
location,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Check UselessObjectInheritance compliance.
|
||||
pub fn check_useless_object_inheritance(
|
||||
stmt: &Stmt,
|
||||
@@ -116,9 +165,7 @@ pub fn check_useless_object_inheritance(
|
||||
CheckKind::UselessObjectInheritance(name.to_string()),
|
||||
expr.location,
|
||||
);
|
||||
if matches!(autofix, fixer::Mode::Generate)
|
||||
|| matches!(autofix, fixer::Mode::Apply)
|
||||
{
|
||||
if matches!(autofix, fixer::Mode::Generate | fixer::Mode::Apply) {
|
||||
if let Some(fix) = fixes::remove_class_def_base(
|
||||
locator,
|
||||
&stmt.location,
|
||||
@@ -214,9 +261,7 @@ pub fn check_assert_equals(expr: &Expr, autofix: &fixer::Mode) -> Option<Check>
|
||||
if let ExprKind::Name { id, .. } = &value.node {
|
||||
if id == "self" {
|
||||
let mut check = Check::new(CheckKind::NoAssertEquals, expr.location);
|
||||
if matches!(autofix, fixer::Mode::Generate)
|
||||
|| matches!(autofix, fixer::Mode::Apply)
|
||||
{
|
||||
if matches!(autofix, fixer::Mode::Generate | fixer::Mode::Apply) {
|
||||
check.amend(Fix {
|
||||
content: "assertEqual".to_string(),
|
||||
start: Location::new(expr.location.row(), expr.location.column() + 1),
|
||||
@@ -275,7 +320,7 @@ pub fn check_repeated_keys(
|
||||
(Some(DictionaryKey::Variable(v1)), Some(DictionaryKey::Variable(v2))) => {
|
||||
if check_repeated_variables && v1 == v2 {
|
||||
checks.push(Check::new(
|
||||
CheckKind::MultiValueRepeatedKeyVariable(v2.to_string()),
|
||||
CheckKind::MultiValueRepeatedKeyVariable((*v2).to_string()),
|
||||
k2.location,
|
||||
))
|
||||
}
|
||||
@@ -396,6 +441,90 @@ pub fn check_literal_comparisons(
|
||||
checks
|
||||
}
|
||||
|
||||
fn is_constant(expr: &Expr) -> bool {
|
||||
match &expr.node {
|
||||
ExprKind::Constant { .. } => true,
|
||||
ExprKind::Tuple { elts, .. } => elts.iter().all(is_constant),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_singleton(expr: &Expr) -> bool {
|
||||
matches!(
|
||||
expr.node,
|
||||
ExprKind::Constant {
|
||||
value: Constant::None | Constant::Bool(_) | Constant::Ellipsis,
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
fn is_constant_non_singleton(expr: &Expr) -> bool {
|
||||
is_constant(expr) && !is_singleton(expr)
|
||||
}
|
||||
|
||||
/// Check IsLiteral compliance.
|
||||
pub fn check_is_literal(
|
||||
left: &Expr,
|
||||
ops: &Vec<Cmpop>,
|
||||
comparators: &Vec<Expr>,
|
||||
location: Location,
|
||||
) -> Vec<Check> {
|
||||
let mut checks: Vec<Check> = vec![];
|
||||
|
||||
let mut left = left;
|
||||
for (op, right) in izip!(ops, comparators) {
|
||||
if matches!(op, Cmpop::Is | Cmpop::IsNot)
|
||||
&& (is_constant_non_singleton(left) || is_constant_non_singleton(right))
|
||||
{
|
||||
checks.push(Check::new(CheckKind::IsLiteral, location));
|
||||
}
|
||||
left = right;
|
||||
}
|
||||
|
||||
checks
|
||||
}
|
||||
|
||||
/// Check TypeComparison compliance.
|
||||
pub fn check_type_comparison(
|
||||
ops: &Vec<Cmpop>,
|
||||
comparators: &Vec<Expr>,
|
||||
location: Location,
|
||||
) -> Vec<Check> {
|
||||
let mut checks: Vec<Check> = vec![];
|
||||
|
||||
for (op, right) in izip!(ops, comparators) {
|
||||
if matches!(op, Cmpop::Is | Cmpop::IsNot | Cmpop::Eq | Cmpop::NotEq) {
|
||||
match &right.node {
|
||||
ExprKind::Call { func, args, .. } => {
|
||||
if let ExprKind::Name { id, .. } = &func.node {
|
||||
// Ex) type(False)
|
||||
if id == "type" {
|
||||
if let Some(arg) = args.first() {
|
||||
// Allow comparison for types which are not obvious.
|
||||
if !matches!(arg.node, ExprKind::Name { .. }) {
|
||||
checks.push(Check::new(CheckKind::TypeComparison, location));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ExprKind::Attribute { value, .. } => {
|
||||
if let ExprKind::Name { id, .. } = &value.node {
|
||||
// Ex) types.IntType
|
||||
if id == "types" {
|
||||
checks.push(Check::new(CheckKind::TypeComparison, location));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
checks
|
||||
}
|
||||
|
||||
/// Check TwoStarredExpressions and TooManyExpressionsInStarredAssignment compliance.
|
||||
pub fn check_starred_expressions(
|
||||
elts: &[Expr],
|
||||
@@ -428,3 +557,77 @@ pub fn check_starred_expressions(
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Check BreakOutsideLoop compliance.
|
||||
pub fn check_break_outside_loop(
|
||||
stmt: &Stmt,
|
||||
parents: &[&Stmt],
|
||||
parent_stack: &[usize],
|
||||
) -> Option<Check> {
|
||||
let mut allowed: bool = false;
|
||||
let mut parent = stmt;
|
||||
for index in parent_stack.iter().rev() {
|
||||
let child = parent;
|
||||
parent = parents[*index];
|
||||
match &parent.node {
|
||||
StmtKind::For { orelse, .. }
|
||||
| StmtKind::AsyncFor { orelse, .. }
|
||||
| StmtKind::While { orelse, .. } => {
|
||||
if !orelse.contains(child) {
|
||||
allowed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
StmtKind::FunctionDef { .. }
|
||||
| StmtKind::AsyncFunctionDef { .. }
|
||||
| StmtKind::ClassDef { .. } => {
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
if !allowed {
|
||||
Some(Check::new(CheckKind::BreakOutsideLoop, stmt.location))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Check ContinueOutsideLoop compliance.
|
||||
pub fn check_continue_outside_loop(
|
||||
stmt: &Stmt,
|
||||
parents: &[&Stmt],
|
||||
parent_stack: &[usize],
|
||||
) -> Option<Check> {
|
||||
let mut allowed: bool = false;
|
||||
let mut parent = stmt;
|
||||
for index in parent_stack.iter().rev() {
|
||||
let child = parent;
|
||||
parent = parents[*index];
|
||||
match &parent.node {
|
||||
StmtKind::For { orelse, .. }
|
||||
| StmtKind::AsyncFor { orelse, .. }
|
||||
| StmtKind::While { orelse, .. } => {
|
||||
if !orelse.contains(child) {
|
||||
allowed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
StmtKind::FunctionDef { .. }
|
||||
| StmtKind::AsyncFunctionDef { .. }
|
||||
| StmtKind::ClassDef { .. } => {
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
if !allowed {
|
||||
Some(Check::new(CheckKind::ContinueOutsideLoop, stmt.location))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ pub fn extract_all_names(stmt: &Stmt, scope: &Scope) -> Vec<String> {
|
||||
if let StmtKind::AugAssign { .. } = &stmt.node {
|
||||
if let Some(binding) = scope.values.get("__all__") {
|
||||
if let BindingKind::Export(existing) = &binding.kind {
|
||||
names.extend(existing.clone());
|
||||
names.extend_from_slice(existing);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -70,9 +70,7 @@ pub fn extract_all_names(stmt: &Stmt, scope: &Scope) -> Vec<String> {
|
||||
pub fn on_conditional_branch(parent_stack: &[usize], parents: &[&Stmt]) -> bool {
|
||||
for index in parent_stack.iter().rev() {
|
||||
let parent = parents[*index];
|
||||
if matches!(parent.node, StmtKind::If { .. })
|
||||
|| matches!(parent.node, StmtKind::While { .. })
|
||||
{
|
||||
if matches!(parent.node, StmtKind::If { .. } | StmtKind::While { .. }) {
|
||||
return true;
|
||||
}
|
||||
if let StmtKind::Expr { value } = &parent.node {
|
||||
@@ -89,10 +87,10 @@ pub fn on_conditional_branch(parent_stack: &[usize], parents: &[&Stmt]) -> bool
|
||||
pub fn in_nested_block(parent_stack: &[usize], parents: &[&Stmt]) -> bool {
|
||||
for index in parent_stack.iter().rev() {
|
||||
let parent = parents[*index];
|
||||
if matches!(parent.node, StmtKind::Try { .. })
|
||||
|| matches!(parent.node, StmtKind::If { .. })
|
||||
|| matches!(parent.node, StmtKind::With { .. })
|
||||
{
|
||||
if matches!(
|
||||
parent.node,
|
||||
StmtKind::Try { .. } | StmtKind::If { .. } | StmtKind::With { .. }
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -100,6 +98,26 @@ pub fn in_nested_block(parent_stack: &[usize], parents: &[&Stmt]) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Check if a node represents an unpacking assignment.
|
||||
pub fn is_unpacking_assignment(stmt: &Stmt) -> bool {
|
||||
if let StmtKind::Assign { targets, value, .. } = &stmt.node {
|
||||
if !targets.iter().any(|child| {
|
||||
matches!(
|
||||
child.node,
|
||||
ExprKind::Set { .. } | ExprKind::List { .. } | ExprKind::Tuple { .. }
|
||||
)
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
match &value.node {
|
||||
ExprKind::Set { .. } | ExprKind::List { .. } | ExprKind::Tuple { .. } => return false,
|
||||
_ => {}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Struct used to efficiently slice source code at (row, column) Locations.
|
||||
pub struct SourceCodeLocator<'a> {
|
||||
content: &'a str,
|
||||
|
||||
@@ -8,10 +8,15 @@ fn id() -> usize {
|
||||
COUNTER.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct FunctionScope {
|
||||
pub uses_locals: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum ScopeKind {
|
||||
Class,
|
||||
Function,
|
||||
Function(FunctionScope),
|
||||
Generator,
|
||||
Module,
|
||||
}
|
||||
@@ -35,8 +40,10 @@ impl Scope {
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum BindingKind {
|
||||
Annotation,
|
||||
Argument,
|
||||
Assignment,
|
||||
Binding,
|
||||
Builtin,
|
||||
ClassDefinition,
|
||||
Definition,
|
||||
@@ -51,5 +58,7 @@ pub enum BindingKind {
|
||||
pub struct Binding {
|
||||
pub kind: BindingKind,
|
||||
pub location: Location,
|
||||
pub used: Option<usize>,
|
||||
/// Tuple of (scope index, location) indicating the scope and location at which the binding was
|
||||
/// last used.
|
||||
pub used: Option<(usize, Location)>,
|
||||
}
|
||||
|
||||
17
src/cache.rs
17
src/cache.rs
@@ -1,11 +1,14 @@
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::fs::Metadata;
|
||||
use std::fs::{create_dir_all, File, Metadata};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Result;
|
||||
use cacache::Error::EntryNotFound;
|
||||
use filetime::FileTime;
|
||||
use log::error;
|
||||
use path_absolutize::Absolutize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::autofix::fixer;
|
||||
@@ -77,12 +80,22 @@ fn cache_key(path: &Path, settings: &Settings, autofix: &fixer::Mode) -> String
|
||||
autofix.hash(&mut hasher);
|
||||
format!(
|
||||
"{}@{}@{}",
|
||||
path.canonicalize().unwrap().to_string_lossy(),
|
||||
path.absolutize().unwrap().to_string_lossy(),
|
||||
VERSION,
|
||||
hasher.finish()
|
||||
)
|
||||
}
|
||||
|
||||
pub fn init() -> Result<()> {
|
||||
let gitignore_path = Path::new(cache_dir()).join(".gitignore");
|
||||
if gitignore_path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
create_dir_all(cache_dir())?;
|
||||
let mut file = File::create(gitignore_path)?;
|
||||
file.write_all(b"*").map_err(|e| e.into())
|
||||
}
|
||||
|
||||
pub fn get(
|
||||
path: &Path,
|
||||
metadata: &Metadata,
|
||||
|
||||
502
src/check_ast.rs
502
src/check_ast.rs
@@ -1,19 +1,21 @@
|
||||
use std::ops::Deref;
|
||||
use std::path::Path;
|
||||
|
||||
use rustpython_parser::ast::{
|
||||
Arg, Arguments, Constant, Excepthandler, ExcepthandlerKind, Expr, ExprContext, ExprKind,
|
||||
KeywordData, Location, Stmt, StmtKind, Suite,
|
||||
KeywordData, Location, Operator, Stmt, StmtKind, Suite,
|
||||
};
|
||||
use rustpython_parser::parser;
|
||||
|
||||
use crate::ast::operations::{extract_all_names, SourceCodeLocator};
|
||||
use crate::ast::relocate::relocate_expr;
|
||||
use crate::ast::types::{Binding, BindingKind, Scope, ScopeKind};
|
||||
use crate::ast::types::{Binding, BindingKind, FunctionScope, Scope, ScopeKind};
|
||||
use crate::ast::visitor::{walk_excepthandler, Visitor};
|
||||
use crate::ast::{checks, operations, visitor};
|
||||
use crate::autofix::fixer;
|
||||
use crate::checks::{Check, CheckCode, CheckKind};
|
||||
use crate::python::builtins::{BUILTINS, MAGIC_GLOBALS};
|
||||
use crate::python::future::ALL_FEATURE_NAMES;
|
||||
use crate::python::typing;
|
||||
use crate::settings::Settings;
|
||||
|
||||
@@ -24,7 +26,7 @@ struct Checker<'a> {
|
||||
locator: SourceCodeLocator<'a>,
|
||||
settings: &'a Settings,
|
||||
autofix: &'a fixer::Mode,
|
||||
path: &'a str,
|
||||
path: &'a Path,
|
||||
// Computed checks.
|
||||
checks: Vec<Check>,
|
||||
// Retain all scopes and parent nodes, along with a stack of indexes to track which are active
|
||||
@@ -34,7 +36,8 @@ struct Checker<'a> {
|
||||
scopes: Vec<Scope>,
|
||||
scope_stack: Vec<usize>,
|
||||
dead_scopes: Vec<usize>,
|
||||
deferred_annotations: Vec<(Location, &'a str)>,
|
||||
deferred_string_annotations: Vec<(Location, &'a str)>,
|
||||
deferred_annotations: Vec<(&'a Expr, Vec<usize>, Vec<usize>)>,
|
||||
deferred_functions: Vec<(&'a Stmt, Vec<usize>, Vec<usize>)>,
|
||||
deferred_lambdas: Vec<(&'a Expr, Vec<usize>, Vec<usize>)>,
|
||||
deferred_assignments: Vec<usize>,
|
||||
@@ -44,13 +47,15 @@ struct Checker<'a> {
|
||||
in_literal: bool,
|
||||
seen_non_import: bool,
|
||||
seen_docstring: bool,
|
||||
futures_allowed: bool,
|
||||
annotations_future_enabled: bool,
|
||||
}
|
||||
|
||||
impl<'a> Checker<'a> {
|
||||
pub fn new(
|
||||
settings: &'a Settings,
|
||||
autofix: &'a fixer::Mode,
|
||||
path: &'a str,
|
||||
path: &'a Path,
|
||||
content: &'a str,
|
||||
) -> Checker<'a> {
|
||||
Checker {
|
||||
@@ -64,6 +69,7 @@ impl<'a> Checker<'a> {
|
||||
scopes: vec![],
|
||||
scope_stack: vec![],
|
||||
dead_scopes: vec![],
|
||||
deferred_string_annotations: vec![],
|
||||
deferred_annotations: vec![],
|
||||
deferred_functions: vec![],
|
||||
deferred_lambdas: vec![],
|
||||
@@ -73,6 +79,8 @@ impl<'a> Checker<'a> {
|
||||
in_literal: false,
|
||||
seen_non_import: false,
|
||||
seen_docstring: false,
|
||||
futures_allowed: true,
|
||||
annotations_future_enabled: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,32 +110,57 @@ where
|
||||
|
||||
// Track whether we've seen docstrings, non-imports, etc.
|
||||
match &stmt.node {
|
||||
StmtKind::Import { .. } => {}
|
||||
StmtKind::ImportFrom { .. } => {}
|
||||
StmtKind::Expr { value } => {
|
||||
if !self.seen_docstring
|
||||
&& stmt.location.column() == 1
|
||||
&& !operations::in_nested_block(&self.parent_stack, &self.parents)
|
||||
{
|
||||
if let ExprKind::Constant {
|
||||
value: Constant::Str(_),
|
||||
..
|
||||
} = &value.node
|
||||
{
|
||||
self.seen_docstring = true;
|
||||
StmtKind::ImportFrom { module, .. } => {
|
||||
// Allow __future__ imports until we see a non-__future__ import.
|
||||
if self.futures_allowed {
|
||||
if let Some(module) = module {
|
||||
if module != "__future__" {
|
||||
self.futures_allowed = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !self.seen_non_import
|
||||
&& stmt.location.column() == 1
|
||||
}
|
||||
StmtKind::Import { .. } => {
|
||||
self.futures_allowed = false;
|
||||
}
|
||||
StmtKind::Expr { value } => {
|
||||
if self.seen_docstring
|
||||
&& !self.seen_non_import
|
||||
&& !operations::in_nested_block(&self.parent_stack, &self.parents)
|
||||
{
|
||||
self.seen_non_import = true;
|
||||
}
|
||||
|
||||
if !self.seen_docstring
|
||||
&& !operations::in_nested_block(&self.parent_stack, &self.parents)
|
||||
&& matches!(
|
||||
&value.node,
|
||||
ExprKind::Constant {
|
||||
value: Constant::Str(_),
|
||||
..
|
||||
},
|
||||
)
|
||||
{
|
||||
self.seen_docstring = true;
|
||||
}
|
||||
|
||||
// Allow docstrings to interrupt __future__ imports.
|
||||
if self.futures_allowed
|
||||
&& !matches!(
|
||||
&value.node,
|
||||
ExprKind::Constant {
|
||||
value: Constant::Str(_),
|
||||
..
|
||||
},
|
||||
)
|
||||
{
|
||||
self.futures_allowed = false;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.futures_allowed = false;
|
||||
|
||||
if !self.seen_non_import
|
||||
&& stmt.location.column() == 1
|
||||
&& !operations::in_nested_block(&self.parent_stack, &self.parents)
|
||||
{
|
||||
self.seen_non_import = true;
|
||||
@@ -151,13 +184,37 @@ where
|
||||
name.to_string(),
|
||||
Binding {
|
||||
kind: BindingKind::Assignment,
|
||||
used: Some(global_scope_id),
|
||||
used: Some((global_scope_id, stmt.location)),
|
||||
location: stmt.location,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if self.settings.select.contains(&CheckCode::E741) {
|
||||
self.checks.extend(names.iter().filter_map(|name| {
|
||||
checks::check_ambiguous_variable_name(name, stmt.location)
|
||||
}));
|
||||
}
|
||||
}
|
||||
StmtKind::Break => {
|
||||
if self.settings.select.contains(&CheckCode::F701) {
|
||||
if let Some(check) =
|
||||
checks::check_break_outside_loop(stmt, &self.parents, &self.parent_stack)
|
||||
{
|
||||
self.checks.push(check);
|
||||
}
|
||||
}
|
||||
}
|
||||
StmtKind::Continue => {
|
||||
if self.settings.select.contains(&CheckCode::F702) {
|
||||
if let Some(check) =
|
||||
checks::check_continue_outside_loop(stmt, &self.parents, &self.parent_stack)
|
||||
{
|
||||
self.checks.push(check);
|
||||
}
|
||||
}
|
||||
}
|
||||
StmtKind::FunctionDef {
|
||||
name,
|
||||
@@ -173,6 +230,12 @@ where
|
||||
args,
|
||||
..
|
||||
} => {
|
||||
if self.settings.select.contains(&CheckCode::E743) {
|
||||
if let Some(check) = checks::check_ambiguous_function_name(name, stmt.location)
|
||||
{
|
||||
self.checks.push(check);
|
||||
}
|
||||
}
|
||||
for expr in decorator_list {
|
||||
self.visit_expr(expr);
|
||||
}
|
||||
@@ -261,6 +324,12 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
if self.settings.select.contains(&CheckCode::E742) {
|
||||
if let Some(check) = checks::check_ambiguous_class_name(name, stmt.location) {
|
||||
self.checks.push(check);
|
||||
}
|
||||
}
|
||||
|
||||
for expr in bases {
|
||||
self.visit_expr(expr)
|
||||
}
|
||||
@@ -347,16 +416,36 @@ where
|
||||
name,
|
||||
Binding {
|
||||
kind: BindingKind::FutureImportation,
|
||||
used: Some(
|
||||
used: Some((
|
||||
self.scopes[*(self
|
||||
.scope_stack
|
||||
.last()
|
||||
.expect("No current scope found."))]
|
||||
.id,
|
||||
),
|
||||
stmt.location,
|
||||
)),
|
||||
location: stmt.location,
|
||||
},
|
||||
);
|
||||
|
||||
if alias.node.name == "annotations" {
|
||||
self.annotations_future_enabled = true;
|
||||
}
|
||||
|
||||
if self.settings.select.contains(&CheckCode::F407)
|
||||
&& !ALL_FEATURE_NAMES.contains(&alias.node.name.deref())
|
||||
{
|
||||
self.checks.push(Check::new(
|
||||
CheckKind::FutureFeatureNotDefined(alias.node.name.to_string()),
|
||||
stmt.location,
|
||||
));
|
||||
}
|
||||
|
||||
if self.settings.select.contains(&CheckCode::F404) && !self.futures_allowed
|
||||
{
|
||||
self.checks
|
||||
.push(Check::new(CheckKind::LateFutureImport, stmt.location));
|
||||
}
|
||||
} else if alias.node.name == "*" {
|
||||
self.add_binding(
|
||||
name,
|
||||
@@ -368,14 +457,31 @@ where
|
||||
);
|
||||
|
||||
if self.settings.select.contains(&CheckCode::F403) {
|
||||
self.checks
|
||||
.push(Check::new(CheckKind::ImportStarUsage, stmt.location));
|
||||
self.checks.push(Check::new(
|
||||
CheckKind::ImportStarUsage(
|
||||
module.clone().unwrap_or_else(|| "module".to_string()),
|
||||
),
|
||||
stmt.location,
|
||||
));
|
||||
}
|
||||
|
||||
if self.settings.select.contains(&CheckCode::F406) {
|
||||
let scope = &self.scopes
|
||||
[*(self.scope_stack.last().expect("No current scope found."))];
|
||||
if !matches!(scope.kind, ScopeKind::Module) {
|
||||
self.checks.push(Check::new(
|
||||
CheckKind::ImportStarNotPermitted(
|
||||
module.clone().unwrap_or_else(|| "module".to_string()),
|
||||
),
|
||||
stmt.location,
|
||||
));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let binding = Binding {
|
||||
kind: BindingKind::Importation(match module {
|
||||
None => name.clone(),
|
||||
Some(parent) => format!("{}.{}", parent, name.clone()),
|
||||
Some(parent) => format!("{}.{}", parent, name),
|
||||
}),
|
||||
used: None,
|
||||
location: stmt.location,
|
||||
@@ -484,6 +590,17 @@ where
|
||||
let prev_in_literal = self.in_literal;
|
||||
let prev_in_annotation = self.in_annotation;
|
||||
|
||||
// Important:
|
||||
if self.in_annotation && self.annotations_future_enabled {
|
||||
self.deferred_annotations.push((
|
||||
expr,
|
||||
self.scope_stack.clone(),
|
||||
self.parent_stack.clone(),
|
||||
));
|
||||
visitor::walk_expr(self, expr);
|
||||
return;
|
||||
}
|
||||
|
||||
// Pre-visit.
|
||||
match &expr.node {
|
||||
ExprKind::Subscript { value, .. } => {
|
||||
@@ -491,7 +608,7 @@ where
|
||||
self.in_literal = true;
|
||||
}
|
||||
}
|
||||
ExprKind::Tuple { elts, ctx } => {
|
||||
ExprKind::Tuple { elts, ctx } | ExprKind::List { elts, ctx } => {
|
||||
if matches!(ctx, ExprContext::Store) {
|
||||
let check_too_many_expressions =
|
||||
self.settings.select.contains(&CheckCode::F621);
|
||||
@@ -507,12 +624,19 @@ where
|
||||
}
|
||||
}
|
||||
}
|
||||
ExprKind::Name { ctx, .. } => match ctx {
|
||||
ExprKind::Name { id, ctx } => match ctx {
|
||||
ExprContext::Load => self.handle_node_load(expr),
|
||||
ExprContext::Store => {
|
||||
if self.settings.select.contains(&CheckCode::E741) {
|
||||
if let Some(check) =
|
||||
checks::check_ambiguous_variable_name(id, expr.location)
|
||||
{
|
||||
self.checks.push(check);
|
||||
}
|
||||
}
|
||||
let parent =
|
||||
self.parents[*(self.parent_stack.last().expect("No parent found."))];
|
||||
self.handle_node_store(expr, Some(parent));
|
||||
self.handle_node_store(expr, parent);
|
||||
}
|
||||
ExprContext::Del => self.handle_node_delete(expr),
|
||||
},
|
||||
@@ -522,6 +646,33 @@ where
|
||||
self.checks.push(check)
|
||||
}
|
||||
}
|
||||
|
||||
if let ExprKind::Name { id, ctx } = &func.node {
|
||||
if id == "locals" && matches!(ctx, ExprContext::Load) {
|
||||
let scope = &mut self.scopes[*(self
|
||||
.scope_stack
|
||||
.last_mut()
|
||||
.expect("No current scope found."))];
|
||||
if matches!(
|
||||
scope.kind,
|
||||
ScopeKind::Function(FunctionScope { uses_locals: false })
|
||||
) {
|
||||
scope.kind = ScopeKind::Function(FunctionScope { uses_locals: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// if id == "locals" {
|
||||
// let scope = &self.scopes
|
||||
// [*(self.scope_stack.last().expect("No current scope found."))];
|
||||
// if matches!(scope.kind, ScopeKind::Function(_)) {
|
||||
// let parent =
|
||||
// self.parents[*(self.parent_stack.last().expect("No parent found."))];
|
||||
// if matches!(parent.node, StmtKind::Call)
|
||||
// }
|
||||
//
|
||||
// }
|
||||
}
|
||||
ExprKind::Dict { keys, .. } => {
|
||||
let check_repeated_literals = self.settings.select.contains(&CheckCode::F601);
|
||||
@@ -541,8 +692,7 @@ where
|
||||
.settings
|
||||
.select
|
||||
.contains(CheckKind::YieldOutsideFunction.code())
|
||||
&& matches!(scope.kind, ScopeKind::Class)
|
||||
|| matches!(scope.kind, ScopeKind::Module)
|
||||
&& matches!(scope.kind, ScopeKind::Class | ScopeKind::Module)
|
||||
{
|
||||
self.checks
|
||||
.push(Check::new(CheckKind::YieldOutsideFunction, expr.location));
|
||||
@@ -565,6 +715,28 @@ where
|
||||
}
|
||||
self.in_f_string = true;
|
||||
}
|
||||
ExprKind::BinOp {
|
||||
left,
|
||||
op: Operator::RShift,
|
||||
..
|
||||
} => {
|
||||
if self.settings.select.contains(&CheckCode::F633) {
|
||||
if let ExprKind::Name { id, .. } = &left.node {
|
||||
if id == "print" {
|
||||
let scope = &self.scopes
|
||||
[*(self.scope_stack.last().expect("No current scope found."))];
|
||||
if let Some(Binding {
|
||||
kind: BindingKind::Builtin,
|
||||
..
|
||||
}) = scope.values.get("print")
|
||||
{
|
||||
self.checks
|
||||
.push(Check::new(CheckKind::InvalidPrintSyntax, left.location));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ExprKind::UnaryOp { op, operand } => {
|
||||
let check_not_in = self.settings.select.contains(&CheckCode::E713);
|
||||
let check_not_is = self.settings.select.contains(&CheckCode::E714);
|
||||
@@ -593,12 +765,30 @@ where
|
||||
check_true_false_comparisons,
|
||||
));
|
||||
}
|
||||
|
||||
if self.settings.select.contains(&CheckCode::F632) {
|
||||
self.checks.extend(checks::check_is_literal(
|
||||
left,
|
||||
ops,
|
||||
comparators,
|
||||
expr.location,
|
||||
));
|
||||
}
|
||||
|
||||
if self.settings.select.contains(&CheckCode::E721) {
|
||||
self.checks.extend(checks::check_type_comparison(
|
||||
ops,
|
||||
comparators,
|
||||
expr.location,
|
||||
));
|
||||
}
|
||||
}
|
||||
ExprKind::Constant {
|
||||
value: Constant::Str(value),
|
||||
..
|
||||
} if self.in_annotation && !self.in_literal => {
|
||||
self.deferred_annotations.push((expr.location, value));
|
||||
self.deferred_string_annotations
|
||||
.push((expr.location, value));
|
||||
}
|
||||
ExprKind::GeneratorExp { .. }
|
||||
| ExprKind::ListComp { .. }
|
||||
@@ -659,7 +849,7 @@ where
|
||||
} else if match_name_or_attr(func, "NamedTuple") {
|
||||
self.visit_expr(func);
|
||||
|
||||
// NamedTuple("a", [("a", int)])
|
||||
// Ex) NamedTuple("a", [("a", int)])
|
||||
if args.len() > 1 {
|
||||
match &args[1].node {
|
||||
ExprKind::List { elts, .. } | ExprKind::Tuple { elts, .. } => {
|
||||
@@ -683,7 +873,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
// NamedTuple("a", a=int)
|
||||
// Ex) NamedTuple("a", a=int)
|
||||
for keyword in keywords {
|
||||
let KeywordData { value, .. } = &keyword.node;
|
||||
self.visit_annotation(value);
|
||||
@@ -691,7 +881,7 @@ where
|
||||
} else if match_name_or_attr(func, "TypedDict") {
|
||||
self.visit_expr(func);
|
||||
|
||||
// TypedDict("a", {"a": int})
|
||||
// Ex) TypedDict("a", {"a": int})
|
||||
if args.len() > 1 {
|
||||
if let ExprKind::Dict { keys, values } = &args[1].node {
|
||||
for key in keys {
|
||||
@@ -705,7 +895,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
// TypedDict("a", a=int)
|
||||
// Ex) TypedDict("a", a=int)
|
||||
for keyword in keywords {
|
||||
let KeywordData { value, .. } = &keyword.node;
|
||||
self.visit_annotation(value);
|
||||
@@ -744,13 +934,45 @@ where
|
||||
|
||||
fn visit_excepthandler(&mut self, excepthandler: &'b Excepthandler) {
|
||||
match &excepthandler.node {
|
||||
ExcepthandlerKind::ExceptHandler { name, .. } => match name {
|
||||
Some(name) => {
|
||||
let scope =
|
||||
&self.scopes[*(self.scope_stack.last().expect("No current scope found."))];
|
||||
if scope.values.contains_key(name) {
|
||||
ExcepthandlerKind::ExceptHandler { type_, name, .. } => {
|
||||
if self.settings.select.contains(&CheckCode::E722) && type_.is_none() {
|
||||
self.checks.push(Check::new(
|
||||
CheckKind::DoNotUseBareExcept,
|
||||
excepthandler.location,
|
||||
));
|
||||
}
|
||||
match name {
|
||||
Some(name) => {
|
||||
if self.settings.select.contains(&CheckCode::E741) {
|
||||
if let Some(check) =
|
||||
checks::check_ambiguous_variable_name(name, excepthandler.location)
|
||||
{
|
||||
self.checks.push(check);
|
||||
}
|
||||
}
|
||||
let scope = &self.scopes
|
||||
[*(self.scope_stack.last().expect("No current scope found."))];
|
||||
if scope.values.contains_key(name) {
|
||||
let parent = self.parents
|
||||
[*(self.parent_stack.last().expect("No parent found."))];
|
||||
self.handle_node_store(
|
||||
&Expr::new(
|
||||
excepthandler.location,
|
||||
ExprKind::Name {
|
||||
id: name.to_string(),
|
||||
ctx: ExprContext::Store,
|
||||
},
|
||||
),
|
||||
parent,
|
||||
);
|
||||
self.parents.push(parent);
|
||||
}
|
||||
|
||||
let parent =
|
||||
self.parents[*(self.parent_stack.last().expect("No parent found."))];
|
||||
let scope = &self.scopes
|
||||
[*(self.scope_stack.last().expect("No current scope found."))];
|
||||
let definition = scope.values.get(name).cloned();
|
||||
self.handle_node_store(
|
||||
&Expr::new(
|
||||
excepthandler.location,
|
||||
@@ -759,48 +981,32 @@ where
|
||||
ctx: ExprContext::Store,
|
||||
},
|
||||
),
|
||||
Some(parent),
|
||||
parent,
|
||||
);
|
||||
self.parents.push(parent);
|
||||
}
|
||||
|
||||
let parent =
|
||||
self.parents[*(self.parent_stack.last().expect("No parent found."))];
|
||||
let scope =
|
||||
&self.scopes[*(self.scope_stack.last().expect("No current scope found."))];
|
||||
let definition = scope.values.get(name).cloned();
|
||||
self.handle_node_store(
|
||||
&Expr::new(
|
||||
excepthandler.location,
|
||||
ExprKind::Name {
|
||||
id: name.to_string(),
|
||||
ctx: ExprContext::Store,
|
||||
},
|
||||
),
|
||||
Some(parent),
|
||||
);
|
||||
self.parents.push(parent);
|
||||
walk_excepthandler(self, excepthandler);
|
||||
|
||||
walk_excepthandler(self, excepthandler);
|
||||
let scope = &mut self.scopes
|
||||
[*(self.scope_stack.last().expect("No current scope found."))];
|
||||
if let Some(binding) = &scope.values.remove(name) {
|
||||
if self.settings.select.contains(&CheckCode::F841)
|
||||
&& binding.used.is_none()
|
||||
{
|
||||
self.checks.push(Check::new(
|
||||
CheckKind::UnusedVariable(name.to_string()),
|
||||
excepthandler.location,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let scope = &mut self.scopes
|
||||
[*(self.scope_stack.last().expect("No current scope found."))];
|
||||
if let Some(binding) = &scope.values.remove(name) {
|
||||
if self.settings.select.contains(&CheckCode::F841) && binding.used.is_none()
|
||||
{
|
||||
self.checks.push(Check::new(
|
||||
CheckKind::UnusedVariable(name.to_string()),
|
||||
excepthandler.location,
|
||||
));
|
||||
if let Some(binding) = definition {
|
||||
scope.values.insert(name.to_string(), binding);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(binding) = definition {
|
||||
scope.values.insert(name.to_string(), binding);
|
||||
}
|
||||
None => walk_excepthandler(self, excepthandler),
|
||||
}
|
||||
None => walk_excepthandler(self, excepthandler),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -838,6 +1044,13 @@ where
|
||||
location: arg.location,
|
||||
},
|
||||
);
|
||||
|
||||
if self.settings.select.contains(&CheckCode::E741) {
|
||||
if let Some(check) = checks::check_ambiguous_variable_name(&arg.node.arg, arg.location)
|
||||
{
|
||||
self.checks.push(check);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -871,7 +1084,7 @@ impl<'a> Checker<'a> {
|
||||
|
||||
for builtin in BUILTINS {
|
||||
scope.values.insert(
|
||||
builtin.to_string(),
|
||||
(*builtin).to_string(),
|
||||
Binding {
|
||||
kind: BindingKind::Builtin,
|
||||
location: Default::default(),
|
||||
@@ -881,7 +1094,7 @@ impl<'a> Checker<'a> {
|
||||
}
|
||||
for builtin in MAGIC_GLOBALS {
|
||||
scope.values.insert(
|
||||
builtin.to_string(),
|
||||
(*builtin).to_string(),
|
||||
Binding {
|
||||
kind: BindingKind::Builtin,
|
||||
location: Default::default(),
|
||||
@@ -923,7 +1136,7 @@ impl<'a> Checker<'a> {
|
||||
}
|
||||
}
|
||||
if let Some(binding) = scope.values.get_mut(id) {
|
||||
binding.used = Some(scope_id);
|
||||
binding.used = Some((scope_id, expr.location));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -932,6 +1145,10 @@ impl<'a> Checker<'a> {
|
||||
}
|
||||
|
||||
if self.settings.select.contains(&CheckCode::F821) {
|
||||
// Allow __path__.
|
||||
if self.path.ends_with("__init__.py") && id == "__path__" {
|
||||
return;
|
||||
}
|
||||
self.checks.push(Check::new(
|
||||
CheckKind::UndefinedName(id.clone()),
|
||||
expr.location,
|
||||
@@ -940,65 +1157,88 @@ impl<'a> Checker<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_node_store(&mut self, expr: &Expr, parent: Option<&Stmt>) {
|
||||
fn handle_node_store(&mut self, expr: &Expr, parent: &Stmt) {
|
||||
if let ExprKind::Name { id, .. } = &expr.node {
|
||||
let current =
|
||||
&self.scopes[*(self.scope_stack.last().expect("No current scope found."))];
|
||||
|
||||
if self.settings.select.contains(&CheckCode::F823)
|
||||
&& matches!(current.kind, ScopeKind::Function)
|
||||
&& matches!(current.kind, ScopeKind::Function(_))
|
||||
&& !current.values.contains_key(id)
|
||||
{
|
||||
for scope in self.scopes.iter().rev().skip(1) {
|
||||
if matches!(scope.kind, ScopeKind::Function)
|
||||
|| matches!(scope.kind, ScopeKind::Module)
|
||||
{
|
||||
let used = scope
|
||||
.values
|
||||
.get(id)
|
||||
.map(|binding| binding.used)
|
||||
.unwrap_or_default();
|
||||
if let Some(scope_id) = used {
|
||||
if scope_id == current.id {
|
||||
self.checks.push(Check::new(
|
||||
CheckKind::UndefinedLocal(id.clone()),
|
||||
expr.location,
|
||||
));
|
||||
if matches!(scope.kind, ScopeKind::Function(_) | ScopeKind::Module) {
|
||||
if let Some(binding) = scope.values.get(id) {
|
||||
if let Some((scope_id, location)) = binding.used {
|
||||
if scope_id == current.id {
|
||||
self.checks.push(Check::new(
|
||||
CheckKind::UndefinedLocal(id.clone()),
|
||||
location,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO(charlie): Handle alternate binding types (like `Annotation`).
|
||||
if id == "__all__"
|
||||
&& matches!(current.kind, ScopeKind::Module)
|
||||
&& parent
|
||||
.map(|stmt| {
|
||||
matches!(stmt.node, StmtKind::Assign { .. })
|
||||
|| matches!(stmt.node, StmtKind::AugAssign { .. })
|
||||
|| matches!(stmt.node, StmtKind::AnnAssign { .. })
|
||||
})
|
||||
.unwrap_or_default()
|
||||
if matches!(parent.node, StmtKind::AnnAssign { value: None, .. }) {
|
||||
self.add_binding(
|
||||
id.to_string(),
|
||||
Binding {
|
||||
kind: BindingKind::Annotation,
|
||||
used: None,
|
||||
location: expr.location,
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO(charlie): Include comprehensions here.
|
||||
if matches!(
|
||||
parent.node,
|
||||
StmtKind::For { .. } | StmtKind::AsyncFor { .. }
|
||||
) || operations::is_unpacking_assignment(parent)
|
||||
{
|
||||
self.add_binding(
|
||||
id.to_string(),
|
||||
Binding {
|
||||
kind: BindingKind::Export(extract_all_names(parent.unwrap(), current)),
|
||||
kind: BindingKind::Binding,
|
||||
used: None,
|
||||
location: expr.location,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
if id == "__all__"
|
||||
&& matches!(current.kind, ScopeKind::Module)
|
||||
&& matches!(
|
||||
parent.node,
|
||||
StmtKind::Assign { .. }
|
||||
| StmtKind::AugAssign { .. }
|
||||
| StmtKind::AnnAssign { .. }
|
||||
)
|
||||
{
|
||||
self.add_binding(
|
||||
id.to_string(),
|
||||
Binding {
|
||||
kind: BindingKind::Assignment,
|
||||
kind: BindingKind::Export(extract_all_names(parent, current)),
|
||||
used: None,
|
||||
location: expr.location,
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
self.add_binding(
|
||||
id.to_string(),
|
||||
Binding {
|
||||
kind: BindingKind::Assignment,
|
||||
used: None,
|
||||
location: expr.location,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1021,15 +1261,27 @@ impl<'a> Checker<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn check_deferred_annotations<'b>(&mut self, path: &str, allocator: &'b mut Vec<Expr>)
|
||||
fn check_deferred_annotations(&mut self) {
|
||||
while let Some((expr, scopes, parents)) = self.deferred_annotations.pop() {
|
||||
self.parent_stack = parents;
|
||||
self.scope_stack = scopes;
|
||||
self.visit_expr(expr);
|
||||
}
|
||||
}
|
||||
|
||||
fn check_deferred_string_annotations<'b>(&mut self, allocator: &'b mut Vec<Expr>)
|
||||
where
|
||||
'b: 'a,
|
||||
{
|
||||
while !self.deferred_annotations.is_empty() {
|
||||
let (location, expression) = self.deferred_annotations.pop().unwrap();
|
||||
if let Ok(mut expr) = parser::parse_expression(expression, path) {
|
||||
while let Some((location, expression)) = self.deferred_string_annotations.pop() {
|
||||
if let Ok(mut expr) = parser::parse_expression(expression, "<filename>") {
|
||||
relocate_expr(&mut expr, location);
|
||||
allocator.push(expr);
|
||||
} else if self.settings.select.contains(&CheckCode::F722) {
|
||||
self.checks.push(Check::new(
|
||||
CheckKind::ForwardAnnotationSyntaxError(expression.to_string()),
|
||||
location,
|
||||
));
|
||||
}
|
||||
}
|
||||
for expr in allocator {
|
||||
@@ -1038,12 +1290,10 @@ impl<'a> Checker<'a> {
|
||||
}
|
||||
|
||||
fn check_deferred_functions(&mut self) {
|
||||
while !self.deferred_functions.is_empty() {
|
||||
let (stmt, scopes, parents) = self.deferred_functions.pop().unwrap();
|
||||
|
||||
while let Some((stmt, scopes, parents)) = self.deferred_functions.pop() {
|
||||
self.parent_stack = parents;
|
||||
self.scope_stack = scopes;
|
||||
self.push_scope(Scope::new(ScopeKind::Function));
|
||||
self.push_scope(Scope::new(ScopeKind::Function(Default::default())));
|
||||
|
||||
match &stmt.node {
|
||||
StmtKind::FunctionDef { body, args, .. }
|
||||
@@ -1064,12 +1314,10 @@ impl<'a> Checker<'a> {
|
||||
}
|
||||
|
||||
fn check_deferred_lambdas(&mut self) {
|
||||
while !self.deferred_lambdas.is_empty() {
|
||||
let (expr, scopes, parents) = self.deferred_lambdas.pop().unwrap();
|
||||
|
||||
while let Some((expr, scopes, parents)) = self.deferred_lambdas.pop() {
|
||||
self.parent_stack = parents;
|
||||
self.scope_stack = scopes;
|
||||
self.push_scope(Scope::new(ScopeKind::Function));
|
||||
self.push_scope(Scope::new(ScopeKind::Function(Default::default())));
|
||||
|
||||
if let ExprKind::Lambda { args, body } = &expr.node {
|
||||
self.visit_arguments(args);
|
||||
@@ -1084,8 +1332,7 @@ impl<'a> Checker<'a> {
|
||||
}
|
||||
|
||||
fn check_deferred_assignments(&mut self) {
|
||||
while !self.deferred_assignments.is_empty() {
|
||||
let index = self.deferred_assignments.pop().unwrap();
|
||||
while let Some(index) = self.deferred_assignments.pop() {
|
||||
if self.settings.select.contains(&CheckCode::F841) {
|
||||
self.checks
|
||||
.extend(checks::check_unused_variables(&self.scopes[index]));
|
||||
@@ -1100,7 +1347,7 @@ impl<'a> Checker<'a> {
|
||||
return;
|
||||
}
|
||||
|
||||
for index in self.dead_scopes.clone() {
|
||||
for index in self.dead_scopes.iter().copied() {
|
||||
let scope = &self.scopes[index];
|
||||
|
||||
let all_binding = scope.values.get("__all__");
|
||||
@@ -1110,7 +1357,7 @@ impl<'a> Checker<'a> {
|
||||
});
|
||||
|
||||
if self.settings.select.contains(&CheckCode::F822)
|
||||
&& !Path::new(self.path).ends_with("__init__.py")
|
||||
&& !self.path.ends_with("__init__.py")
|
||||
{
|
||||
if let Some(binding) = all_binding {
|
||||
if let Some(names) = all_names {
|
||||
@@ -1156,7 +1403,7 @@ pub fn check_ast(
|
||||
content: &str,
|
||||
settings: &Settings,
|
||||
autofix: &fixer::Mode,
|
||||
path: &str,
|
||||
path: &Path,
|
||||
) -> Vec<Check> {
|
||||
let mut checker = Checker::new(settings, autofix, path, content);
|
||||
checker.push_scope(Scope::new(ScopeKind::Module));
|
||||
@@ -1171,8 +1418,9 @@ pub fn check_ast(
|
||||
checker.check_deferred_functions();
|
||||
checker.check_deferred_lambdas();
|
||||
checker.check_deferred_assignments();
|
||||
checker.check_deferred_annotations();
|
||||
let mut allocator = vec![];
|
||||
checker.check_deferred_annotations(path, &mut allocator);
|
||||
checker.check_deferred_string_annotations(&mut allocator);
|
||||
|
||||
// Reset the scope to module-level, and check all consumed scopes.
|
||||
checker.scope_stack = vec![GLOBAL_SCOPE_INDEX];
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use rustpython_parser::ast::Location;
|
||||
|
||||
use crate::checks::{Check, CheckKind};
|
||||
use crate::checks::{Check, CheckCode, CheckKind};
|
||||
use crate::settings::Settings;
|
||||
|
||||
/// Whether the given line is too long and should be reported.
|
||||
fn should_enforce_line_length(line: &str, limit: usize) -> bool {
|
||||
if line.len() > limit {
|
||||
fn should_enforce_line_length(line: &str, length: usize, limit: usize) -> bool {
|
||||
if length > limit {
|
||||
let mut chunks = line.split_whitespace();
|
||||
if let (Some(first), Some(_)) = (chunks.next(), chunks.next()) {
|
||||
// Do not enforce the line length for commented lines with a single word
|
||||
@@ -20,7 +20,7 @@ fn should_enforce_line_length(line: &str, limit: usize) -> bool {
|
||||
}
|
||||
|
||||
pub fn check_lines(checks: &mut Vec<Check>, contents: &str, settings: &Settings) {
|
||||
let enforce_line_too_long = settings.select.contains(CheckKind::LineTooLong.code());
|
||||
let enforce_line_too_long = settings.select.contains(&CheckCode::E501);
|
||||
|
||||
let mut line_checks = vec![];
|
||||
let mut ignored = vec![];
|
||||
@@ -34,13 +34,16 @@ pub fn check_lines(checks: &mut Vec<Check>, contents: &str, settings: &Settings)
|
||||
}
|
||||
|
||||
// Enforce line length.
|
||||
if enforce_line_too_long && should_enforce_line_length(line, settings.line_length) {
|
||||
let check = Check::new(
|
||||
CheckKind::LineTooLong,
|
||||
Location::new(row + 1, settings.line_length + 1),
|
||||
);
|
||||
if !check.is_inline_ignored(line) {
|
||||
line_checks.push(check);
|
||||
if enforce_line_too_long {
|
||||
let line_length = line.chars().count();
|
||||
if should_enforce_line_length(line, line_length, settings.line_length) {
|
||||
let check = Check::new(
|
||||
CheckKind::LineTooLong(line_length, settings.line_length),
|
||||
Location::new(row + 1, settings.line_length + 1),
|
||||
);
|
||||
if !check.is_inline_ignored(line) {
|
||||
line_checks.push(check);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,3 +53,29 @@ pub fn check_lines(checks: &mut Vec<Check>, contents: &str, settings: &Settings)
|
||||
}
|
||||
checks.extend(line_checks);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::check_lines;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn e501_non_ascii_char() {
|
||||
let line = "'\u{4e9c}' * 2"; // 7 in UTF-32, 9 in UTF-8.
|
||||
let check_with_max_line_length = |line_length: usize| {
|
||||
let mut checks: Vec<Check> = vec![];
|
||||
let settings = Settings {
|
||||
line_length,
|
||||
exclude: vec![],
|
||||
extend_exclude: vec![],
|
||||
select: BTreeSet::from_iter(vec![CheckCode::E501]),
|
||||
};
|
||||
check_lines(&mut checks, line, &settings);
|
||||
return checks;
|
||||
};
|
||||
assert!(!check_with_max_line_length(6).is_empty());
|
||||
assert!(check_with_max_line_length(7).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
306
src/checks.rs
306
src/checks.rs
@@ -6,7 +6,52 @@ use regex::Regex;
|
||||
use rustpython_parser::ast::Location;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Hash, PartialOrd, Ord)]
|
||||
pub const ALL_CHECK_CODES: [CheckCode; 42] = [
|
||||
CheckCode::E402,
|
||||
CheckCode::E501,
|
||||
CheckCode::E711,
|
||||
CheckCode::E712,
|
||||
CheckCode::E713,
|
||||
CheckCode::E714,
|
||||
CheckCode::E721,
|
||||
CheckCode::E722,
|
||||
CheckCode::E731,
|
||||
CheckCode::E741,
|
||||
CheckCode::E742,
|
||||
CheckCode::E743,
|
||||
CheckCode::E902,
|
||||
CheckCode::E999,
|
||||
CheckCode::F401,
|
||||
CheckCode::F403,
|
||||
CheckCode::F404,
|
||||
CheckCode::F406,
|
||||
CheckCode::F407,
|
||||
CheckCode::F541,
|
||||
CheckCode::F601,
|
||||
CheckCode::F602,
|
||||
CheckCode::F621,
|
||||
CheckCode::F622,
|
||||
CheckCode::F631,
|
||||
CheckCode::F632,
|
||||
CheckCode::F633,
|
||||
CheckCode::F634,
|
||||
CheckCode::F701,
|
||||
CheckCode::F702,
|
||||
CheckCode::F704,
|
||||
CheckCode::F706,
|
||||
CheckCode::F707,
|
||||
CheckCode::F722,
|
||||
CheckCode::F821,
|
||||
CheckCode::F822,
|
||||
CheckCode::F823,
|
||||
CheckCode::F831,
|
||||
CheckCode::F841,
|
||||
CheckCode::F901,
|
||||
CheckCode::R001,
|
||||
CheckCode::R002,
|
||||
];
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize, Hash, PartialOrd, Ord)]
|
||||
pub enum CheckCode {
|
||||
E402,
|
||||
E501,
|
||||
@@ -14,20 +59,34 @@ pub enum CheckCode {
|
||||
E712,
|
||||
E713,
|
||||
E714,
|
||||
E721,
|
||||
E722,
|
||||
E731,
|
||||
E741,
|
||||
E742,
|
||||
E743,
|
||||
E902,
|
||||
E999,
|
||||
F401,
|
||||
F403,
|
||||
F404,
|
||||
F406,
|
||||
F407,
|
||||
F541,
|
||||
F601,
|
||||
F602,
|
||||
F621,
|
||||
F622,
|
||||
F631,
|
||||
F632,
|
||||
F633,
|
||||
F634,
|
||||
F701,
|
||||
F702,
|
||||
F704,
|
||||
F706,
|
||||
F707,
|
||||
F722,
|
||||
F821,
|
||||
F822,
|
||||
F823,
|
||||
@@ -49,20 +108,34 @@ impl FromStr for CheckCode {
|
||||
"E712" => Ok(CheckCode::E712),
|
||||
"E713" => Ok(CheckCode::E713),
|
||||
"E714" => Ok(CheckCode::E714),
|
||||
"E721" => Ok(CheckCode::E721),
|
||||
"E722" => Ok(CheckCode::E722),
|
||||
"E731" => Ok(CheckCode::E731),
|
||||
"E741" => Ok(CheckCode::E741),
|
||||
"E742" => Ok(CheckCode::E742),
|
||||
"E743" => Ok(CheckCode::E743),
|
||||
"E902" => Ok(CheckCode::E902),
|
||||
"E999" => Ok(CheckCode::E999),
|
||||
"F401" => Ok(CheckCode::F401),
|
||||
"F403" => Ok(CheckCode::F403),
|
||||
"F404" => Ok(CheckCode::F404),
|
||||
"F406" => Ok(CheckCode::F406),
|
||||
"F407" => Ok(CheckCode::F407),
|
||||
"F541" => Ok(CheckCode::F541),
|
||||
"F601" => Ok(CheckCode::F601),
|
||||
"F602" => Ok(CheckCode::F602),
|
||||
"F621" => Ok(CheckCode::F621),
|
||||
"F622" => Ok(CheckCode::F622),
|
||||
"F631" => Ok(CheckCode::F631),
|
||||
"F632" => Ok(CheckCode::F632),
|
||||
"F633" => Ok(CheckCode::F633),
|
||||
"F634" => Ok(CheckCode::F634),
|
||||
"F701" => Ok(CheckCode::F701),
|
||||
"F702" => Ok(CheckCode::F702),
|
||||
"F704" => Ok(CheckCode::F704),
|
||||
"F706" => Ok(CheckCode::F706),
|
||||
"F707" => Ok(CheckCode::F707),
|
||||
"F722" => Ok(CheckCode::F722),
|
||||
"F821" => Ok(CheckCode::F821),
|
||||
"F822" => Ok(CheckCode::F822),
|
||||
"F823" => Ok(CheckCode::F823),
|
||||
@@ -85,20 +158,34 @@ impl CheckCode {
|
||||
CheckCode::E712 => "E712",
|
||||
CheckCode::E713 => "E713",
|
||||
CheckCode::E714 => "E714",
|
||||
CheckCode::E721 => "E721",
|
||||
CheckCode::E722 => "E722",
|
||||
CheckCode::E731 => "E731",
|
||||
CheckCode::E741 => "E741",
|
||||
CheckCode::E742 => "E742",
|
||||
CheckCode::E743 => "E743",
|
||||
CheckCode::E902 => "E902",
|
||||
CheckCode::E999 => "E999",
|
||||
CheckCode::F401 => "F401",
|
||||
CheckCode::F403 => "F403",
|
||||
CheckCode::F404 => "F404",
|
||||
CheckCode::F406 => "F406",
|
||||
CheckCode::F407 => "F407",
|
||||
CheckCode::F541 => "F541",
|
||||
CheckCode::F601 => "F601",
|
||||
CheckCode::F602 => "F602",
|
||||
CheckCode::F621 => "F621",
|
||||
CheckCode::F622 => "F622",
|
||||
CheckCode::F631 => "F631",
|
||||
CheckCode::F632 => "F632",
|
||||
CheckCode::F633 => "F633",
|
||||
CheckCode::F634 => "F634",
|
||||
CheckCode::F701 => "F701",
|
||||
CheckCode::F702 => "F702",
|
||||
CheckCode::F704 => "F704",
|
||||
CheckCode::F706 => "F706",
|
||||
CheckCode::F707 => "F707",
|
||||
CheckCode::F722 => "F722",
|
||||
CheckCode::F821 => "F821",
|
||||
CheckCode::F822 => "F822",
|
||||
CheckCode::F823 => "F823",
|
||||
@@ -110,37 +197,60 @@ impl CheckCode {
|
||||
}
|
||||
}
|
||||
|
||||
/// The source for the check (either the AST, or the physical lines).
|
||||
/// The source for the check (either the AST, the filesystem, or the physical lines).
|
||||
pub fn lint_source(&self) -> &'static LintSource {
|
||||
match self {
|
||||
CheckCode::E402 => &LintSource::AST,
|
||||
CheckCode::E501 => &LintSource::Lines,
|
||||
CheckCode::E711 => &LintSource::AST,
|
||||
CheckCode::E712 => &LintSource::AST,
|
||||
CheckCode::E713 => &LintSource::AST,
|
||||
CheckCode::E714 => &LintSource::AST,
|
||||
CheckCode::E731 => &LintSource::AST,
|
||||
CheckCode::E902 => &LintSource::FileSystem,
|
||||
CheckCode::F401 => &LintSource::AST,
|
||||
CheckCode::F403 => &LintSource::AST,
|
||||
CheckCode::F541 => &LintSource::AST,
|
||||
CheckCode::F601 => &LintSource::AST,
|
||||
CheckCode::F602 => &LintSource::AST,
|
||||
CheckCode::F621 => &LintSource::AST,
|
||||
CheckCode::F622 => &LintSource::AST,
|
||||
CheckCode::F631 => &LintSource::AST,
|
||||
CheckCode::F634 => &LintSource::AST,
|
||||
CheckCode::F704 => &LintSource::AST,
|
||||
CheckCode::F706 => &LintSource::AST,
|
||||
CheckCode::F707 => &LintSource::AST,
|
||||
CheckCode::F821 => &LintSource::AST,
|
||||
CheckCode::F822 => &LintSource::AST,
|
||||
CheckCode::F823 => &LintSource::AST,
|
||||
CheckCode::F831 => &LintSource::AST,
|
||||
CheckCode::F841 => &LintSource::AST,
|
||||
CheckCode::F901 => &LintSource::AST,
|
||||
CheckCode::R001 => &LintSource::AST,
|
||||
CheckCode::R002 => &LintSource::AST,
|
||||
CheckCode::E902 | CheckCode::E999 => &LintSource::FileSystem,
|
||||
_ => &LintSource::AST,
|
||||
}
|
||||
}
|
||||
|
||||
/// A placeholder representation of the CheckKind for the check.
|
||||
pub fn kind(&self) -> CheckKind {
|
||||
match self {
|
||||
CheckCode::E742 => CheckKind::AmbiguousClassName("...".to_string()),
|
||||
CheckCode::E743 => CheckKind::AmbiguousFunctionName("...".to_string()),
|
||||
CheckCode::E741 => CheckKind::AmbiguousVariableName("...".to_string()),
|
||||
CheckCode::F631 => CheckKind::AssertTuple,
|
||||
CheckCode::F701 => CheckKind::BreakOutsideLoop,
|
||||
CheckCode::F702 => CheckKind::ContinueOutsideLoop,
|
||||
CheckCode::F707 => CheckKind::DefaultExceptNotLast,
|
||||
CheckCode::E731 => CheckKind::DoNotAssignLambda,
|
||||
CheckCode::E722 => CheckKind::DoNotUseBareExcept,
|
||||
CheckCode::F831 => CheckKind::DuplicateArgumentName,
|
||||
CheckCode::F541 => CheckKind::FStringMissingPlaceholders,
|
||||
CheckCode::F722 => CheckKind::ForwardAnnotationSyntaxError("...".to_string()),
|
||||
CheckCode::F407 => CheckKind::FutureFeatureNotDefined("...".to_string()),
|
||||
CheckCode::E902 => CheckKind::IOError("...".to_string()),
|
||||
CheckCode::F634 => CheckKind::IfTuple,
|
||||
CheckCode::F406 => CheckKind::ImportStarNotPermitted("...".to_string()),
|
||||
CheckCode::F403 => CheckKind::ImportStarUsage("...".to_string()),
|
||||
CheckCode::F633 => CheckKind::InvalidPrintSyntax,
|
||||
CheckCode::F632 => CheckKind::IsLiteral,
|
||||
CheckCode::F404 => CheckKind::LateFutureImport,
|
||||
CheckCode::E501 => CheckKind::LineTooLong(89, 88),
|
||||
CheckCode::E402 => CheckKind::ModuleImportNotAtTopOfFile,
|
||||
CheckCode::F601 => CheckKind::MultiValueRepeatedKeyLiteral,
|
||||
CheckCode::F602 => CheckKind::MultiValueRepeatedKeyVariable("...".to_string()),
|
||||
CheckCode::R002 => CheckKind::NoAssertEquals,
|
||||
CheckCode::E711 => CheckKind::NoneComparison(RejectedCmpop::Eq),
|
||||
CheckCode::E713 => CheckKind::NotInTest,
|
||||
CheckCode::E714 => CheckKind::NotIsTest,
|
||||
CheckCode::F901 => CheckKind::RaiseNotImplemented,
|
||||
CheckCode::F706 => CheckKind::ReturnOutsideFunction,
|
||||
CheckCode::E999 => CheckKind::SyntaxError("...".to_string()),
|
||||
CheckCode::F621 => CheckKind::TooManyExpressionsInStarredAssignment,
|
||||
CheckCode::E712 => CheckKind::TrueFalseComparison(true, RejectedCmpop::Eq),
|
||||
CheckCode::F622 => CheckKind::TwoStarredExpressions,
|
||||
CheckCode::E721 => CheckKind::TypeComparison,
|
||||
CheckCode::F822 => CheckKind::UndefinedExport("...".to_string()),
|
||||
CheckCode::F823 => CheckKind::UndefinedLocal("...".to_string()),
|
||||
CheckCode::F821 => CheckKind::UndefinedName("...".to_string()),
|
||||
CheckCode::F401 => CheckKind::UnusedImport("...".to_string()),
|
||||
CheckCode::F841 => CheckKind::UnusedVariable("...".to_string()),
|
||||
CheckCode::R001 => CheckKind::UselessObjectInheritance("...".to_string()),
|
||||
CheckCode::F704 => CheckKind::YieldOutsideFunction,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -160,15 +270,27 @@ pub enum RejectedCmpop {
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum CheckKind {
|
||||
AmbiguousClassName(String),
|
||||
AmbiguousFunctionName(String),
|
||||
AmbiguousVariableName(String),
|
||||
AssertTuple,
|
||||
BreakOutsideLoop,
|
||||
ContinueOutsideLoop,
|
||||
DefaultExceptNotLast,
|
||||
DoNotAssignLambda,
|
||||
DoNotUseBareExcept,
|
||||
DuplicateArgumentName,
|
||||
ForwardAnnotationSyntaxError(String),
|
||||
FStringMissingPlaceholders,
|
||||
FutureFeatureNotDefined(String),
|
||||
IOError(String),
|
||||
IfTuple,
|
||||
ImportStarUsage,
|
||||
LineTooLong,
|
||||
ImportStarNotPermitted(String),
|
||||
ImportStarUsage(String),
|
||||
InvalidPrintSyntax,
|
||||
IsLiteral,
|
||||
LateFutureImport,
|
||||
LineTooLong(usize, usize),
|
||||
ModuleImportNotAtTopOfFile,
|
||||
MultiValueRepeatedKeyLiteral,
|
||||
MultiValueRepeatedKeyVariable(String),
|
||||
@@ -178,9 +300,11 @@ pub enum CheckKind {
|
||||
NotIsTest,
|
||||
RaiseNotImplemented,
|
||||
ReturnOutsideFunction,
|
||||
SyntaxError(String),
|
||||
TooManyExpressionsInStarredAssignment,
|
||||
TrueFalseComparison(bool, RejectedCmpop),
|
||||
TwoStarredExpressions,
|
||||
TypeComparison,
|
||||
UndefinedExport(String),
|
||||
UndefinedLocal(String),
|
||||
UndefinedName(String),
|
||||
@@ -194,15 +318,27 @@ impl CheckKind {
|
||||
/// The name of the check.
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
CheckKind::AmbiguousClassName(_) => "AmbiguousClassName",
|
||||
CheckKind::AmbiguousFunctionName(_) => "AmbiguousFunctionName",
|
||||
CheckKind::AmbiguousVariableName(_) => "AmbiguousVariableName",
|
||||
CheckKind::AssertTuple => "AssertTuple",
|
||||
CheckKind::BreakOutsideLoop => "BreakOutsideLoop",
|
||||
CheckKind::ContinueOutsideLoop => "ContinueOutsideLoop",
|
||||
CheckKind::DefaultExceptNotLast => "DefaultExceptNotLast",
|
||||
CheckKind::DoNotAssignLambda => "DoNotAssignLambda",
|
||||
CheckKind::DoNotUseBareExcept => "DoNotUseBareExcept",
|
||||
CheckKind::DuplicateArgumentName => "DuplicateArgumentName",
|
||||
CheckKind::FStringMissingPlaceholders => "FStringMissingPlaceholders",
|
||||
CheckKind::ForwardAnnotationSyntaxError(_) => "ForwardAnnotationSyntaxError",
|
||||
CheckKind::FutureFeatureNotDefined(_) => "FutureFeatureNotDefined",
|
||||
CheckKind::IOError(_) => "IOError",
|
||||
CheckKind::IfTuple => "IfTuple",
|
||||
CheckKind::ImportStarUsage => "ImportStarUsage",
|
||||
CheckKind::LineTooLong => "LineTooLong",
|
||||
CheckKind::DoNotAssignLambda => "DoNotAssignLambda",
|
||||
CheckKind::ImportStarNotPermitted(_) => "ImportStarNotPermitted",
|
||||
CheckKind::ImportStarUsage(_) => "ImportStarUsage",
|
||||
CheckKind::InvalidPrintSyntax => "InvalidPrintSyntax",
|
||||
CheckKind::IsLiteral => "IsLiteral",
|
||||
CheckKind::LateFutureImport => "LateFutureImport",
|
||||
CheckKind::LineTooLong(_, _) => "LineTooLong",
|
||||
CheckKind::ModuleImportNotAtTopOfFile => "ModuleImportNotAtTopOfFile",
|
||||
CheckKind::MultiValueRepeatedKeyLiteral => "MultiValueRepeatedKeyLiteral",
|
||||
CheckKind::MultiValueRepeatedKeyVariable(_) => "MultiValueRepeatedKeyVariable",
|
||||
@@ -212,11 +348,13 @@ impl CheckKind {
|
||||
CheckKind::NotIsTest => "NotIsTest",
|
||||
CheckKind::RaiseNotImplemented => "RaiseNotImplemented",
|
||||
CheckKind::ReturnOutsideFunction => "ReturnOutsideFunction",
|
||||
CheckKind::SyntaxError(_) => "SyntaxError",
|
||||
CheckKind::TooManyExpressionsInStarredAssignment => {
|
||||
"TooManyExpressionsInStarredAssignment"
|
||||
}
|
||||
CheckKind::TrueFalseComparison(_, _) => "TrueFalseComparison",
|
||||
CheckKind::TwoStarredExpressions => "TwoStarredExpressions",
|
||||
CheckKind::TypeComparison => "TypeComparison",
|
||||
CheckKind::UndefinedExport(_) => "UndefinedExport",
|
||||
CheckKind::UndefinedLocal(_) => "UndefinedLocal",
|
||||
CheckKind::UndefinedName(_) => "UndefinedName",
|
||||
@@ -230,15 +368,27 @@ impl CheckKind {
|
||||
/// A four-letter shorthand code for the check.
|
||||
pub fn code(&self) -> &'static CheckCode {
|
||||
match self {
|
||||
CheckKind::AmbiguousClassName(_) => &CheckCode::E742,
|
||||
CheckKind::AmbiguousFunctionName(_) => &CheckCode::E743,
|
||||
CheckKind::AmbiguousVariableName(_) => &CheckCode::E741,
|
||||
CheckKind::AssertTuple => &CheckCode::F631,
|
||||
CheckKind::BreakOutsideLoop => &CheckCode::F701,
|
||||
CheckKind::ContinueOutsideLoop => &CheckCode::F702,
|
||||
CheckKind::DefaultExceptNotLast => &CheckCode::F707,
|
||||
CheckKind::DoNotAssignLambda => &CheckCode::E731,
|
||||
CheckKind::DoNotUseBareExcept => &CheckCode::E722,
|
||||
CheckKind::DuplicateArgumentName => &CheckCode::F831,
|
||||
CheckKind::FStringMissingPlaceholders => &CheckCode::F541,
|
||||
CheckKind::ForwardAnnotationSyntaxError(_) => &CheckCode::F722,
|
||||
CheckKind::FutureFeatureNotDefined(_) => &CheckCode::F407,
|
||||
CheckKind::IOError(_) => &CheckCode::E902,
|
||||
CheckKind::IfTuple => &CheckCode::F634,
|
||||
CheckKind::ImportStarUsage => &CheckCode::F403,
|
||||
CheckKind::LineTooLong => &CheckCode::E501,
|
||||
CheckKind::DoNotAssignLambda => &CheckCode::E731,
|
||||
CheckKind::ImportStarNotPermitted(_) => &CheckCode::F406,
|
||||
CheckKind::ImportStarUsage(_) => &CheckCode::F403,
|
||||
CheckKind::InvalidPrintSyntax => &CheckCode::F633,
|
||||
CheckKind::IsLiteral => &CheckCode::F632,
|
||||
CheckKind::LateFutureImport => &CheckCode::F404,
|
||||
CheckKind::LineTooLong(_, _) => &CheckCode::E501,
|
||||
CheckKind::ModuleImportNotAtTopOfFile => &CheckCode::E402,
|
||||
CheckKind::MultiValueRepeatedKeyLiteral => &CheckCode::F601,
|
||||
CheckKind::MultiValueRepeatedKeyVariable(_) => &CheckCode::F602,
|
||||
@@ -248,9 +398,11 @@ impl CheckKind {
|
||||
CheckKind::NotIsTest => &CheckCode::E714,
|
||||
CheckKind::RaiseNotImplemented => &CheckCode::F901,
|
||||
CheckKind::ReturnOutsideFunction => &CheckCode::F706,
|
||||
CheckKind::SyntaxError(_) => &CheckCode::E999,
|
||||
CheckKind::TooManyExpressionsInStarredAssignment => &CheckCode::F621,
|
||||
CheckKind::TrueFalseComparison(_, _) => &CheckCode::E712,
|
||||
CheckKind::TwoStarredExpressions => &CheckCode::F622,
|
||||
CheckKind::TypeComparison => &CheckCode::E721,
|
||||
CheckKind::UndefinedExport(_) => &CheckCode::F822,
|
||||
CheckKind::UndefinedLocal(_) => &CheckCode::F823,
|
||||
CheckKind::UndefinedName(_) => &CheckCode::F821,
|
||||
@@ -264,26 +416,56 @@ impl CheckKind {
|
||||
/// The body text for the check.
|
||||
pub fn body(&self) -> String {
|
||||
match self {
|
||||
CheckKind::AmbiguousClassName(name) => {
|
||||
format!("ambiguous class name '{}'", name)
|
||||
}
|
||||
CheckKind::AmbiguousFunctionName(name) => {
|
||||
format!("ambiguous function name '{}'", name)
|
||||
}
|
||||
CheckKind::AmbiguousVariableName(name) => {
|
||||
format!("ambiguous variable name '{}'", name)
|
||||
}
|
||||
CheckKind::AssertTuple => {
|
||||
"Assert test is a non-empty tuple, which is always `True`".to_string()
|
||||
}
|
||||
CheckKind::BreakOutsideLoop => "`break` outside loop".to_string(),
|
||||
CheckKind::ContinueOutsideLoop => "`continue` not properly in loop".to_string(),
|
||||
CheckKind::DefaultExceptNotLast => {
|
||||
"an `except:` block as not the last exception handler".to_string()
|
||||
}
|
||||
CheckKind::DoNotAssignLambda => {
|
||||
"Do not assign a lambda expression, use a def".to_string()
|
||||
}
|
||||
CheckKind::DoNotUseBareExcept => "Do not use bare `except`".to_string(),
|
||||
CheckKind::DuplicateArgumentName => {
|
||||
"Duplicate argument name in function definition".to_string()
|
||||
}
|
||||
CheckKind::ForwardAnnotationSyntaxError(body) => {
|
||||
format!("syntax error in forward annotation '{body}'")
|
||||
}
|
||||
CheckKind::FStringMissingPlaceholders => {
|
||||
"f-string without any placeholders".to_string()
|
||||
}
|
||||
CheckKind::FutureFeatureNotDefined(name) => {
|
||||
format!("future feature '{name}' is not defined")
|
||||
}
|
||||
CheckKind::IOError(name) => {
|
||||
format!("No such file or directory: `{name}`")
|
||||
}
|
||||
CheckKind::IfTuple => "If test is a tuple, which is always `True`".to_string(),
|
||||
CheckKind::ImportStarUsage => "Unable to detect undefined names".to_string(),
|
||||
CheckKind::LineTooLong => "Line too long".to_string(),
|
||||
CheckKind::DoNotAssignLambda => {
|
||||
"Do not assign a lambda expression, use a def".to_string()
|
||||
CheckKind::InvalidPrintSyntax => "use of >> is invalid with print function".to_string(),
|
||||
CheckKind::ImportStarNotPermitted(name) => {
|
||||
format!("`from {name} import *` only allowed at module level")
|
||||
}
|
||||
CheckKind::ImportStarUsage(name) => {
|
||||
format!("`from {name} import *` used; unable to detect undefined names")
|
||||
}
|
||||
CheckKind::IsLiteral => "use ==/!= to compare constant literals".to_string(),
|
||||
CheckKind::LateFutureImport => {
|
||||
"from __future__ imports must occur at the beginning of the file".to_string()
|
||||
}
|
||||
CheckKind::LineTooLong(length, limit) => {
|
||||
format!("Line too long ({length} > {limit} characters)")
|
||||
}
|
||||
CheckKind::ModuleImportNotAtTopOfFile => {
|
||||
"Module level import not at top of file".to_string()
|
||||
@@ -311,6 +493,7 @@ impl CheckKind {
|
||||
CheckKind::ReturnOutsideFunction => {
|
||||
"a `return` statement outside of a function/method".to_string()
|
||||
}
|
||||
CheckKind::SyntaxError(message) => format!("SyntaxError: {message}"),
|
||||
CheckKind::TooManyExpressionsInStarredAssignment => {
|
||||
"too many expressions in star-unpacking assignment".to_string()
|
||||
}
|
||||
@@ -333,15 +516,16 @@ impl CheckKind {
|
||||
},
|
||||
},
|
||||
CheckKind::TwoStarredExpressions => "two starred expressions in assignment".to_string(),
|
||||
CheckKind::TypeComparison => "do not compare types, use `isinstance()`".to_string(),
|
||||
CheckKind::UndefinedExport(name) => {
|
||||
format!("Undefined name `{name}` in `__all__`")
|
||||
}
|
||||
CheckKind::UndefinedName(name) => {
|
||||
format!("Undefined name `{name}`")
|
||||
}
|
||||
CheckKind::UndefinedLocal(name) => {
|
||||
format!("Local variable `{name}` referenced before assignment")
|
||||
}
|
||||
CheckKind::UndefinedName(name) => {
|
||||
format!("Undefined name `{name}`")
|
||||
}
|
||||
CheckKind::UnusedImport(name) => format!("`{name}` imported but unused"),
|
||||
CheckKind::UnusedVariable(name) => {
|
||||
format!("Local variable `{name}` is assigned to but never used")
|
||||
@@ -357,36 +541,10 @@ impl CheckKind {
|
||||
|
||||
/// Whether the check kind is (potentially) fixable.
|
||||
pub fn fixable(&self) -> bool {
|
||||
match self {
|
||||
CheckKind::AssertTuple => false,
|
||||
CheckKind::DefaultExceptNotLast => false,
|
||||
CheckKind::DuplicateArgumentName => false,
|
||||
CheckKind::FStringMissingPlaceholders => false,
|
||||
CheckKind::IOError(_) => false,
|
||||
CheckKind::IfTuple => false,
|
||||
CheckKind::ImportStarUsage => false,
|
||||
CheckKind::DoNotAssignLambda => false,
|
||||
CheckKind::LineTooLong => false,
|
||||
CheckKind::ModuleImportNotAtTopOfFile => false,
|
||||
CheckKind::MultiValueRepeatedKeyLiteral => false,
|
||||
CheckKind::MultiValueRepeatedKeyVariable(_) => false,
|
||||
CheckKind::NoAssertEquals => true,
|
||||
CheckKind::NotInTest => false,
|
||||
CheckKind::NotIsTest => false,
|
||||
CheckKind::NoneComparison(_) => false,
|
||||
CheckKind::RaiseNotImplemented => false,
|
||||
CheckKind::ReturnOutsideFunction => false,
|
||||
CheckKind::TooManyExpressionsInStarredAssignment => false,
|
||||
CheckKind::TrueFalseComparison(_, _) => false,
|
||||
CheckKind::TwoStarredExpressions => false,
|
||||
CheckKind::UndefinedExport(_) => false,
|
||||
CheckKind::UndefinedLocal(_) => false,
|
||||
CheckKind::UndefinedName(_) => false,
|
||||
CheckKind::UnusedImport(_) => false,
|
||||
CheckKind::UnusedVariable(_) => false,
|
||||
CheckKind::UselessObjectInheritance(_) => true,
|
||||
CheckKind::YieldOutsideFunction => false,
|
||||
}
|
||||
matches!(
|
||||
self,
|
||||
CheckKind::NoAssertEquals | CheckKind::UselessObjectInheritance(_)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
236
src/fs.rs
236
src/fs.rs
@@ -1,39 +1,142 @@
|
||||
use std::borrow::Cow;
|
||||
use std::fs::File;
|
||||
use std::io::{BufReader, Read};
|
||||
use std::ops::Deref;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::Result;
|
||||
use glob::Pattern;
|
||||
use anyhow::{anyhow, Result};
|
||||
use log::debug;
|
||||
use path_absolutize::path_dedot;
|
||||
use path_absolutize::Absolutize;
|
||||
use walkdir::{DirEntry, WalkDir};
|
||||
|
||||
fn is_not_hidden(entry: &DirEntry) -> bool {
|
||||
entry
|
||||
.file_name()
|
||||
use crate::settings::FilePattern;
|
||||
|
||||
/// Extract the absolute path and basename (as strings) from a Path.
|
||||
fn extract_path_names(path: &Path) -> Result<(&str, &str)> {
|
||||
let file_path = path
|
||||
.to_str()
|
||||
.map(|s| (entry.depth() == 0 || !s.starts_with('.')))
|
||||
.unwrap_or(false)
|
||||
.ok_or_else(|| anyhow!("Unable to parse filename: {:?}", path))?;
|
||||
let file_basename = path
|
||||
.file_name()
|
||||
.ok_or_else(|| anyhow!("Unable to parse filename: {:?}", path))?
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow!("Unable to parse filename: {:?}", path))?;
|
||||
Ok((file_path, file_basename))
|
||||
}
|
||||
|
||||
fn is_not_excluded(entry: &DirEntry, exclude: &[Pattern]) -> bool {
|
||||
entry
|
||||
.path()
|
||||
.to_str()
|
||||
.map(|s| !exclude.iter().any(|pattern| pattern.matches(s)))
|
||||
.unwrap_or(false)
|
||||
fn is_excluded(file_path: &str, file_basename: &str, exclude: &[FilePattern]) -> bool {
|
||||
for pattern in exclude {
|
||||
match &pattern {
|
||||
FilePattern::Simple(basename) => {
|
||||
if *basename == file_basename {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
FilePattern::Complex(absolute, basename) => {
|
||||
if absolute.matches(file_path) {
|
||||
return true;
|
||||
}
|
||||
if basename
|
||||
.as_ref()
|
||||
.map(|pattern| pattern.matches(file_basename))
|
||||
.unwrap_or_default()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn is_included(path: &Path) -> bool {
|
||||
let file_name = path.to_string_lossy();
|
||||
file_name.ends_with(".py") || file_name.ends_with(".pyi")
|
||||
}
|
||||
|
||||
pub fn iter_python_files<'a>(
|
||||
path: &'a PathBuf,
|
||||
exclude: &'a [Pattern],
|
||||
path: &'a Path,
|
||||
exclude: &'a [FilePattern],
|
||||
extend_exclude: &'a [FilePattern],
|
||||
) -> impl Iterator<Item = DirEntry> + 'a {
|
||||
WalkDir::new(path)
|
||||
// Run some checks over the provided patterns, to enable optimizations below.
|
||||
let has_exclude = !exclude.is_empty();
|
||||
let has_extend_exclude = !extend_exclude.is_empty();
|
||||
let exclude_simple = exclude
|
||||
.iter()
|
||||
.all(|pattern| matches!(pattern, FilePattern::Simple(_)));
|
||||
let extend_exclude_simple = extend_exclude
|
||||
.iter()
|
||||
.all(|pattern| matches!(pattern, FilePattern::Simple(_)));
|
||||
|
||||
WalkDir::new(normalize_path(path))
|
||||
.follow_links(true)
|
||||
.into_iter()
|
||||
.filter_entry(|entry| is_not_hidden(entry) && is_not_excluded(entry, exclude))
|
||||
.filter_entry(move |entry| {
|
||||
if !has_exclude && !has_extend_exclude {
|
||||
return true;
|
||||
}
|
||||
|
||||
let path = entry.path();
|
||||
match extract_path_names(path) {
|
||||
Ok((file_path, file_basename)) => {
|
||||
let file_type = entry.file_type();
|
||||
|
||||
if has_exclude
|
||||
&& (!exclude_simple || file_type.is_dir())
|
||||
&& is_excluded(file_path, file_basename, exclude)
|
||||
{
|
||||
debug!("Ignored path via `exclude`: {:?}", path);
|
||||
false
|
||||
} else if has_extend_exclude
|
||||
&& (!extend_exclude_simple || file_type.is_dir())
|
||||
&& is_excluded(file_path, file_basename, extend_exclude)
|
||||
{
|
||||
debug!("Ignored path via `extend-exclude`: {:?}", path);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
debug!("Ignored path due to error in parsing: {:?}", path);
|
||||
true
|
||||
}
|
||||
}
|
||||
})
|
||||
.filter_map(|entry| entry.ok())
|
||||
.filter(|entry| entry.path().to_string_lossy().ends_with(".py"))
|
||||
.filter(|entry| {
|
||||
let path = entry.path();
|
||||
is_included(path)
|
||||
})
|
||||
}
|
||||
|
||||
/// Convert any path to an absolute path (based on the current working directory).
|
||||
pub fn normalize_path(path: &Path) -> PathBuf {
|
||||
if let Ok(path) = path.absolutize() {
|
||||
return path.to_path_buf();
|
||||
}
|
||||
path.to_path_buf()
|
||||
}
|
||||
|
||||
/// Convert any path to an absolute path (based on the specified project root).
|
||||
pub fn normalize_path_to(path: &Path, project_root: &Path) -> PathBuf {
|
||||
if let Ok(path) = path.absolutize_from(project_root) {
|
||||
return path.to_path_buf();
|
||||
}
|
||||
path.to_path_buf()
|
||||
}
|
||||
|
||||
/// Convert an absolute path to be relative to the current working directory.
|
||||
pub fn relativize_path(path: &Path) -> Cow<str> {
|
||||
if let Ok(path) = path.strip_prefix(path_dedot::CWD.deref()) {
|
||||
return path.to_string_lossy();
|
||||
}
|
||||
path.to_string_lossy()
|
||||
}
|
||||
|
||||
/// Read a file's contents from disk.
|
||||
pub fn read_file(path: &Path) -> Result<String> {
|
||||
let file = File::open(path)?;
|
||||
let mut buf_reader = BufReader::new(file);
|
||||
@@ -41,3 +144,100 @@ pub fn read_file(path: &Path) -> Result<String> {
|
||||
buf_reader.read_to_string(&mut contents)?;
|
||||
Ok(contents)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Result;
|
||||
use path_absolutize::Absolutize;
|
||||
|
||||
use crate::fs::{extract_path_names, is_excluded, is_included};
|
||||
use crate::settings::FilePattern;
|
||||
|
||||
#[test]
|
||||
fn inclusions() {
|
||||
let path = Path::new("foo/bar/baz.py").absolutize().unwrap();
|
||||
assert!(is_included(&path));
|
||||
|
||||
let path = Path::new("foo/bar/baz.pyi").absolutize().unwrap();
|
||||
assert!(is_included(&path));
|
||||
|
||||
let path = Path::new("foo/bar/baz.js").absolutize().unwrap();
|
||||
assert!(!is_included(&path));
|
||||
|
||||
let path = Path::new("foo/bar/baz").absolutize().unwrap();
|
||||
assert!(!is_included(&path));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exclusions() -> Result<()> {
|
||||
let project_root = Path::new("/tmp/");
|
||||
|
||||
let path = Path::new("foo").absolutize_from(project_root).unwrap();
|
||||
let exclude = vec![FilePattern::from_user(
|
||||
"foo",
|
||||
&Some(project_root.to_path_buf()),
|
||||
)];
|
||||
let (file_path, file_basename) = extract_path_names(&path)?;
|
||||
assert!(is_excluded(file_path, file_basename, &exclude));
|
||||
|
||||
let path = Path::new("foo/bar").absolutize_from(project_root).unwrap();
|
||||
let exclude = vec![FilePattern::from_user(
|
||||
"bar",
|
||||
&Some(project_root.to_path_buf()),
|
||||
)];
|
||||
let (file_path, file_basename) = extract_path_names(&path)?;
|
||||
assert!(is_excluded(file_path, file_basename, &exclude));
|
||||
|
||||
let path = Path::new("foo/bar/baz.py")
|
||||
.absolutize_from(project_root)
|
||||
.unwrap();
|
||||
let exclude = vec![FilePattern::from_user(
|
||||
"baz.py",
|
||||
&Some(project_root.to_path_buf()),
|
||||
)];
|
||||
let (file_path, file_basename) = extract_path_names(&path)?;
|
||||
assert!(is_excluded(file_path, file_basename, &exclude));
|
||||
|
||||
let path = Path::new("foo/bar").absolutize_from(project_root).unwrap();
|
||||
let exclude = vec![FilePattern::from_user(
|
||||
"foo/bar",
|
||||
&Some(project_root.to_path_buf()),
|
||||
)];
|
||||
let (file_path, file_basename) = extract_path_names(&path)?;
|
||||
assert!(is_excluded(file_path, file_basename, &exclude));
|
||||
|
||||
let path = Path::new("foo/bar/baz.py")
|
||||
.absolutize_from(project_root)
|
||||
.unwrap();
|
||||
let exclude = vec![FilePattern::from_user(
|
||||
"foo/bar/baz.py",
|
||||
&Some(project_root.to_path_buf()),
|
||||
)];
|
||||
let (file_path, file_basename) = extract_path_names(&path)?;
|
||||
assert!(is_excluded(file_path, file_basename, &exclude));
|
||||
|
||||
let path = Path::new("foo/bar/baz.py")
|
||||
.absolutize_from(project_root)
|
||||
.unwrap();
|
||||
let exclude = vec![FilePattern::from_user(
|
||||
"foo/bar/*.py",
|
||||
&Some(project_root.to_path_buf()),
|
||||
)];
|
||||
let (file_path, file_basename) = extract_path_names(&path)?;
|
||||
assert!(is_excluded(file_path, file_basename, &exclude));
|
||||
|
||||
let path = Path::new("foo/bar/baz.py")
|
||||
.absolutize_from(project_root)
|
||||
.unwrap();
|
||||
let exclude = vec![FilePattern::from_user(
|
||||
"baz",
|
||||
&Some(project_root.to_path_buf()),
|
||||
)];
|
||||
let (file_path, file_basename) = extract_path_names(&path)?;
|
||||
assert!(!is_excluded(file_path, file_basename, &exclude));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ extern crate core;
|
||||
|
||||
mod ast;
|
||||
mod autofix;
|
||||
mod cache;
|
||||
pub mod cache;
|
||||
pub mod check_ast;
|
||||
mod check_lines;
|
||||
pub mod checks;
|
||||
@@ -10,6 +10,7 @@ pub mod fs;
|
||||
pub mod linter;
|
||||
pub mod logging;
|
||||
pub mod message;
|
||||
mod pyproject;
|
||||
pub mod printer;
|
||||
pub mod pyproject;
|
||||
mod python;
|
||||
pub mod settings;
|
||||
|
||||
1072
src/linter.rs
1072
src/linter.rs
File diff suppressed because it is too large
Load Diff
133
src/main.rs
133
src/main.rs
@@ -1,4 +1,6 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
extern crate core;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
use std::sync::mpsc::channel;
|
||||
use std::time::Instant;
|
||||
@@ -6,19 +8,21 @@ use std::time::Instant;
|
||||
use anyhow::Result;
|
||||
use clap::{Parser, ValueHint};
|
||||
use colored::Colorize;
|
||||
use glob::Pattern;
|
||||
use log::{debug, error};
|
||||
use notify::{raw_watcher, RecursiveMode, Watcher};
|
||||
use rayon::prelude::*;
|
||||
use walkdir::DirEntry;
|
||||
|
||||
use ::ruff::cache;
|
||||
use ::ruff::checks::CheckCode;
|
||||
use ::ruff::checks::CheckKind;
|
||||
use ::ruff::fs::iter_python_files;
|
||||
use ::ruff::linter::lint_path;
|
||||
use ::ruff::logging::set_up_logging;
|
||||
use ::ruff::message::Message;
|
||||
use ::ruff::settings::Settings;
|
||||
use ::ruff::printer::{Printer, SerializationFormat};
|
||||
use ::ruff::pyproject;
|
||||
use ::ruff::settings::{FilePattern, Settings};
|
||||
use ::ruff::tell_user;
|
||||
|
||||
const CARGO_PKG_NAME: &str = env!("CARGO_PKG_NAME");
|
||||
@@ -27,6 +31,7 @@ const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
#[derive(Debug, Parser)]
|
||||
#[clap(name = format!("{CARGO_PKG_NAME} (v{CARGO_PKG_VERSION})"))]
|
||||
#[clap(about = "An extremely fast Python linter.", long_about = None)]
|
||||
#[clap(version)]
|
||||
struct Cli {
|
||||
#[clap(parse(from_os_str), value_hint = ValueHint::AnyPath, required = true)]
|
||||
files: Vec<PathBuf>,
|
||||
@@ -54,9 +59,15 @@ struct Cli {
|
||||
/// List of error codes to ignore.
|
||||
#[clap(long, multiple = true)]
|
||||
ignore: Vec<CheckCode>,
|
||||
/// List of file and/or directory patterns to exclude from checks.
|
||||
/// List of paths, used to exclude files and/or directories from checks.
|
||||
#[clap(long, multiple = true)]
|
||||
exclude: Vec<Pattern>,
|
||||
exclude: Vec<String>,
|
||||
/// Like --exclude, but adds additional files and directories on top of the excluded ones.
|
||||
#[clap(long, multiple = true)]
|
||||
extend_exclude: Vec<String>,
|
||||
/// Output serialization format for error messages.
|
||||
#[clap(long, arg_enum, default_value_t=SerializationFormat::Text)]
|
||||
format: SerializationFormat,
|
||||
}
|
||||
|
||||
#[cfg(feature = "update-informer")]
|
||||
@@ -93,7 +104,7 @@ fn run_once(
|
||||
let start = Instant::now();
|
||||
let paths: Vec<DirEntry> = files
|
||||
.iter()
|
||||
.flat_map(|path| iter_python_files(path, &settings.exclude))
|
||||
.flat_map(|path| iter_python_files(path, &settings.exclude, &settings.extend_exclude))
|
||||
.collect();
|
||||
let duration = start.elapsed();
|
||||
debug!("Identified files to lint in: {:?}", duration);
|
||||
@@ -103,8 +114,17 @@ fn run_once(
|
||||
.par_iter()
|
||||
.map(|entry| {
|
||||
lint_path(entry.path(), settings, &cache.into(), &autofix.into()).unwrap_or_else(|e| {
|
||||
error!("Failed to check {}: {e:?}", entry.path().to_string_lossy());
|
||||
vec![]
|
||||
if settings.select.contains(&CheckCode::E999) {
|
||||
vec![Message {
|
||||
kind: CheckKind::SyntaxError(e.to_string()),
|
||||
fixed: false,
|
||||
location: Default::default(),
|
||||
filename: entry.path().to_string_lossy().to_string(),
|
||||
}]
|
||||
} else {
|
||||
error!("Failed to check {}: {e:?}", entry.path().to_string_lossy());
|
||||
vec![]
|
||||
}
|
||||
})
|
||||
})
|
||||
.flatten()
|
||||
@@ -130,62 +150,25 @@ fn run_once(
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
fn report_once(messages: &[Message]) -> Result<()> {
|
||||
let (fixed, outstanding): (Vec<&Message>, Vec<&Message>) =
|
||||
messages.iter().partition(|message| message.fixed);
|
||||
let num_fixable = outstanding
|
||||
.iter()
|
||||
.filter(|message| message.kind.fixable())
|
||||
.count();
|
||||
|
||||
if !outstanding.is_empty() {
|
||||
for message in &outstanding {
|
||||
println!("{}", message);
|
||||
}
|
||||
println!();
|
||||
}
|
||||
|
||||
if !fixed.is_empty() {
|
||||
println!(
|
||||
"Found {} error(s) ({} fixed).",
|
||||
outstanding.len(),
|
||||
fixed.len()
|
||||
);
|
||||
} else {
|
||||
println!("Found {} error(s).", outstanding.len());
|
||||
}
|
||||
|
||||
if num_fixable > 0 {
|
||||
println!("{num_fixable} potentially fixable with the --fix option.");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn report_continuously(messages: &[Message]) -> Result<()> {
|
||||
tell_user!(
|
||||
"Found {} error(s). Watching for file changes.",
|
||||
messages.len(),
|
||||
);
|
||||
|
||||
if !messages.is_empty() {
|
||||
println!();
|
||||
for message in messages {
|
||||
println!("{}", message);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn inner_main() -> Result<ExitCode> {
|
||||
let cli = Cli::parse();
|
||||
|
||||
set_up_logging(cli.verbose)?;
|
||||
|
||||
// TODO(charlie): Can we avoid this cast?
|
||||
let paths: Vec<&Path> = cli.files.iter().map(PathBuf::as_path).collect();
|
||||
let mut settings = Settings::from_paths(paths)?;
|
||||
// Find the project root and pyproject.toml.
|
||||
let project_root = pyproject::find_project_root(&cli.files);
|
||||
match &project_root {
|
||||
Some(path) => debug!("Found project root at: {:?}", path),
|
||||
None => debug!("Unable to identify project root; assuming current directory..."),
|
||||
};
|
||||
let pyproject = pyproject::find_pyproject_toml(&project_root);
|
||||
match &pyproject {
|
||||
Some(path) => debug!("Found pyproject.toml at: {:?}", path),
|
||||
None => debug!("Unable to find pyproject.toml; using default settings..."),
|
||||
};
|
||||
|
||||
// Parse the settings from the pyproject.toml and command-line arguments.
|
||||
let mut settings = Settings::from_pyproject(&pyproject, &project_root);
|
||||
if !cli.select.is_empty() {
|
||||
settings.select(cli.select);
|
||||
}
|
||||
@@ -193,21 +176,39 @@ fn inner_main() -> Result<ExitCode> {
|
||||
settings.ignore(&cli.ignore);
|
||||
}
|
||||
if !cli.exclude.is_empty() {
|
||||
settings.exclude(cli.exclude);
|
||||
settings.exclude = cli
|
||||
.exclude
|
||||
.iter()
|
||||
.map(|path| FilePattern::from_user(path, &project_root))
|
||||
.collect();
|
||||
}
|
||||
if !cli.extend_exclude.is_empty() {
|
||||
settings.extend_exclude = cli
|
||||
.extend_exclude
|
||||
.iter()
|
||||
.map(|path| FilePattern::from_user(path, &project_root))
|
||||
.collect();
|
||||
}
|
||||
|
||||
cache::init()?;
|
||||
|
||||
let mut printer = Printer::new(cli.format);
|
||||
if cli.watch {
|
||||
if cli.fix {
|
||||
println!("Warning: --fix is not enabled in watch mode.")
|
||||
println!("Warning: --fix is not enabled in watch mode.");
|
||||
}
|
||||
|
||||
if cli.format != SerializationFormat::Text {
|
||||
println!("Warning: --format 'text' is used in watch mode.");
|
||||
}
|
||||
|
||||
// Perform an initial run instantly.
|
||||
clearscreen::clear()?;
|
||||
printer.clear_screen()?;
|
||||
tell_user!("Starting linter in watch mode...\n");
|
||||
|
||||
let messages = run_once(&cli.files, &settings, !cli.no_cache, false)?;
|
||||
if !cli.quiet {
|
||||
report_continuously(&messages)?;
|
||||
printer.write_continuously(&messages)?;
|
||||
}
|
||||
|
||||
// Configure the file watcher.
|
||||
@@ -222,12 +223,12 @@ fn inner_main() -> Result<ExitCode> {
|
||||
Ok(e) => {
|
||||
if let Some(path) = e.path {
|
||||
if path.to_string_lossy().ends_with(".py") {
|
||||
clearscreen::clear()?;
|
||||
printer.clear_screen()?;
|
||||
tell_user!("File change detected...\n");
|
||||
|
||||
let messages = run_once(&cli.files, &settings, !cli.no_cache, false)?;
|
||||
if !cli.quiet {
|
||||
report_continuously(&messages)?;
|
||||
printer.write_continuously(&messages)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -238,7 +239,7 @@ fn inner_main() -> Result<ExitCode> {
|
||||
} else {
|
||||
let messages = run_once(&cli.files, &settings, !cli.no_cache, cli.fix)?;
|
||||
if !cli.quiet {
|
||||
report_once(&messages)?;
|
||||
printer.write_once(&messages)?;
|
||||
}
|
||||
|
||||
#[cfg(feature = "update-informer")]
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
use std::cmp::Ordering;
|
||||
use std::fmt;
|
||||
use std::path::Path;
|
||||
|
||||
use colored::Colorize;
|
||||
use rustpython_parser::ast::Location;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::checks::CheckKind;
|
||||
use crate::fs::relativize_path;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Message {
|
||||
@@ -36,7 +38,8 @@ impl fmt::Display for Message {
|
||||
write!(
|
||||
f,
|
||||
"{}{}{}{}{}{} {} {}",
|
||||
self.filename.white().bold(),
|
||||
relativize_path(Path::new(&self.filename)).white().bold(),
|
||||
// self.filename.white(),
|
||||
":".cyan(),
|
||||
self.location.row(),
|
||||
":".cyan(),
|
||||
|
||||
79
src/printer.rs
Normal file
79
src/printer.rs
Normal file
@@ -0,0 +1,79 @@
|
||||
use anyhow::Result;
|
||||
use clap::ValueEnum;
|
||||
use colored::Colorize;
|
||||
|
||||
use crate::message::Message;
|
||||
use crate::tell_user;
|
||||
|
||||
#[derive(Clone, Copy, ValueEnum, PartialEq, Eq, Debug)]
|
||||
pub enum SerializationFormat {
|
||||
Text,
|
||||
Json,
|
||||
}
|
||||
|
||||
pub struct Printer {
|
||||
format: SerializationFormat,
|
||||
}
|
||||
|
||||
impl Printer {
|
||||
pub fn new(format: SerializationFormat) -> Self {
|
||||
Self { format }
|
||||
}
|
||||
|
||||
pub fn write_once(&mut self, messages: &[Message]) -> Result<()> {
|
||||
let (fixed, outstanding): (Vec<&Message>, Vec<&Message>) =
|
||||
messages.iter().partition(|message| message.fixed);
|
||||
let num_fixable = outstanding
|
||||
.iter()
|
||||
.filter(|message| message.kind.fixable())
|
||||
.count();
|
||||
|
||||
match self.format {
|
||||
SerializationFormat::Json => {
|
||||
println!("{}", serde_json::to_string_pretty(&messages)?)
|
||||
}
|
||||
SerializationFormat::Text => {
|
||||
if !fixed.is_empty() {
|
||||
println!(
|
||||
"Found {} error(s) ({} fixed).",
|
||||
outstanding.len(),
|
||||
fixed.len()
|
||||
)
|
||||
} else {
|
||||
println!("Found {} error(s).", outstanding.len())
|
||||
}
|
||||
|
||||
for message in outstanding {
|
||||
println!("{}", message)
|
||||
}
|
||||
|
||||
if num_fixable > 0 {
|
||||
println!("{num_fixable} potentially fixable with the --fix option.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_continuously(&mut self, messages: &[Message]) -> Result<()> {
|
||||
tell_user!(
|
||||
"Found {} error(s). Watching for file changes.",
|
||||
messages.len(),
|
||||
);
|
||||
|
||||
if !messages.is_empty() {
|
||||
println!();
|
||||
for message in messages {
|
||||
println!("{}", message)
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn clear_screen(&mut self) -> Result<()> {
|
||||
clearscreen::clear()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
132
src/pyproject.rs
132
src/pyproject.rs
@@ -2,35 +2,30 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::Result;
|
||||
use common_path::common_path_all;
|
||||
use log::debug;
|
||||
use path_absolutize::Absolutize;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::checks::CheckCode;
|
||||
use crate::fs;
|
||||
|
||||
pub fn load_config<'a>(paths: impl IntoIterator<Item = &'a Path>) -> Result<(PathBuf, Config)> {
|
||||
match find_project_root(paths) {
|
||||
Some(project_root) => match find_pyproject_toml(&project_root) {
|
||||
Some(path) => {
|
||||
debug!("Found pyproject.toml at: {}", path.to_string_lossy());
|
||||
match parse_pyproject_toml(&path) {
|
||||
Ok(pyproject) => {
|
||||
let config = pyproject
|
||||
.tool
|
||||
.and_then(|tool| tool.ruff)
|
||||
.unwrap_or_default();
|
||||
Ok((project_root, config))
|
||||
}
|
||||
Err(e) => {
|
||||
println!("Failed to load pyproject.toml: {:?}", e);
|
||||
println!("Falling back to default configuration...");
|
||||
Ok(Default::default())
|
||||
}
|
||||
}
|
||||
pub fn load_config(pyproject: &Option<PathBuf>) -> Config {
|
||||
match pyproject {
|
||||
Some(pyproject) => match parse_pyproject_toml(pyproject) {
|
||||
Ok(pyproject) => pyproject
|
||||
.tool
|
||||
.and_then(|tool| tool.ruff)
|
||||
.unwrap_or_default(),
|
||||
Err(e) => {
|
||||
println!("Failed to load pyproject.toml: {:?}", e);
|
||||
println!("Falling back to default configuration...");
|
||||
Default::default()
|
||||
}
|
||||
None => Ok(Default::default()),
|
||||
},
|
||||
None => Ok(Default::default()),
|
||||
None => {
|
||||
println!("No pyproject.toml found.");
|
||||
println!("Falling back to default configuration...");
|
||||
Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +33,8 @@ pub fn load_config<'a>(paths: impl IntoIterator<Item = &'a Path>) -> Result<(Pat
|
||||
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct Config {
|
||||
pub line_length: Option<usize>,
|
||||
pub exclude: Option<Vec<PathBuf>>,
|
||||
pub exclude: Option<Vec<String>>,
|
||||
pub extend_exclude: Option<Vec<String>>,
|
||||
pub select: Option<Vec<CheckCode>>,
|
||||
pub ignore: Option<Vec<CheckCode>>,
|
||||
}
|
||||
@@ -58,20 +54,34 @@ fn parse_pyproject_toml(path: &Path) -> Result<PyProject> {
|
||||
toml::from_str(&contents).map_err(|e| e.into())
|
||||
}
|
||||
|
||||
fn find_pyproject_toml(path: &Path) -> Option<PathBuf> {
|
||||
let path_pyproject_toml = path.join("pyproject.toml");
|
||||
if path_pyproject_toml.is_file() {
|
||||
return Some(path_pyproject_toml);
|
||||
pub fn find_pyproject_toml(path: &Option<PathBuf>) -> Option<PathBuf> {
|
||||
if let Some(path) = path {
|
||||
let path_pyproject_toml = path.join("pyproject.toml");
|
||||
if path_pyproject_toml.is_file() {
|
||||
return Some(path_pyproject_toml);
|
||||
}
|
||||
}
|
||||
|
||||
find_user_pyproject_toml()
|
||||
}
|
||||
|
||||
fn find_user_pyproject_toml() -> Option<PathBuf> {
|
||||
dirs::home_dir().map(|path| path.join(".ruff"))
|
||||
let mut path = dirs::config_dir()?;
|
||||
path.push("ruff");
|
||||
path.push("pyproject.toml");
|
||||
if path.is_file() {
|
||||
Some(path)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn find_project_root<'a>(sources: impl IntoIterator<Item = &'a Path>) -> Option<PathBuf> {
|
||||
if let Some(prefix) = common_path_all(sources) {
|
||||
pub fn find_project_root(sources: &[PathBuf]) -> Option<PathBuf> {
|
||||
let absolute_sources: Vec<PathBuf> = sources
|
||||
.iter()
|
||||
.flat_map(|source| source.absolutize().map(|path| path.to_path_buf()))
|
||||
.collect();
|
||||
if let Some(prefix) = common_path_all(absolute_sources.iter().map(PathBuf::as_path)) {
|
||||
for directory in prefix.ancestors() {
|
||||
if directory.join(".git").is_dir() {
|
||||
return Some(directory.to_path_buf());
|
||||
@@ -90,7 +100,8 @@ fn find_project_root<'a>(sources: impl IntoIterator<Item = &'a Path>) -> Option<
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::Path;
|
||||
use std::env::current_dir;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Result;
|
||||
|
||||
@@ -123,6 +134,7 @@ mod tests {
|
||||
ruff: Some(Config {
|
||||
line_length: None,
|
||||
exclude: None,
|
||||
extend_exclude: None,
|
||||
select: None,
|
||||
ignore: None,
|
||||
})
|
||||
@@ -142,6 +154,7 @@ line-length = 79
|
||||
ruff: Some(Config {
|
||||
line_length: Some(79),
|
||||
exclude: None,
|
||||
extend_exclude: None,
|
||||
select: None,
|
||||
ignore: None,
|
||||
})
|
||||
@@ -160,7 +173,8 @@ exclude = ["foo.py"]
|
||||
Some(Tools {
|
||||
ruff: Some(Config {
|
||||
line_length: None,
|
||||
exclude: Some(vec![Path::new("foo.py").to_path_buf()]),
|
||||
exclude: Some(vec!["foo.py".to_string()]),
|
||||
extend_exclude: None,
|
||||
select: None,
|
||||
ignore: None,
|
||||
})
|
||||
@@ -180,6 +194,7 @@ select = ["E501"]
|
||||
ruff: Some(Config {
|
||||
line_length: None,
|
||||
exclude: None,
|
||||
extend_exclude: None,
|
||||
select: Some(vec![CheckCode::E501]),
|
||||
ignore: None,
|
||||
})
|
||||
@@ -199,6 +214,7 @@ ignore = ["E501"]
|
||||
ruff: Some(Config {
|
||||
line_length: None,
|
||||
exclude: None,
|
||||
extend_exclude: None,
|
||||
select: None,
|
||||
ignore: Some(vec![CheckCode::E501]),
|
||||
})
|
||||
@@ -238,12 +254,15 @@ other-attribute = 1
|
||||
|
||||
#[test]
|
||||
fn find_and_parse_pyproject_toml() -> Result<()> {
|
||||
let project_root = find_project_root([Path::new("resources/test/fixtures/__init__.py")])
|
||||
.expect("Unable to find project root.");
|
||||
assert_eq!(project_root, Path::new("resources/test/fixtures"));
|
||||
let cwd = current_dir()?;
|
||||
let project_root =
|
||||
find_project_root(&[PathBuf::from("resources/test/fixtures/__init__.py")])
|
||||
.expect("Unable to find project root.");
|
||||
assert_eq!(project_root, cwd.join("resources/test/fixtures"));
|
||||
|
||||
let path = find_pyproject_toml(&project_root).expect("Unable to find pyproject.toml.");
|
||||
assert_eq!(path, Path::new("resources/test/fixtures/pyproject.toml"));
|
||||
let path =
|
||||
find_pyproject_toml(&Some(project_root)).expect("Unable to find pyproject.toml.");
|
||||
assert_eq!(path, cwd.join("resources/test/fixtures/pyproject.toml"));
|
||||
|
||||
let pyproject = parse_pyproject_toml(&path)?;
|
||||
let config = pyproject
|
||||
@@ -254,40 +273,13 @@ other-attribute = 1
|
||||
config,
|
||||
Config {
|
||||
line_length: Some(88),
|
||||
exclude: Some(vec![
|
||||
Path::new("excluded.py").to_path_buf(),
|
||||
Path::new("**/migrations").to_path_buf()
|
||||
]),
|
||||
select: Some(vec![
|
||||
CheckCode::E402,
|
||||
CheckCode::E501,
|
||||
CheckCode::E711,
|
||||
CheckCode::E712,
|
||||
CheckCode::E713,
|
||||
CheckCode::E714,
|
||||
CheckCode::E731,
|
||||
CheckCode::E902,
|
||||
CheckCode::F401,
|
||||
CheckCode::F403,
|
||||
CheckCode::F541,
|
||||
CheckCode::F601,
|
||||
CheckCode::F602,
|
||||
CheckCode::F621,
|
||||
CheckCode::F622,
|
||||
CheckCode::F631,
|
||||
CheckCode::F634,
|
||||
CheckCode::F704,
|
||||
CheckCode::F706,
|
||||
CheckCode::F707,
|
||||
CheckCode::F821,
|
||||
CheckCode::F822,
|
||||
CheckCode::F823,
|
||||
CheckCode::F831,
|
||||
CheckCode::F841,
|
||||
CheckCode::F901,
|
||||
CheckCode::R001,
|
||||
CheckCode::R002,
|
||||
exclude: None,
|
||||
extend_exclude: Some(vec![
|
||||
"excluded.py".to_string(),
|
||||
"migrations".to_string(),
|
||||
"directory/also_excluded.py".to_string(),
|
||||
]),
|
||||
select: None,
|
||||
ignore: None,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
pub mod builtins;
|
||||
pub mod future;
|
||||
pub mod typing;
|
||||
|
||||
13
src/python/future.rs
Normal file
13
src/python/future.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
/// A copy of `__future__.all_feature_names`.
|
||||
pub const ALL_FEATURE_NAMES: &[&str] = &[
|
||||
"nested_scopes",
|
||||
"generators",
|
||||
"division",
|
||||
"absolute_import",
|
||||
"with_statement",
|
||||
"print_function",
|
||||
"unicode_literals",
|
||||
"barry_as_FLUFL",
|
||||
"generator_stop",
|
||||
"annotations",
|
||||
];
|
||||
@@ -1,8 +1,9 @@
|
||||
use lazy_static::lazy_static;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
lazy_static! {
|
||||
static ref ANNOTATED_SUBSCRIPTS: BTreeSet<&'static str> = BTreeSet::from([
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
static ANNOTATED_SUBSCRIPTS: Lazy<BTreeSet<&'static str>> = Lazy::new(|| {
|
||||
BTreeSet::from([
|
||||
"AbstractAsyncContextManager",
|
||||
"AbstractContextManager",
|
||||
"AbstractSet",
|
||||
@@ -80,8 +81,8 @@ lazy_static! {
|
||||
"set",
|
||||
"tuple",
|
||||
"type",
|
||||
]);
|
||||
}
|
||||
])
|
||||
});
|
||||
|
||||
pub fn is_annotated_subscript(name: &str) -> bool {
|
||||
ANNOTATED_SUBSCRIPTS.contains(name)
|
||||
|
||||
132
src/settings.rs
132
src/settings.rs
@@ -1,17 +1,44 @@
|
||||
use std::collections::BTreeSet;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::Result;
|
||||
use glob::Pattern;
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
use crate::checks::CheckCode;
|
||||
use crate::checks::{CheckCode, ALL_CHECK_CODES};
|
||||
use crate::fs;
|
||||
use crate::pyproject::load_config;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum FilePattern {
|
||||
Simple(&'static str),
|
||||
Complex(Pattern, Option<Pattern>),
|
||||
}
|
||||
|
||||
impl FilePattern {
|
||||
pub fn from_user(pattern: &str, project_root: &Option<PathBuf>) -> Self {
|
||||
let path = Path::new(pattern);
|
||||
let absolute_path = match project_root {
|
||||
Some(project_root) => fs::normalize_path_to(path, project_root),
|
||||
None => fs::normalize_path(path),
|
||||
};
|
||||
|
||||
let absolute = Pattern::new(&absolute_path.to_string_lossy()).expect("Invalid pattern.");
|
||||
let basename = if !pattern.contains(std::path::MAIN_SEPARATOR) {
|
||||
Some(Pattern::new(pattern).expect("Invalid pattern."))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
FilePattern::Complex(absolute, basename)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Settings {
|
||||
pub line_length: usize,
|
||||
pub exclude: Vec<Pattern>,
|
||||
pub exclude: Vec<FilePattern>,
|
||||
pub extend_exclude: Vec<FilePattern>,
|
||||
pub select: BTreeSet<CheckCode>,
|
||||
}
|
||||
|
||||
@@ -24,62 +51,63 @@ impl Hash for Settings {
|
||||
}
|
||||
}
|
||||
|
||||
static DEFAULT_EXCLUDE: Lazy<Vec<FilePattern>> = Lazy::new(|| {
|
||||
vec![
|
||||
FilePattern::Simple(".bzr"),
|
||||
FilePattern::Simple(".direnv"),
|
||||
FilePattern::Simple(".eggs"),
|
||||
FilePattern::Simple(".git"),
|
||||
FilePattern::Simple(".hg"),
|
||||
FilePattern::Simple(".mypy_cache"),
|
||||
FilePattern::Simple(".nox"),
|
||||
FilePattern::Simple(".pants.d"),
|
||||
FilePattern::Simple(".ruff_cache"),
|
||||
FilePattern::Simple(".svn"),
|
||||
FilePattern::Simple(".tox"),
|
||||
FilePattern::Simple(".venv"),
|
||||
FilePattern::Simple("__pypackages__"),
|
||||
FilePattern::Simple("_build"),
|
||||
FilePattern::Simple("buck-out"),
|
||||
FilePattern::Simple("build"),
|
||||
FilePattern::Simple("dist"),
|
||||
FilePattern::Simple("node_modules"),
|
||||
FilePattern::Simple("venv"),
|
||||
]
|
||||
});
|
||||
|
||||
impl Settings {
|
||||
pub fn from_paths<'a>(paths: impl IntoIterator<Item = &'a Path>) -> Result<Self> {
|
||||
let (project_root, config) = load_config(paths)?;
|
||||
pub fn from_pyproject(path: &Option<PathBuf>, project_root: &Option<PathBuf>) -> Self {
|
||||
let config = load_config(path);
|
||||
let mut settings = Settings {
|
||||
line_length: config.line_length.unwrap_or(88),
|
||||
exclude: config
|
||||
.exclude
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|path| {
|
||||
if path.is_relative() {
|
||||
project_root.join(path)
|
||||
} else {
|
||||
path
|
||||
}
|
||||
.map(|paths| {
|
||||
paths
|
||||
.iter()
|
||||
.map(|path| FilePattern::from_user(path, project_root))
|
||||
.collect()
|
||||
})
|
||||
.map(|path| Pattern::new(&path.to_string_lossy()).expect("Invalid pattern."))
|
||||
.collect(),
|
||||
select: BTreeSet::from_iter(config.select.unwrap_or_else(|| {
|
||||
vec![
|
||||
CheckCode::E402,
|
||||
CheckCode::E501,
|
||||
CheckCode::E711,
|
||||
CheckCode::E712,
|
||||
CheckCode::E713,
|
||||
CheckCode::E714,
|
||||
CheckCode::E731,
|
||||
CheckCode::E902,
|
||||
CheckCode::F401,
|
||||
CheckCode::F403,
|
||||
CheckCode::F541,
|
||||
CheckCode::F601,
|
||||
CheckCode::F602,
|
||||
CheckCode::F621,
|
||||
CheckCode::F622,
|
||||
CheckCode::F631,
|
||||
CheckCode::F634,
|
||||
CheckCode::F704,
|
||||
CheckCode::F706,
|
||||
CheckCode::F707,
|
||||
CheckCode::F821,
|
||||
CheckCode::F822,
|
||||
CheckCode::F823,
|
||||
CheckCode::F831,
|
||||
CheckCode::F841,
|
||||
CheckCode::F901,
|
||||
// Disable refactoring codes by default.
|
||||
// CheckCode::R001,
|
||||
// CheckCode::R002,
|
||||
]
|
||||
})),
|
||||
.unwrap_or_else(|| DEFAULT_EXCLUDE.clone()),
|
||||
extend_exclude: config
|
||||
.extend_exclude
|
||||
.map(|paths| {
|
||||
paths
|
||||
.iter()
|
||||
.map(|path| FilePattern::from_user(path, project_root))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
select: if let Some(select) = config.select {
|
||||
BTreeSet::from_iter(select)
|
||||
} else {
|
||||
BTreeSet::from_iter(ALL_CHECK_CODES)
|
||||
},
|
||||
};
|
||||
if let Some(ignore) = &config.ignore {
|
||||
settings.ignore(ignore);
|
||||
}
|
||||
Ok(settings)
|
||||
settings
|
||||
}
|
||||
|
||||
pub fn select(&mut self, codes: Vec<CheckCode>) {
|
||||
@@ -94,8 +122,4 @@ impl Settings {
|
||||
self.select.remove(code);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn exclude(&mut self, exclude: Vec<Pattern>) {
|
||||
self.exclude = exclude;
|
||||
}
|
||||
}
|
||||
|
||||
10
src/snapshots/ruff__linter__tests__e402.snap
Normal file
10
src/snapshots/ruff__linter__tests__e402.snap
Normal file
@@ -0,0 +1,10 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: ModuleImportNotAtTopOfFile
|
||||
location:
|
||||
row: 20
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
13
src/snapshots/ruff__linter__tests__e501.snap
Normal file
13
src/snapshots/ruff__linter__tests__e501.snap
Normal file
@@ -0,0 +1,13 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
LineTooLong:
|
||||
- 123
|
||||
- 88
|
||||
location:
|
||||
row: 5
|
||||
column: 89
|
||||
fix: ~
|
||||
|
||||
53
src/snapshots/ruff__linter__tests__e711.snap
Normal file
53
src/snapshots/ruff__linter__tests__e711.snap
Normal file
@@ -0,0 +1,53 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
NoneComparison: Eq
|
||||
location:
|
||||
row: 2
|
||||
column: 11
|
||||
fix: ~
|
||||
- kind:
|
||||
NoneComparison: NotEq
|
||||
location:
|
||||
row: 5
|
||||
column: 11
|
||||
fix: ~
|
||||
- kind:
|
||||
NoneComparison: Eq
|
||||
location:
|
||||
row: 8
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind:
|
||||
NoneComparison: NotEq
|
||||
location:
|
||||
row: 11
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind:
|
||||
NoneComparison: Eq
|
||||
location:
|
||||
row: 14
|
||||
column: 14
|
||||
fix: ~
|
||||
- kind:
|
||||
NoneComparison: NotEq
|
||||
location:
|
||||
row: 17
|
||||
column: 14
|
||||
fix: ~
|
||||
- kind:
|
||||
NoneComparison: NotEq
|
||||
location:
|
||||
row: 20
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind:
|
||||
NoneComparison: Eq
|
||||
location:
|
||||
row: 23
|
||||
column: 4
|
||||
fix: ~
|
||||
|
||||
77
src/snapshots/ruff__linter__tests__e712.snap
Normal file
77
src/snapshots/ruff__linter__tests__e712.snap
Normal file
@@ -0,0 +1,77 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
TrueFalseComparison:
|
||||
- true
|
||||
- Eq
|
||||
location:
|
||||
row: 2
|
||||
column: 11
|
||||
fix: ~
|
||||
- kind:
|
||||
TrueFalseComparison:
|
||||
- false
|
||||
- NotEq
|
||||
location:
|
||||
row: 5
|
||||
column: 11
|
||||
fix: ~
|
||||
- kind:
|
||||
TrueFalseComparison:
|
||||
- true
|
||||
- NotEq
|
||||
location:
|
||||
row: 8
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind:
|
||||
TrueFalseComparison:
|
||||
- false
|
||||
- Eq
|
||||
location:
|
||||
row: 11
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind:
|
||||
TrueFalseComparison:
|
||||
- true
|
||||
- Eq
|
||||
location:
|
||||
row: 14
|
||||
column: 14
|
||||
fix: ~
|
||||
- kind:
|
||||
TrueFalseComparison:
|
||||
- false
|
||||
- NotEq
|
||||
location:
|
||||
row: 17
|
||||
column: 14
|
||||
fix: ~
|
||||
- kind:
|
||||
TrueFalseComparison:
|
||||
- true
|
||||
- Eq
|
||||
location:
|
||||
row: 20
|
||||
column: 20
|
||||
fix: ~
|
||||
- kind:
|
||||
TrueFalseComparison:
|
||||
- false
|
||||
- Eq
|
||||
location:
|
||||
row: 20
|
||||
column: 44
|
||||
fix: ~
|
||||
- kind:
|
||||
TrueFalseComparison:
|
||||
- true
|
||||
- Eq
|
||||
location:
|
||||
row: 22
|
||||
column: 5
|
||||
fix: ~
|
||||
|
||||
30
src/snapshots/ruff__linter__tests__e713.snap
Normal file
30
src/snapshots/ruff__linter__tests__e713.snap
Normal file
@@ -0,0 +1,30 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: NotInTest
|
||||
location:
|
||||
row: 2
|
||||
column: 10
|
||||
fix: ~
|
||||
- kind: NotInTest
|
||||
location:
|
||||
row: 5
|
||||
column: 12
|
||||
fix: ~
|
||||
- kind: NotInTest
|
||||
location:
|
||||
row: 8
|
||||
column: 10
|
||||
fix: ~
|
||||
- kind: NotInTest
|
||||
location:
|
||||
row: 11
|
||||
column: 25
|
||||
fix: ~
|
||||
- kind: NotInTest
|
||||
location:
|
||||
row: 14
|
||||
column: 11
|
||||
fix: ~
|
||||
|
||||
20
src/snapshots/ruff__linter__tests__e714.snap
Normal file
20
src/snapshots/ruff__linter__tests__e714.snap
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: NotIsTest
|
||||
location:
|
||||
row: 2
|
||||
column: 10
|
||||
fix: ~
|
||||
- kind: NotIsTest
|
||||
location:
|
||||
row: 5
|
||||
column: 12
|
||||
fix: ~
|
||||
- kind: NotIsTest
|
||||
location:
|
||||
row: 8
|
||||
column: 10
|
||||
fix: ~
|
||||
|
||||
85
src/snapshots/ruff__linter__tests__e721.snap
Normal file
85
src/snapshots/ruff__linter__tests__e721.snap
Normal file
@@ -0,0 +1,85 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: TypeComparison
|
||||
location:
|
||||
row: 2
|
||||
column: 14
|
||||
fix: ~
|
||||
- kind: TypeComparison
|
||||
location:
|
||||
row: 5
|
||||
column: 14
|
||||
fix: ~
|
||||
- kind: TypeComparison
|
||||
location:
|
||||
row: 10
|
||||
column: 8
|
||||
fix: ~
|
||||
- kind: TypeComparison
|
||||
location:
|
||||
row: 15
|
||||
column: 14
|
||||
fix: ~
|
||||
- kind: TypeComparison
|
||||
location:
|
||||
row: 18
|
||||
column: 18
|
||||
fix: ~
|
||||
- kind: TypeComparison
|
||||
location:
|
||||
row: 18
|
||||
column: 46
|
||||
fix: ~
|
||||
- kind: TypeComparison
|
||||
location:
|
||||
row: 20
|
||||
column: 18
|
||||
fix: ~
|
||||
- kind: TypeComparison
|
||||
location:
|
||||
row: 22
|
||||
column: 18
|
||||
fix: ~
|
||||
- kind: TypeComparison
|
||||
location:
|
||||
row: 24
|
||||
column: 18
|
||||
fix: ~
|
||||
- kind: TypeComparison
|
||||
location:
|
||||
row: 26
|
||||
column: 18
|
||||
fix: ~
|
||||
- kind: TypeComparison
|
||||
location:
|
||||
row: 28
|
||||
column: 18
|
||||
fix: ~
|
||||
- kind: TypeComparison
|
||||
location:
|
||||
row: 30
|
||||
column: 18
|
||||
fix: ~
|
||||
- kind: TypeComparison
|
||||
location:
|
||||
row: 32
|
||||
column: 18
|
||||
fix: ~
|
||||
- kind: TypeComparison
|
||||
location:
|
||||
row: 34
|
||||
column: 18
|
||||
fix: ~
|
||||
- kind: TypeComparison
|
||||
location:
|
||||
row: 40
|
||||
column: 18
|
||||
fix: ~
|
||||
- kind: TypeComparison
|
||||
location:
|
||||
row: 42
|
||||
column: 18
|
||||
fix: ~
|
||||
|
||||
20
src/snapshots/ruff__linter__tests__e722.snap
Normal file
20
src/snapshots/ruff__linter__tests__e722.snap
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: DoNotUseBareExcept
|
||||
location:
|
||||
row: 4
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind: DoNotUseBareExcept
|
||||
location:
|
||||
row: 11
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind: DoNotUseBareExcept
|
||||
location:
|
||||
row: 16
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
30
src/snapshots/ruff__linter__tests__e731.snap
Normal file
30
src/snapshots/ruff__linter__tests__e731.snap
Normal file
@@ -0,0 +1,30 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: DoNotAssignLambda
|
||||
location:
|
||||
row: 2
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind: DoNotAssignLambda
|
||||
location:
|
||||
row: 4
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind: DoNotAssignLambda
|
||||
location:
|
||||
row: 7
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind: DoNotAssignLambda
|
||||
location:
|
||||
row: 12
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind: DoNotAssignLambda
|
||||
location:
|
||||
row: 16
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
155
src/snapshots/ruff__linter__tests__e741.snap
Normal file
155
src/snapshots/ruff__linter__tests__e741.snap
Normal file
@@ -0,0 +1,155 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 3
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: I
|
||||
location:
|
||||
row: 4
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: O
|
||||
location:
|
||||
row: 5
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 6
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 8
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 9
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 10
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 11
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 16
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 20
|
||||
column: 8
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 25
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 26
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 30
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 33
|
||||
column: 9
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 34
|
||||
column: 9
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 40
|
||||
column: 8
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: I
|
||||
location:
|
||||
row: 40
|
||||
column: 14
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 44
|
||||
column: 8
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: I
|
||||
location:
|
||||
row: 44
|
||||
column: 16
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 48
|
||||
column: 9
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: I
|
||||
location:
|
||||
row: 48
|
||||
column: 14
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 57
|
||||
column: 16
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 66
|
||||
column: 20
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 71
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousVariableName: l
|
||||
location:
|
||||
row: 74
|
||||
column: 5
|
||||
fix: ~
|
||||
|
||||
23
src/snapshots/ruff__linter__tests__e742.snap
Normal file
23
src/snapshots/ruff__linter__tests__e742.snap
Normal file
@@ -0,0 +1,23 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
AmbiguousClassName: l
|
||||
location:
|
||||
row: 1
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousClassName: I
|
||||
location:
|
||||
row: 5
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousClassName: O
|
||||
location:
|
||||
row: 9
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
23
src/snapshots/ruff__linter__tests__e743.snap
Normal file
23
src/snapshots/ruff__linter__tests__e743.snap
Normal file
@@ -0,0 +1,23 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
AmbiguousFunctionName: l
|
||||
location:
|
||||
row: 1
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousFunctionName: I
|
||||
location:
|
||||
row: 5
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind:
|
||||
AmbiguousFunctionName: O
|
||||
location:
|
||||
row: 10
|
||||
column: 5
|
||||
fix: ~
|
||||
|
||||
23
src/snapshots/ruff__linter__tests__f401.snap
Normal file
23
src/snapshots/ruff__linter__tests__f401.snap
Normal file
@@ -0,0 +1,23 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
UnusedImport: functools
|
||||
location:
|
||||
row: 3
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind:
|
||||
UnusedImport: collections.OrderedDict
|
||||
location:
|
||||
row: 5
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind:
|
||||
UnusedImport: logging.handlers
|
||||
location:
|
||||
row: 13
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
17
src/snapshots/ruff__linter__tests__f403.snap
Normal file
17
src/snapshots/ruff__linter__tests__f403.snap
Normal file
@@ -0,0 +1,17 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
ImportStarUsage: F634
|
||||
location:
|
||||
row: 1
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind:
|
||||
ImportStarUsage: F634
|
||||
location:
|
||||
row: 2
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
10
src/snapshots/ruff__linter__tests__f404.snap
Normal file
10
src/snapshots/ruff__linter__tests__f404.snap
Normal file
@@ -0,0 +1,10 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: LateFutureImport
|
||||
location:
|
||||
row: 7
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
17
src/snapshots/ruff__linter__tests__f406.snap
Normal file
17
src/snapshots/ruff__linter__tests__f406.snap
Normal file
@@ -0,0 +1,17 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
ImportStarNotPermitted: F634
|
||||
location:
|
||||
row: 5
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind:
|
||||
ImportStarNotPermitted: F634
|
||||
location:
|
||||
row: 9
|
||||
column: 5
|
||||
fix: ~
|
||||
|
||||
11
src/snapshots/ruff__linter__tests__f407.snap
Normal file
11
src/snapshots/ruff__linter__tests__f407.snap
Normal file
@@ -0,0 +1,11 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
FutureFeatureNotDefined: non_existent_feature
|
||||
location:
|
||||
row: 2
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
20
src/snapshots/ruff__linter__tests__f541.snap
Normal file
20
src/snapshots/ruff__linter__tests__f541.snap
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: FStringMissingPlaceholders
|
||||
location:
|
||||
row: 4
|
||||
column: 7
|
||||
fix: ~
|
||||
- kind: FStringMissingPlaceholders
|
||||
location:
|
||||
row: 5
|
||||
column: 7
|
||||
fix: ~
|
||||
- kind: FStringMissingPlaceholders
|
||||
location:
|
||||
row: 7
|
||||
column: 7
|
||||
fix: ~
|
||||
|
||||
20
src/snapshots/ruff__linter__tests__f601.snap
Normal file
20
src/snapshots/ruff__linter__tests__f601.snap
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: MultiValueRepeatedKeyLiteral
|
||||
location:
|
||||
row: 3
|
||||
column: 6
|
||||
fix: ~
|
||||
- kind: MultiValueRepeatedKeyLiteral
|
||||
location:
|
||||
row: 9
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind: MultiValueRepeatedKeyLiteral
|
||||
location:
|
||||
row: 11
|
||||
column: 7
|
||||
fix: ~
|
||||
|
||||
11
src/snapshots/ruff__linter__tests__f602.snap
Normal file
11
src/snapshots/ruff__linter__tests__f602.snap
Normal file
@@ -0,0 +1,11 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
MultiValueRepeatedKeyVariable: a
|
||||
location:
|
||||
row: 5
|
||||
column: 5
|
||||
fix: ~
|
||||
|
||||
10
src/snapshots/ruff__linter__tests__f622.snap
Normal file
10
src/snapshots/ruff__linter__tests__f622.snap
Normal file
@@ -0,0 +1,10 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: TwoStarredExpressions
|
||||
location:
|
||||
row: 1
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
15
src/snapshots/ruff__linter__tests__f631.snap
Normal file
15
src/snapshots/ruff__linter__tests__f631.snap
Normal file
@@ -0,0 +1,15 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: AssertTuple
|
||||
location:
|
||||
row: 1
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind: AssertTuple
|
||||
location:
|
||||
row: 2
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
15
src/snapshots/ruff__linter__tests__f632.snap
Normal file
15
src/snapshots/ruff__linter__tests__f632.snap
Normal file
@@ -0,0 +1,15 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: IsLiteral
|
||||
location:
|
||||
row: 1
|
||||
column: 6
|
||||
fix: ~
|
||||
- kind: IsLiteral
|
||||
location:
|
||||
row: 4
|
||||
column: 8
|
||||
fix: ~
|
||||
|
||||
10
src/snapshots/ruff__linter__tests__f633.snap
Normal file
10
src/snapshots/ruff__linter__tests__f633.snap
Normal file
@@ -0,0 +1,10 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: InvalidPrintSyntax
|
||||
location:
|
||||
row: 4
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
15
src/snapshots/ruff__linter__tests__f634.snap
Normal file
15
src/snapshots/ruff__linter__tests__f634.snap
Normal file
@@ -0,0 +1,15 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: IfTuple
|
||||
location:
|
||||
row: 1
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind: IfTuple
|
||||
location:
|
||||
row: 7
|
||||
column: 5
|
||||
fix: ~
|
||||
|
||||
25
src/snapshots/ruff__linter__tests__f701.snap
Normal file
25
src/snapshots/ruff__linter__tests__f701.snap
Normal file
@@ -0,0 +1,25 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: BreakOutsideLoop
|
||||
location:
|
||||
row: 4
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind: BreakOutsideLoop
|
||||
location:
|
||||
row: 16
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind: BreakOutsideLoop
|
||||
location:
|
||||
row: 20
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind: BreakOutsideLoop
|
||||
location:
|
||||
row: 23
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
25
src/snapshots/ruff__linter__tests__f702.snap
Normal file
25
src/snapshots/ruff__linter__tests__f702.snap
Normal file
@@ -0,0 +1,25 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: ContinueOutsideLoop
|
||||
location:
|
||||
row: 4
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind: ContinueOutsideLoop
|
||||
location:
|
||||
row: 16
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind: ContinueOutsideLoop
|
||||
location:
|
||||
row: 20
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind: ContinueOutsideLoop
|
||||
location:
|
||||
row: 23
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
20
src/snapshots/ruff__linter__tests__f704.snap
Normal file
20
src/snapshots/ruff__linter__tests__f704.snap
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: YieldOutsideFunction
|
||||
location:
|
||||
row: 6
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind: YieldOutsideFunction
|
||||
location:
|
||||
row: 9
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind: YieldOutsideFunction
|
||||
location:
|
||||
row: 10
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
15
src/snapshots/ruff__linter__tests__f706.snap
Normal file
15
src/snapshots/ruff__linter__tests__f706.snap
Normal file
@@ -0,0 +1,15 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: ReturnOutsideFunction
|
||||
location:
|
||||
row: 6
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind: ReturnOutsideFunction
|
||||
location:
|
||||
row: 9
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
20
src/snapshots/ruff__linter__tests__f707.snap
Normal file
20
src/snapshots/ruff__linter__tests__f707.snap
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: DefaultExceptNotLast
|
||||
location:
|
||||
row: 3
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind: DefaultExceptNotLast
|
||||
location:
|
||||
row: 10
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind: DefaultExceptNotLast
|
||||
location:
|
||||
row: 19
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
11
src/snapshots/ruff__linter__tests__f722.snap
Normal file
11
src/snapshots/ruff__linter__tests__f722.snap
Normal file
@@ -0,0 +1,11 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
ForwardAnnotationSyntaxError: ///
|
||||
location:
|
||||
row: 9
|
||||
column: 13
|
||||
fix: ~
|
||||
|
||||
41
src/snapshots/ruff__linter__tests__f821.snap
Normal file
41
src/snapshots/ruff__linter__tests__f821.snap
Normal file
@@ -0,0 +1,41 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
UndefinedName: self
|
||||
location:
|
||||
row: 2
|
||||
column: 12
|
||||
fix: ~
|
||||
- kind:
|
||||
UndefinedName: self
|
||||
location:
|
||||
row: 6
|
||||
column: 13
|
||||
fix: ~
|
||||
- kind:
|
||||
UndefinedName: self
|
||||
location:
|
||||
row: 10
|
||||
column: 9
|
||||
fix: ~
|
||||
- kind:
|
||||
UndefinedName: numeric_string
|
||||
location:
|
||||
row: 21
|
||||
column: 12
|
||||
fix: ~
|
||||
- kind:
|
||||
UndefinedName: Bar
|
||||
location:
|
||||
row: 58
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind:
|
||||
UndefinedName: TOMATO
|
||||
location:
|
||||
row: 83
|
||||
column: 11
|
||||
fix: ~
|
||||
|
||||
11
src/snapshots/ruff__linter__tests__f822.snap
Normal file
11
src/snapshots/ruff__linter__tests__f822.snap
Normal file
@@ -0,0 +1,11 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
UndefinedExport: b
|
||||
location:
|
||||
row: 3
|
||||
column: 1
|
||||
fix: ~
|
||||
|
||||
11
src/snapshots/ruff__linter__tests__f823.snap
Normal file
11
src/snapshots/ruff__linter__tests__f823.snap
Normal file
@@ -0,0 +1,11 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
UndefinedLocal: my_var
|
||||
location:
|
||||
row: 6
|
||||
column: 5
|
||||
fix: ~
|
||||
|
||||
20
src/snapshots/ruff__linter__tests__f831.snap
Normal file
20
src/snapshots/ruff__linter__tests__f831.snap
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: DuplicateArgumentName
|
||||
location:
|
||||
row: 1
|
||||
column: 25
|
||||
fix: ~
|
||||
- kind: DuplicateArgumentName
|
||||
location:
|
||||
row: 5
|
||||
column: 28
|
||||
fix: ~
|
||||
- kind: DuplicateArgumentName
|
||||
location:
|
||||
row: 9
|
||||
column: 27
|
||||
fix: ~
|
||||
|
||||
35
src/snapshots/ruff__linter__tests__f841.snap
Normal file
35
src/snapshots/ruff__linter__tests__f841.snap
Normal file
@@ -0,0 +1,35 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
UnusedVariable: e
|
||||
location:
|
||||
row: 3
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind:
|
||||
UnusedVariable: z
|
||||
location:
|
||||
row: 16
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind:
|
||||
UnusedVariable: foo
|
||||
location:
|
||||
row: 20
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind:
|
||||
UnusedVariable: a
|
||||
location:
|
||||
row: 21
|
||||
column: 6
|
||||
fix: ~
|
||||
- kind:
|
||||
UnusedVariable: b
|
||||
location:
|
||||
row: 21
|
||||
column: 9
|
||||
fix: ~
|
||||
|
||||
15
src/snapshots/ruff__linter__tests__f901.snap
Normal file
15
src/snapshots/ruff__linter__tests__f901.snap
Normal file
@@ -0,0 +1,15 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: RaiseNotImplemented
|
||||
location:
|
||||
row: 2
|
||||
column: 25
|
||||
fix: ~
|
||||
- kind: RaiseNotImplemented
|
||||
location:
|
||||
row: 6
|
||||
column: 11
|
||||
fix: ~
|
||||
|
||||
17
src/snapshots/ruff__linter__tests__future_annotations.snap
Normal file
17
src/snapshots/ruff__linter__tests__future_annotations.snap
Normal file
@@ -0,0 +1,17 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
UnusedImport: models.Nut
|
||||
location:
|
||||
row: 5
|
||||
column: 1
|
||||
fix: ~
|
||||
- kind:
|
||||
UndefinedName: Bar
|
||||
location:
|
||||
row: 22
|
||||
column: 19
|
||||
fix: ~
|
||||
|
||||
6
src/snapshots/ruff__linter__tests__init.snap
Normal file
6
src/snapshots/ruff__linter__tests__init.snap
Normal file
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
[]
|
||||
|
||||
285
src/snapshots/ruff__linter__tests__r001.snap
Normal file
285
src/snapshots/ruff__linter__tests__r001.snap
Normal file
@@ -0,0 +1,285 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind:
|
||||
UselessObjectInheritance: A
|
||||
location:
|
||||
row: 5
|
||||
column: 9
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 5
|
||||
column: 8
|
||||
end:
|
||||
row: 5
|
||||
column: 16
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: A
|
||||
location:
|
||||
row: 10
|
||||
column: 5
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 9
|
||||
column: 8
|
||||
end:
|
||||
row: 11
|
||||
column: 2
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: A
|
||||
location:
|
||||
row: 16
|
||||
column: 5
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 15
|
||||
column: 8
|
||||
end:
|
||||
row: 18
|
||||
column: 2
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: A
|
||||
location:
|
||||
row: 24
|
||||
column: 5
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 22
|
||||
column: 8
|
||||
end:
|
||||
row: 25
|
||||
column: 2
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: A
|
||||
location:
|
||||
row: 31
|
||||
column: 5
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 29
|
||||
column: 8
|
||||
end:
|
||||
row: 32
|
||||
column: 2
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: A
|
||||
location:
|
||||
row: 37
|
||||
column: 5
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 36
|
||||
column: 8
|
||||
end:
|
||||
row: 39
|
||||
column: 2
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: A
|
||||
location:
|
||||
row: 45
|
||||
column: 5
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 43
|
||||
column: 8
|
||||
end:
|
||||
row: 47
|
||||
column: 2
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: A
|
||||
location:
|
||||
row: 53
|
||||
column: 5
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 51
|
||||
column: 8
|
||||
end:
|
||||
row: 55
|
||||
column: 2
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: A
|
||||
location:
|
||||
row: 61
|
||||
column: 5
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 59
|
||||
column: 8
|
||||
end:
|
||||
row: 63
|
||||
column: 2
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: A
|
||||
location:
|
||||
row: 69
|
||||
column: 5
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 67
|
||||
column: 8
|
||||
end:
|
||||
row: 71
|
||||
column: 2
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: B
|
||||
location:
|
||||
row: 75
|
||||
column: 12
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 75
|
||||
column: 10
|
||||
end:
|
||||
row: 75
|
||||
column: 18
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: B
|
||||
location:
|
||||
row: 79
|
||||
column: 9
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 79
|
||||
column: 9
|
||||
end:
|
||||
row: 79
|
||||
column: 17
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: B
|
||||
location:
|
||||
row: 84
|
||||
column: 5
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 84
|
||||
column: 5
|
||||
end:
|
||||
row: 85
|
||||
column: 5
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: B
|
||||
location:
|
||||
row: 92
|
||||
column: 5
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 91
|
||||
column: 6
|
||||
end:
|
||||
row: 92
|
||||
column: 11
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: B
|
||||
location:
|
||||
row: 98
|
||||
column: 5
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 98
|
||||
column: 5
|
||||
end:
|
||||
row: 100
|
||||
column: 5
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: B
|
||||
location:
|
||||
row: 108
|
||||
column: 5
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 107
|
||||
column: 6
|
||||
end:
|
||||
row: 108
|
||||
column: 11
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: A
|
||||
location:
|
||||
row: 114
|
||||
column: 13
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 114
|
||||
column: 12
|
||||
end:
|
||||
row: 114
|
||||
column: 20
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: A
|
||||
location:
|
||||
row: 119
|
||||
column: 5
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 118
|
||||
column: 8
|
||||
end:
|
||||
row: 120
|
||||
column: 2
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: A
|
||||
location:
|
||||
row: 125
|
||||
column: 5
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 124
|
||||
column: 8
|
||||
end:
|
||||
row: 126
|
||||
column: 2
|
||||
applied: false
|
||||
- kind:
|
||||
UselessObjectInheritance: A
|
||||
location:
|
||||
row: 131
|
||||
column: 5
|
||||
fix:
|
||||
content: ""
|
||||
start:
|
||||
row: 130
|
||||
column: 8
|
||||
end:
|
||||
row: 133
|
||||
column: 2
|
||||
applied: false
|
||||
|
||||
31
src/snapshots/ruff__linter__tests__r002.snap
Normal file
31
src/snapshots/ruff__linter__tests__r002.snap
Normal file
@@ -0,0 +1,31 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: NoAssertEquals
|
||||
location:
|
||||
row: 1
|
||||
column: 5
|
||||
fix:
|
||||
content: assertEqual
|
||||
start:
|
||||
row: 1
|
||||
column: 6
|
||||
end:
|
||||
row: 1
|
||||
column: 18
|
||||
applied: false
|
||||
- kind: NoAssertEquals
|
||||
location:
|
||||
row: 2
|
||||
column: 5
|
||||
fix:
|
||||
content: assertEqual
|
||||
start:
|
||||
row: 2
|
||||
column: 6
|
||||
end:
|
||||
row: 2
|
||||
column: 18
|
||||
applied: false
|
||||
|
||||
Reference in New Issue
Block a user