Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
edab268d50 | ||
|
|
e4fad70a57 | ||
|
|
1a09fff991 | ||
|
|
b85105d2ec | ||
|
|
f7ac28a935 | ||
|
|
9532f342a6 | ||
|
|
0ee37aa0aa |
15
.github/CONTRIBUTING.md
vendored
15
.github/CONTRIBUTING.md
vendored
@@ -56,9 +56,9 @@ prior to merging.
|
||||
|
||||
There are four phases to adding a new lint rule:
|
||||
|
||||
1. Define the violation in `src/violations.rs` (e.g., `ModuleImportNotAtTopOfFile`).
|
||||
2. Map the violation to a code in `src/registry.rs` (e.g., `E402`).
|
||||
3. Define the _logic_ for triggering the violation in `src/checkers/ast.rs` (for AST-based checks),
|
||||
1. Define the violation struct in `src/violations.rs` (e.g., `ModuleImportNotAtTopOfFile`).
|
||||
2. Map the violation struct to a rule code in `src/registry.rs` (e.g., `E402`).
|
||||
3. Define the logic for triggering the violation in `src/checkers/ast.rs` (for AST-based checks),
|
||||
`src/checkers/tokens.rs` (for token-based checks), or `src/checkers/lines.rs` (for text-based checks).
|
||||
4. Add a test fixture.
|
||||
5. Update the generated files (documentation and generated code).
|
||||
@@ -74,15 +74,16 @@ collecting diagnostics as it goes.
|
||||
If you need to inspect the AST, you can run `cargo +nightly dev print-ast` with a Python file. Grep
|
||||
for the `Check::new` invocations to understand how other, similar rules are implemented.
|
||||
|
||||
To add a test fixture, create a file under `resources/test/fixtures/[plugin-name]`, named to match
|
||||
the code you defined earlier (e.g., `E402.py`). This file should contain a variety of
|
||||
violations and non-violations designed to evaluate and demonstrate the behavior of your lint rule.
|
||||
To add a test fixture, create a file under `resources/test/fixtures/[origin]`, named to match
|
||||
the code you defined earlier (e.g., `resources/test/fixtures/pycodestyle/E402.py`). This file should
|
||||
contain a variety of violations and non-violations designed to evaluate and demonstrate the behavior
|
||||
of your lint rule.
|
||||
|
||||
Run `cargo +nightly dev generate-all` to generate the code for your new fixture. Then run Ruff
|
||||
locally with (e.g.) `cargo run resources/test/fixtures/pycodestyle/E402.py --no-cache --select E402`.
|
||||
|
||||
Once you're satisfied with the output, codify the behavior as a snapshot test by adding a new
|
||||
`test_case` macro in the relevant `src/[plugin-name]/mod.rs` file. Then, run `cargo test --all`.
|
||||
`test_case` macro in the relevant `src/[origin]/mod.rs` file. Then, run `cargo test --all`.
|
||||
Your test will fail, but you'll be prompted to follow-up with `cargo insta review`. Accept the
|
||||
generated snapshot, then commit the snapshot file alongside the rest of your changes.
|
||||
|
||||
|
||||
65
.github/workflows/ci.yaml
vendored
65
.github/workflows/ci.yaml
vendored
@@ -26,19 +26,7 @@ jobs:
|
||||
profile: minimal
|
||||
toolchain: nightly-2022-11-01
|
||||
override: true
|
||||
components: rustfmt
|
||||
- uses: actions/cache@v3
|
||||
env:
|
||||
cache-name: cache-cargo
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-build-${{ env.cache-name }}-
|
||||
${{ runner.os }}-build-
|
||||
${{ runner.os }}-
|
||||
- uses: Swatinem/rust-cache@v1
|
||||
- run: cargo build --all --release
|
||||
- run: ./target/release/ruff_dev generate-all
|
||||
- run: git diff --quiet README.md || echo "::error file=README.md::This file is outdated. Run 'cargo +nightly dev generate-all'."
|
||||
@@ -56,18 +44,6 @@ jobs:
|
||||
toolchain: nightly-2022-11-01
|
||||
override: true
|
||||
components: rustfmt
|
||||
- uses: actions/cache@v3
|
||||
env:
|
||||
cache-name: cache-cargo
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-build-${{ env.cache-name }}-
|
||||
${{ runner.os }}-build-
|
||||
${{ runner.os }}-
|
||||
- run: cargo fmt --all --check
|
||||
|
||||
cargo_clippy:
|
||||
@@ -82,18 +58,7 @@ jobs:
|
||||
override: true
|
||||
components: clippy
|
||||
target: wasm32-unknown-unknown
|
||||
- uses: actions/cache@v3
|
||||
env:
|
||||
cache-name: cache-cargo
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-build-${{ env.cache-name }}-
|
||||
${{ runner.os }}-build-
|
||||
${{ runner.os }}-
|
||||
- uses: Swatinem/rust-cache@v1
|
||||
- run: cargo clippy --workspace --all-targets --all-features -- -D warnings -W clippy::pedantic
|
||||
- run: cargo clippy --workspace --target wasm32-unknown-unknown --all-features -- -D warnings -W clippy::pedantic
|
||||
|
||||
@@ -107,18 +72,7 @@ jobs:
|
||||
profile: minimal
|
||||
toolchain: nightly-2022-11-01
|
||||
override: true
|
||||
- uses: actions/cache@v3
|
||||
env:
|
||||
cache-name: cache-cargo
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-build-${{ env.cache-name }}-
|
||||
${{ runner.os }}-build-
|
||||
${{ runner.os }}-
|
||||
- uses: Swatinem/rust-cache@v1
|
||||
- run: cargo install cargo-insta
|
||||
- run: pip install black[d]==22.12.0
|
||||
- name: Run tests
|
||||
@@ -167,22 +121,11 @@ jobs:
|
||||
profile: minimal
|
||||
toolchain: nightly-2022-11-01
|
||||
override: true
|
||||
- uses: Swatinem/rust-cache@v1
|
||||
- uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: "3.11"
|
||||
- run: pip install maturin
|
||||
- uses: actions/cache@v3
|
||||
env:
|
||||
cache-name: cache-cargo
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-build-${{ env.cache-name }}-
|
||||
${{ runner.os }}-build-
|
||||
${{ runner.os }}-
|
||||
- run: maturin build -b bin
|
||||
|
||||
typos:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
repos:
|
||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||
rev: v0.0.216
|
||||
rev: v0.0.217
|
||||
hooks:
|
||||
- id: ruff
|
||||
|
||||
|
||||
8
Cargo.lock
generated
8
Cargo.lock
generated
@@ -735,7 +735,7 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
|
||||
|
||||
[[package]]
|
||||
name = "flake8-to-ruff"
|
||||
version = "0.0.216-dev.0"
|
||||
version = "0.0.217-dev.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap 4.0.32",
|
||||
@@ -1874,7 +1874,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ruff"
|
||||
version = "0.0.216"
|
||||
version = "0.0.217"
|
||||
dependencies = [
|
||||
"annotate-snippets 0.9.1",
|
||||
"anyhow",
|
||||
@@ -1942,7 +1942,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ruff_dev"
|
||||
version = "0.0.216"
|
||||
version = "0.0.217"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap 4.0.32",
|
||||
@@ -1962,7 +1962,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ruff_macros"
|
||||
version = "0.0.216"
|
||||
version = "0.0.217"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"proc-macro2",
|
||||
|
||||
@@ -6,7 +6,7 @@ members = [
|
||||
|
||||
[package]
|
||||
name = "ruff"
|
||||
version = "0.0.216"
|
||||
version = "0.0.217"
|
||||
authors = ["Charlie Marsh <charlie.r.marsh@gmail.com>"]
|
||||
edition = "2021"
|
||||
rust-version = "1.65.0"
|
||||
@@ -51,7 +51,7 @@ path-absolutize = { version = "3.0.14", features = ["once_cell_cache", "use_unix
|
||||
quick-junit = { version = "0.3.2" }
|
||||
regex = { version = "1.6.0" }
|
||||
ropey = { version = "1.5.0", features = ["cr_lines", "simd"], default-features = false }
|
||||
ruff_macros = { version = "0.0.216", path = "ruff_macros" }
|
||||
ruff_macros = { version = "0.0.217", path = "ruff_macros" }
|
||||
rustc-hash = { version = "1.1.0" }
|
||||
rustpython-ast = { features = ["unparse"], git = "https://github.com/RustPython/RustPython.git", rev = "d532160333ffeb6dbeca2c2728c2391cd1e53b7f" }
|
||||
rustpython-common = { git = "https://github.com/RustPython/RustPython.git", rev = "d532160333ffeb6dbeca2c2728c2391cd1e53b7f" }
|
||||
|
||||
192
README.md
192
README.md
@@ -164,9 +164,9 @@ pacman -S ruff
|
||||
To run Ruff, try any of the following:
|
||||
|
||||
```shell
|
||||
ruff path/to/code/to/check.py # Run Ruff over `check.py`
|
||||
ruff path/to/code/ # Run Ruff over all files in `/path/to/code` (and any subdirectories)
|
||||
ruff path/to/code/*.py # Run Ruff over all `.py` files in `/path/to/code`
|
||||
ruff path/to/code/to/lint.py # Run Ruff over `lint.py`
|
||||
ruff path/to/code/ # Run Ruff over all files in `/path/to/code` (and any subdirectories)
|
||||
ruff path/to/code/*.py # Run Ruff over all `.py` files in `/path/to/code`
|
||||
```
|
||||
|
||||
You can run Ruff in `--watch` mode to automatically re-run on-change:
|
||||
@@ -180,7 +180,7 @@ Ruff also works with [pre-commit](https://pre-commit.com):
|
||||
```yaml
|
||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||
# Ruff version.
|
||||
rev: 'v0.0.216'
|
||||
rev: 'v0.0.217'
|
||||
hooks:
|
||||
- id: ruff
|
||||
# Respect `exclude` and `extend-exclude` settings.
|
||||
@@ -237,9 +237,9 @@ target-version = "py310"
|
||||
max-complexity = 10
|
||||
```
|
||||
|
||||
As an example, the following would configure Ruff to: (1) avoid checking for line-length
|
||||
violations (`E501`); (2) never remove unused imports (`F401`); and (3) ignore import-at-top-of-file
|
||||
errors (`E402`) in `__init__.py` files:
|
||||
As an example, the following would configure Ruff to: (1) avoid enforcing line-length violations
|
||||
(`E501`); (2) never remove unused imports (`F401`); and (3) ignore import-at-top-of-file violations
|
||||
(`E402`) in `__init__.py` files:
|
||||
|
||||
```toml
|
||||
[tool.ruff]
|
||||
@@ -269,16 +269,16 @@ select = ["E", "F", "Q"]
|
||||
docstring-quotes = "double"
|
||||
```
|
||||
|
||||
Ruff mirrors Flake8's error code system, in which each error code consists of a one-to-three letter
|
||||
prefix, followed by three digits (e.g., `F401`). The prefix indicates that "source" of the error
|
||||
code (e.g., `F` for Pyflakes, `E` for `pycodestyle`, `ANN` for `flake8-annotations`). The set of
|
||||
enabled errors is determined by the `select` and `ignore` options, which support both the full
|
||||
error code (e.g., `F401`) and the prefix (e.g., `F`).
|
||||
Ruff mirrors Flake8's rule code system, in which each rule code consists of a one-to-three letter
|
||||
prefix, followed by three digits (e.g., `F401`). The prefix indicates that "source" of the rule
|
||||
(e.g., `F` for Pyflakes, `E` for `pycodestyle`, `ANN` for `flake8-annotations`). The set of enabled
|
||||
rules is determined by the `select` and `ignore` options, which support both the full code (e.g.,
|
||||
`F401`) and the prefix (e.g., `F`).
|
||||
|
||||
As a special-case, Ruff also supports the `ALL` error code, which enables all error codes. Note that
|
||||
some of the `pydocstyle` error codes are conflicting (e.g., `D203` and `D211`) as they represent
|
||||
alternative docstring formats. Enabling `ALL` without further configuration may result in suboptimal
|
||||
behavior, especially for the `pydocstyle` plugin.
|
||||
As a special-case, Ruff also supports the `ALL` code, which enables all rules. Note that some of the
|
||||
`pydocstyle` rules conflict (e.g., `D203` and `D211`) as they represent alternative docstring
|
||||
formats. Enabling `ALL` without further configuration may result in suboptimal behavior, especially
|
||||
for the `pydocstyle` plugin.
|
||||
|
||||
As an alternative to `pyproject.toml`, Ruff will also respect a `ruff.toml` file, which implements
|
||||
an equivalent schema (though the `[tool.ruff]` hierarchy can be omitted). For example, the
|
||||
@@ -326,17 +326,17 @@ Options:
|
||||
-v, --verbose
|
||||
Enable verbose logging
|
||||
-q, --quiet
|
||||
Only log errors
|
||||
Print lint violations, but nothing else
|
||||
-s, --silent
|
||||
Disable all logging (but still exit with status code "1" upon detecting errors)
|
||||
Disable all logging (but still exit with status code "1" upon detecting lint violations)
|
||||
-e, --exit-zero
|
||||
Exit with status code "0", even upon detecting errors
|
||||
Exit with status code "0", even upon detecting lint violations
|
||||
-w, --watch
|
||||
Run in watch mode by re-running whenever files change
|
||||
--fix
|
||||
Attempt to automatically fix lint errors
|
||||
Attempt to automatically fix lint violations
|
||||
--fix-only
|
||||
Fix any fixable lint errors, but don't report on leftover violations. Implies `--fix`
|
||||
Fix any fixable lint violations, but don't report on leftover violations. Implies `--fix`
|
||||
--diff
|
||||
Avoid writing any fixed files back; instead, output a diff for each changed file to stdout
|
||||
-n, --no-cache
|
||||
@@ -346,23 +346,23 @@ Options:
|
||||
--select <SELECT>
|
||||
Comma-separated list of rule codes to enable (or ALL, to enable all rules)
|
||||
--extend-select <EXTEND_SELECT>
|
||||
Like --select, but adds additional error codes on top of the selected ones
|
||||
Like --select, but adds additional rule codes on top of the selected ones
|
||||
--ignore <IGNORE>
|
||||
Comma-separated list of error codes to disable
|
||||
Comma-separated list of rule codes to disable
|
||||
--extend-ignore <EXTEND_IGNORE>
|
||||
Like --ignore, but adds additional error codes on top of the ignored ones
|
||||
Like --ignore, but adds additional rule codes on top of the ignored ones
|
||||
--exclude <EXCLUDE>
|
||||
List of paths, used to exclude files and/or directories from checks
|
||||
List of paths, used to omit files and/or directories from analysis
|
||||
--extend-exclude <EXTEND_EXCLUDE>
|
||||
Like --exclude, but adds additional files and directories on top of the excluded ones
|
||||
Like --exclude, but adds additional files and directories on top of those already excluded
|
||||
--fixable <FIXABLE>
|
||||
List of error codes to treat as eligible for autofix. Only applicable when autofix itself is enabled (e.g., via `--fix`)
|
||||
List of rule codes to treat as eligible for autofix. Only applicable when autofix itself is enabled (e.g., via `--fix`)
|
||||
--unfixable <UNFIXABLE>
|
||||
List of error codes to treat as ineligible for autofix. Only applicable when autofix itself is enabled (e.g., via `--fix`)
|
||||
List of rule codes to treat as ineligible for autofix. Only applicable when autofix itself is enabled (e.g., via `--fix`)
|
||||
--per-file-ignores <PER_FILE_IGNORES>
|
||||
List of mappings from file pattern to code to exclude
|
||||
--format <FORMAT>
|
||||
Output serialization format for error messages [env: RUFF_FORMAT=] [possible values: text, json, junit, grouped, github, gitlab]
|
||||
Output serialization format for violations [env: RUFF_FORMAT=] [possible values: text, json, junit, grouped, github, gitlab]
|
||||
--stdin-filename <STDIN_FILENAME>
|
||||
The name of the file when passing it through stdin
|
||||
--cache-dir <CACHE_DIR>
|
||||
@@ -380,7 +380,7 @@ Options:
|
||||
--target-version <TARGET_VERSION>
|
||||
The minimum Python version that should be supported
|
||||
--line-length <LINE_LENGTH>
|
||||
Set the line-length for length-associated checks and automatic formatting
|
||||
Set the line-length for length-associated rules and automatic formatting
|
||||
--max-complexity <MAX_COMPLEXITY>
|
||||
Maximum McCabe complexity allowed for a given function
|
||||
--add-noqa
|
||||
@@ -392,7 +392,7 @@ Options:
|
||||
--show-files
|
||||
See the files Ruff will be run against with the current settings
|
||||
--show-settings
|
||||
See the settings Ruff will use to check a given Python file
|
||||
See the settings Ruff will use to lint a given Python file
|
||||
-h, --help
|
||||
Print help information
|
||||
-V, --version
|
||||
@@ -449,16 +449,16 @@ in each directory's `pyproject.toml` file.
|
||||
By default, Ruff will also skip any files that are omitted via `.ignore`, `.gitignore`,
|
||||
`.git/info/exclude`, and global `gitignore` files (see: [`respect-gitignore`](#respect-gitignore)).
|
||||
|
||||
Files that are passed to `ruff` directly are always checked, regardless of the above criteria.
|
||||
For example, `ruff /path/to/excluded/file.py` will always check `file.py`.
|
||||
Files that are passed to `ruff` directly are always linted, regardless of the above criteria.
|
||||
For example, `ruff /path/to/excluded/file.py` will always lint `file.py`.
|
||||
|
||||
### Ignoring errors
|
||||
|
||||
To omit a lint check entirely, add it to the "ignore" list via [`ignore`](#ignore) or
|
||||
To omit a lint rule entirely, add it to the "ignore" list via [`ignore`](#ignore) or
|
||||
[`extend-ignore`](#extend-ignore), either on the command-line or in your `pyproject.toml` file.
|
||||
|
||||
To ignore an error inline, Ruff uses a `noqa` system similar to [Flake8](https://flake8.pycqa.org/en/3.1.1/user/ignoring-errors.html).
|
||||
To ignore an individual error, add `# noqa: {code}` to the end of the line, like so:
|
||||
To ignore a violation inline, Ruff uses a `noqa` system similar to [Flake8](https://flake8.pycqa.org/en/3.1.1/user/ignoring-errors.html).
|
||||
To ignore an individual violation, add `# noqa: {code}` to the end of the line, like so:
|
||||
|
||||
```python
|
||||
# Ignore F841.
|
||||
@@ -467,7 +467,7 @@ x = 1 # noqa: F841
|
||||
# Ignore E741 and F841.
|
||||
i = 1 # noqa: E741, F841
|
||||
|
||||
# Ignore _all_ errors.
|
||||
# Ignore _all_ violations.
|
||||
x = 1 # noqa
|
||||
```
|
||||
|
||||
@@ -481,9 +481,9 @@ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor i
|
||||
""" # noqa: E501
|
||||
```
|
||||
|
||||
To ignore all errors across an entire file, Ruff supports Flake8's `# flake8: noqa` directive (or,
|
||||
equivalently, `# ruff: noqa`). Adding either of those directives to any part of a file will disable
|
||||
error reporting for the entire file.
|
||||
To ignore all violations across an entire file, Ruff supports Flake8's `# flake8: noqa` directive
|
||||
(or, equivalently, `# ruff: noqa`). Adding either of those directives to any part of a file will
|
||||
disable enforcement across the entire file.
|
||||
|
||||
For targeted exclusions across entire files (e.g., "Ignore all F841 violations in
|
||||
`/path/to/file.py`"), see the [`per-file-ignores`](#per-file-ignores) configuration setting.
|
||||
@@ -502,8 +502,8 @@ for more.
|
||||
|
||||
Ruff supports several workflows to aid in `noqa` management.
|
||||
|
||||
First, Ruff provides a special error code, `RUF100`, to enforce that your `noqa` directives are
|
||||
"valid", in that the errors they _say_ they ignore are actually being triggered on that line (and
|
||||
First, Ruff provides a special rule code, `RUF100`, to enforce that your `noqa` directives are
|
||||
"valid", in that the violations they _say_ they ignore are actually being triggered on that line (and
|
||||
thus suppressed). You can run `ruff /path/to/file.py --extend-select RUF100` to flag unused `noqa`
|
||||
directives.
|
||||
|
||||
@@ -513,13 +513,13 @@ You can run `ruff /path/to/file.py --extend-select RUF100 --fix` to automaticall
|
||||
|
||||
Third, Ruff can _automatically add_ `noqa` directives to all failing lines. This is useful when
|
||||
migrating a new codebase to Ruff. You can run `ruff /path/to/file.py --add-noqa` to automatically
|
||||
add `noqa` directives to all failing lines, with the appropriate error codes.
|
||||
add `noqa` directives to all failing lines, with the appropriate rule codes.
|
||||
|
||||
## Supported Rules
|
||||
|
||||
Regardless of the rule's origin, Ruff re-implements every rule in Rust as a first-party feature.
|
||||
|
||||
By default, Ruff enables all `E` and `F` error codes, which correspond to those built-in to Flake8.
|
||||
By default, Ruff enables all `E` and `F` rule codes, which correspond to those built-in to Flake8.
|
||||
|
||||
The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` command-line option.
|
||||
|
||||
@@ -1066,8 +1066,8 @@ For more, see [pygrep-hooks](https://github.com/pre-commit/pygrep-hooks) on GitH
|
||||
| ---- | ---- | ------- | --- |
|
||||
| PGH001 | NoEval | No builtin `eval()` allowed | |
|
||||
| PGH002 | DeprecatedLogWarn | `warn` is deprecated in favor of `warning` | |
|
||||
| PGH003 | BlanketTypeIgnore | Use specific error codes when ignoring type issues | |
|
||||
| PGH004 | BlanketNOQA | Use specific error codes when using `noqa` | |
|
||||
| PGH003 | BlanketTypeIgnore | Use specific rule codes when ignoring type issues | |
|
||||
| PGH004 | BlanketNOQA | Use specific rule codes when using `noqa` | |
|
||||
|
||||
### Pylint (PLC, PLE, PLR, PLW)
|
||||
|
||||
@@ -1393,7 +1393,7 @@ natively, including:
|
||||
- [`pyupgrade`](https://pypi.org/project/pyupgrade/) ([#827](https://github.com/charliermarsh/ruff/issues/827))
|
||||
- [`yesqa`](https://github.com/asottile/yesqa)
|
||||
|
||||
Note that, in some cases, Ruff uses different error code prefixes than would be found in the
|
||||
Note that, in some cases, Ruff uses different rule codes and prefixes than would be found in the
|
||||
originating Flake8 plugins. For example, Ruff uses `TID252` to represent the `I252` rule from
|
||||
`flake8-tidy-imports`. This helps minimize conflicts across plugins and allows any individual plugin
|
||||
to be toggled on or off with a single (e.g.) `--select TID`, as opposed to `--select I2` (to avoid
|
||||
@@ -1418,9 +1418,9 @@ At time of writing, Pylint implements 409 total rules, while Ruff implements 224
|
||||
at least 60 overlap with the Pylint rule set. Subjectively, Pylint tends to implement more rules
|
||||
based on type inference (e.g., validating the number of arguments in a function call).
|
||||
|
||||
Like Flake8, Pylint supports plugins (called "checkers"), while Ruff implements all checks natively.
|
||||
Like Flake8, Pylint supports plugins (called "checkers"), while Ruff implements all rules natively.
|
||||
|
||||
Unlike Pylint, Ruff is capable of automatically fixing its own lint errors.
|
||||
Unlike Pylint, Ruff is capable of automatically fixing its own lint violations.
|
||||
|
||||
Pylint parity is being tracked in [#689](https://github.com/charliermarsh/ruff/issues/689).
|
||||
|
||||
@@ -1533,7 +1533,7 @@ For example, if you're coming from `flake8-docstrings`, and your originating con
|
||||
`--docstring-convention=numpy`, you'd instead set `convention = "numpy"` in your `pyproject.toml`,
|
||||
as above.
|
||||
|
||||
Alongside `convention`, you'll want to explicitly enable the `D` error code class, like so:
|
||||
Alongside `convention`, you'll want to explicitly enable the `D` rule code prefix, like so:
|
||||
|
||||
```toml
|
||||
[tool.ruff]
|
||||
@@ -1786,7 +1786,7 @@ cache-dir = "~/.cache/ruff"
|
||||
#### [`dummy-variable-rgx`](#dummy-variable-rgx)
|
||||
|
||||
A regular expression used to identify "dummy" variables, or those which
|
||||
should be ignored when evaluating (e.g.) unused-variable checks. The
|
||||
should be ignored when enforcing (e.g.) unused-variable rules. The
|
||||
default expression matches `_`, `__`, and `_var`, but not `_var_`.
|
||||
|
||||
**Default value**: `"^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"`
|
||||
@@ -1880,8 +1880,8 @@ extend-exclude = ["tests", "src/bad.py"]
|
||||
|
||||
#### [`extend-ignore`](#extend-ignore)
|
||||
|
||||
A list of check code prefixes to ignore, in addition to those specified
|
||||
by `ignore`.
|
||||
A list of rule codes or prefixes to ignore, in addition to those
|
||||
specified by `ignore`.
|
||||
|
||||
**Default value**: `[]`
|
||||
|
||||
@@ -1891,7 +1891,7 @@ by `ignore`.
|
||||
|
||||
```toml
|
||||
[tool.ruff]
|
||||
# Skip unused variable checks (`F841`).
|
||||
# Skip unused variable rules (`F841`).
|
||||
extend-ignore = ["F841"]
|
||||
```
|
||||
|
||||
@@ -1899,8 +1899,8 @@ extend-ignore = ["F841"]
|
||||
|
||||
#### [`extend-select`](#extend-select)
|
||||
|
||||
A list of check code prefixes to enable, in addition to those specified
|
||||
by `select`.
|
||||
A list of rule codes or prefixes to enable, in addition to those
|
||||
specified by `select`.
|
||||
|
||||
**Default value**: `[]`
|
||||
|
||||
@@ -1918,7 +1918,7 @@ extend-select = ["B", "Q"]
|
||||
|
||||
#### [`external`](#external)
|
||||
|
||||
A list of check codes that are unsupported by Ruff, but should be
|
||||
A list of rule codes that are unsupported by Ruff, but should be
|
||||
preserved when (e.g.) validating `# noqa` directives. Useful for
|
||||
retaining `# noqa` directives that cover plugins not yet implemented
|
||||
by Ruff.
|
||||
@@ -1975,7 +1975,7 @@ fix-only = true
|
||||
|
||||
#### [`fixable`](#fixable)
|
||||
|
||||
A list of check code prefixes to consider autofix-able.
|
||||
A list of rule codes or prefixes to consider autofixable.
|
||||
|
||||
**Default value**: `["A", "ANN", "ARG", "B", "BLE", "C", "D", "E", "ERA", "F", "FBT", "I", "ICN", "N", "PGH", "PLC", "PLE", "PLR", "PLW", "Q", "RET", "RUF", "S", "T", "TID", "UP", "W", "YTT"]`
|
||||
|
||||
@@ -1985,7 +1985,7 @@ A list of check code prefixes to consider autofix-able.
|
||||
|
||||
```toml
|
||||
[tool.ruff]
|
||||
# Only allow autofix behavior for `E` and `F` checks.
|
||||
# Only allow autofix behavior for `E` and `F` rules.
|
||||
fixable = ["E", "F"]
|
||||
```
|
||||
|
||||
@@ -2041,11 +2041,11 @@ format = "grouped"
|
||||
|
||||
#### [`ignore`](#ignore)
|
||||
|
||||
A list of check code prefixes to ignore. Prefixes can specify exact
|
||||
checks (like `F841`), entire categories (like `F`), or anything in
|
||||
A list of rule codes or prefixes to ignore. Prefixes can specify exact
|
||||
rules (like `F841`), entire categories (like `F`), or anything in
|
||||
between.
|
||||
|
||||
When breaking ties between enabled and disabled checks (via `select` and
|
||||
When breaking ties between enabled and disabled rules (via `select` and
|
||||
`ignore`, respectively), more specific prefixes override less
|
||||
specific prefixes.
|
||||
|
||||
@@ -2057,7 +2057,7 @@ specific prefixes.
|
||||
|
||||
```toml
|
||||
[tool.ruff]
|
||||
# Skip unused variable checks (`F841`).
|
||||
# Skip unused variable rules (`F841`).
|
||||
ignore = ["F841"]
|
||||
```
|
||||
|
||||
@@ -2105,8 +2105,8 @@ line-length = 120
|
||||
|
||||
#### [`per-file-ignores`](#per-file-ignores)
|
||||
|
||||
A list of mappings from file pattern to check code prefixes to exclude,
|
||||
when considering any matching files.
|
||||
A list of mappings from file pattern to rule codes or prefixes to
|
||||
exclude, when considering any matching files.
|
||||
|
||||
**Default value**: `{}`
|
||||
|
||||
@@ -2164,11 +2164,11 @@ respect_gitignore = false
|
||||
|
||||
#### [`select`](#select)
|
||||
|
||||
A list of check code prefixes to enable. Prefixes can specify exact
|
||||
checks (like `F841`), entire categories (like `F`), or anything in
|
||||
A list of rule codes or prefixes to enable. Prefixes can specify exact
|
||||
rules (like `F841`), entire categories (like `F`), or anything in
|
||||
between.
|
||||
|
||||
When breaking ties between enabled and disabled checks (via `select` and
|
||||
When breaking ties between enabled and disabled rules (via `select` and
|
||||
`ignore`, respectively), more specific prefixes override less
|
||||
specific prefixes.
|
||||
|
||||
@@ -2188,8 +2188,8 @@ select = ["E", "F", "B", "Q"]
|
||||
|
||||
#### [`show-source`](#show-source)
|
||||
|
||||
Whether to show source code snippets when reporting lint error
|
||||
violations (overridden by the `--show-source` command-line flag).
|
||||
Whether to show source code snippets when reporting lint violations
|
||||
(overridden by the `--show-source` command-line flag).
|
||||
|
||||
**Default value**: `false`
|
||||
|
||||
@@ -2272,7 +2272,7 @@ target-version = "py37"
|
||||
A list of task tags to recognize (e.g., "TODO", "FIXME", "XXX").
|
||||
|
||||
Comments starting with these tags will be ignored by commented-out code
|
||||
detection (`ERA`), and skipped by line-length checks (`E501`) if
|
||||
detection (`ERA`), and skipped by line-length rules (`E501`) if
|
||||
`ignore-overlong-task-comments` is set to `true`.
|
||||
|
||||
**Default value**: `["TODO", "FIXME", "XXX"]`
|
||||
@@ -2288,9 +2288,33 @@ task-tags = ["HACK"]
|
||||
|
||||
---
|
||||
|
||||
#### [`typing-modules`](#typing-modules)
|
||||
|
||||
A list of modules whose imports should be treated equivalently to
|
||||
members of the `typing` module.
|
||||
|
||||
This is useful for ensuring proper type annotation inference for
|
||||
projects that re-export `typing` and `typing_extensions` members
|
||||
from a compatibility module. If omitted, any members imported from
|
||||
modules apart from `typing` and `typing_extensions` will be treated
|
||||
as ordinary Python objects.
|
||||
|
||||
**Default value**: `[]`
|
||||
|
||||
**Type**: `Vec<String>`
|
||||
|
||||
**Example usage**:
|
||||
|
||||
```toml
|
||||
[tool.ruff]
|
||||
typing-modules = ["airflow.typing_compat"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### [`unfixable`](#unfixable)
|
||||
|
||||
A list of check code prefixes to consider un-autofix-able.
|
||||
A list of rule codes or prefixes to consider non-autofix-able.
|
||||
|
||||
**Default value**: `[]`
|
||||
|
||||
@@ -2364,7 +2388,7 @@ mypy-init-return = true
|
||||
|
||||
#### [`suppress-dummy-args`](#suppress-dummy-args)
|
||||
|
||||
Whether to suppress `ANN000`-level errors for arguments matching the
|
||||
Whether to suppress `ANN000`-level violations for arguments matching the
|
||||
"dummy" variable regex (like `_`).
|
||||
|
||||
**Default value**: `false`
|
||||
@@ -2382,8 +2406,8 @@ suppress-dummy-args = true
|
||||
|
||||
#### [`suppress-none-returning`](#suppress-none-returning)
|
||||
|
||||
Whether to suppress `ANN200`-level errors for functions that meet either
|
||||
of the following criteria:
|
||||
Whether to suppress `ANN200`-level violations for functions that meet
|
||||
either of the following criteria:
|
||||
|
||||
- Contain no `return` statement.
|
||||
- Explicit `return` statement(s) all return `None` (explicitly or
|
||||
@@ -2444,7 +2468,7 @@ extend-hardcoded-tmp-directory = ["/foo/bar"]
|
||||
#### [`extend-immutable-calls`](#extend-immutable-calls)
|
||||
|
||||
Additional callable functions to consider "immutable" when evaluating,
|
||||
e.g., `no-mutable-default-argument` checks (`B006`).
|
||||
e.g., the `no-mutable-default-argument` rule (`B006`).
|
||||
|
||||
**Default value**: `[]`
|
||||
|
||||
@@ -2531,9 +2555,9 @@ will be added to the `aliases` mapping.
|
||||
|
||||
Boolean flag specifying whether `@pytest.fixture()` without parameters
|
||||
should have parentheses. If the option is set to `true` (the
|
||||
default), `@pytest.fixture()` is valid and `@pytest.fixture` is an
|
||||
error. If set to `false`, `@pytest.fixture` is valid and
|
||||
`@pytest.fixture()` is an error.
|
||||
default), `@pytest.fixture()` is valid and `@pytest.fixture` is
|
||||
invalid. If set to `false`, `@pytest.fixture` is valid and
|
||||
`@pytest.fixture()` is invalid.
|
||||
|
||||
**Default value**: `true`
|
||||
|
||||
@@ -2552,9 +2576,9 @@ fixture-parentheses = true
|
||||
|
||||
Boolean flag specifying whether `@pytest.mark.foo()` without parameters
|
||||
should have parentheses. If the option is set to `true` (the
|
||||
default), `@pytest.mark.foo()` is valid and `@pytest.mark.foo` is an
|
||||
error. If set to `false`, `@pytest.fixture` is valid and
|
||||
`@pytest.mark.foo()` is an error.
|
||||
default), `@pytest.mark.foo()` is valid and `@pytest.mark.foo` is
|
||||
invalid. If set to `false`, `@pytest.fixture` is valid and
|
||||
`@pytest.mark.foo()` is invalid.
|
||||
|
||||
**Default value**: `true`
|
||||
|
||||
@@ -2776,7 +2800,7 @@ ban-relative-imports = "all"
|
||||
#### [`banned-api`](#banned-api)
|
||||
|
||||
Specific modules or module members that may not be imported or accessed.
|
||||
Note that this check is only meant to flag accidental uses,
|
||||
Note that this rule is only meant to flag accidental uses,
|
||||
and can be circumvented via `eval` or `importlib`.
|
||||
|
||||
**Default value**: `{}`
|
||||
@@ -3096,7 +3120,7 @@ staticmethod-decorators = ["staticmethod", "stcmthd"]
|
||||
|
||||
#### [`ignore-overlong-task-comments`](#ignore-overlong-task-comments)
|
||||
|
||||
Whether or not line-length checks (`E501`) should be triggered for
|
||||
Whether or not line-length violations (`E501`) should be triggered for
|
||||
comments starting with `task-tags` (by default: ["TODO", "FIXME",
|
||||
and "XXX"]).
|
||||
|
||||
|
||||
4
flake8_to_ruff/Cargo.lock
generated
4
flake8_to_ruff/Cargo.lock
generated
@@ -771,7 +771,7 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
|
||||
|
||||
[[package]]
|
||||
name = "flake8_to_ruff"
|
||||
version = "0.0.216"
|
||||
version = "0.0.217"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -1975,7 +1975,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ruff"
|
||||
version = "0.0.216"
|
||||
version = "0.0.217"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bincode",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "flake8-to-ruff"
|
||||
version = "0.0.216-dev.0"
|
||||
version = "0.0.217-dev.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
|
||||
@@ -84,7 +84,7 @@ flake8-to-ruff path/to/.flake8 --plugin flake8-builtins --plugin flake8-quotes
|
||||
1. Ruff only supports a subset of the Flake configuration options. `flake8-to-ruff` will warn on and
|
||||
ignore unsupported options in the `.flake8` file (or equivalent). (Similarly, Ruff has a few
|
||||
configuration options that don't exist in Flake8.)
|
||||
2. Ruff will omit any error codes that are unimplemented or unsupported by Ruff, including error
|
||||
2. Ruff will omit any rule codes that are unimplemented or unsupported by Ruff, including rule
|
||||
codes from unsupported plugins. (See the [Ruff README](https://github.com/charliermarsh/ruff#user-content-how-does-ruff-compare-to-flake8)
|
||||
for the complete list of supported plugins.)
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ pub fn convert(
|
||||
.get("flake8")
|
||||
.expect("Unable to find flake8 section in INI file");
|
||||
|
||||
// Extract all referenced check code prefixes, to power plugin inference.
|
||||
// Extract all referenced rule code prefixes, to power plugin inference.
|
||||
let mut referenced_codes: BTreeSet<RuleCodePrefix> = BTreeSet::default();
|
||||
for (key, value) in flake8 {
|
||||
if let Some(value) = value {
|
||||
@@ -435,6 +435,7 @@ mod tests {
|
||||
src: None,
|
||||
target_version: None,
|
||||
unfixable: None,
|
||||
typing_modules: None,
|
||||
task_tags: None,
|
||||
update_check: None,
|
||||
flake8_annotations: None,
|
||||
@@ -499,6 +500,7 @@ mod tests {
|
||||
src: None,
|
||||
target_version: None,
|
||||
unfixable: None,
|
||||
typing_modules: None,
|
||||
task_tags: None,
|
||||
update_check: None,
|
||||
flake8_annotations: None,
|
||||
@@ -563,6 +565,7 @@ mod tests {
|
||||
src: None,
|
||||
target_version: None,
|
||||
unfixable: None,
|
||||
typing_modules: None,
|
||||
task_tags: None,
|
||||
update_check: None,
|
||||
flake8_annotations: None,
|
||||
@@ -627,6 +630,7 @@ mod tests {
|
||||
src: None,
|
||||
target_version: None,
|
||||
unfixable: None,
|
||||
typing_modules: None,
|
||||
task_tags: None,
|
||||
update_check: None,
|
||||
flake8_annotations: None,
|
||||
@@ -691,6 +695,7 @@ mod tests {
|
||||
src: None,
|
||||
target_version: None,
|
||||
unfixable: None,
|
||||
typing_modules: None,
|
||||
task_tags: None,
|
||||
update_check: None,
|
||||
flake8_annotations: None,
|
||||
@@ -764,6 +769,7 @@ mod tests {
|
||||
src: None,
|
||||
target_version: None,
|
||||
unfixable: None,
|
||||
typing_modules: None,
|
||||
task_tags: None,
|
||||
update_check: None,
|
||||
flake8_annotations: None,
|
||||
@@ -831,6 +837,7 @@ mod tests {
|
||||
src: None,
|
||||
target_version: None,
|
||||
unfixable: None,
|
||||
typing_modules: None,
|
||||
task_tags: None,
|
||||
update_check: None,
|
||||
flake8_annotations: None,
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { DEFAULT_PYTHON_SOURCE } from "../constants";
|
||||
import init, { check, Check, currentVersion, defaultSettings } from "../pkg";
|
||||
import init, {
|
||||
check,
|
||||
Diagnostic,
|
||||
currentVersion,
|
||||
defaultSettings,
|
||||
} from "../pkg";
|
||||
import { ErrorMessage } from "./ErrorMessage";
|
||||
import Header from "./Header";
|
||||
import { useTheme } from "./theme";
|
||||
@@ -18,7 +23,7 @@ export default function Editor() {
|
||||
const [edit, setEdit] = useState<number>(0);
|
||||
const [settingsSource, setSettingsSource] = useState<string | null>(null);
|
||||
const [pythonSource, setPythonSource] = useState<string | null>(null);
|
||||
const [checks, setChecks] = useState<Check[]>([]);
|
||||
const [diagnostics, setDiagnostics] = useState<Diagnostic[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [theme, setTheme] = useTheme();
|
||||
|
||||
@@ -32,25 +37,25 @@ export default function Editor() {
|
||||
}
|
||||
|
||||
let config: any;
|
||||
let checks: Check[];
|
||||
let diagnostics: Diagnostic[];
|
||||
|
||||
try {
|
||||
config = JSON.parse(settingsSource);
|
||||
} catch (e) {
|
||||
setChecks([]);
|
||||
setDiagnostics([]);
|
||||
setError((e as Error).message);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
checks = check(pythonSource, config);
|
||||
diagnostics = check(pythonSource, config);
|
||||
} catch (e) {
|
||||
setError(e as string);
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
setChecks(checks);
|
||||
setDiagnostics(diagnostics);
|
||||
}, [initialized, settingsSource, pythonSource]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -122,7 +127,7 @@ export default function Editor() {
|
||||
visible={tab === "Source"}
|
||||
source={pythonSource}
|
||||
theme={theme}
|
||||
checks={checks}
|
||||
diagnostics={diagnostics}
|
||||
onChange={handlePythonSourceChange}
|
||||
/>
|
||||
<SettingsEditor
|
||||
|
||||
@@ -5,19 +5,19 @@
|
||||
import Editor, { useMonaco } from "@monaco-editor/react";
|
||||
import { MarkerSeverity, MarkerTag } from "monaco-editor";
|
||||
import { useCallback, useEffect } from "react";
|
||||
import { Check } from "../pkg";
|
||||
import { Diagnostic } from "../pkg";
|
||||
import { Theme } from "./theme";
|
||||
|
||||
export default function SourceEditor({
|
||||
visible,
|
||||
source,
|
||||
theme,
|
||||
checks,
|
||||
diagnostics,
|
||||
onChange,
|
||||
}: {
|
||||
visible: boolean;
|
||||
source: string;
|
||||
checks: Check[];
|
||||
diagnostics: Diagnostic[];
|
||||
theme: Theme;
|
||||
onChange: (pythonSource: string) => void;
|
||||
}) {
|
||||
@@ -33,15 +33,15 @@ export default function SourceEditor({
|
||||
editor.setModelMarkers(
|
||||
model,
|
||||
"owner",
|
||||
checks.map((check) => ({
|
||||
startLineNumber: check.location.row,
|
||||
startColumn: check.location.column + 1,
|
||||
endLineNumber: check.end_location.row,
|
||||
endColumn: check.end_location.column + 1,
|
||||
message: `${check.code}: ${check.message}`,
|
||||
diagnostics.map((diagnostic) => ({
|
||||
startLineNumber: diagnostic.location.row,
|
||||
startColumn: diagnostic.location.column + 1,
|
||||
endLineNumber: diagnostic.end_location.row,
|
||||
endColumn: diagnostic.end_location.column + 1,
|
||||
message: `${diagnostic.code}: ${diagnostic.message}`,
|
||||
severity: MarkerSeverity.Error,
|
||||
tags:
|
||||
check.code === "F401" || check.code === "F841"
|
||||
diagnostic.code === "F401" || diagnostic.code === "F841"
|
||||
? [MarkerTag.Unnecessary]
|
||||
: [],
|
||||
})),
|
||||
@@ -52,7 +52,7 @@ export default function SourceEditor({
|
||||
{
|
||||
// @ts-expect-error: The type definition is wrong.
|
||||
provideCodeActions: function (model, position) {
|
||||
const actions = checks
|
||||
const actions = diagnostics
|
||||
.filter((check) => position.startLineNumber === check.location.row)
|
||||
.filter((check) => check.fix)
|
||||
.map((check) => ({
|
||||
@@ -89,7 +89,7 @@ export default function SourceEditor({
|
||||
return () => {
|
||||
codeActionProvider?.dispose();
|
||||
};
|
||||
}, [checks, monaco]);
|
||||
}, [diagnostics, monaco]);
|
||||
|
||||
const handleChange = useCallback(
|
||||
(value: string | undefined) => {
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "maturin"
|
||||
|
||||
[project]
|
||||
name = "ruff"
|
||||
version = "0.0.216"
|
||||
version = "0.0.217"
|
||||
description = "An extremely fast Python linter, written in Rust."
|
||||
authors = [
|
||||
{ name = "Charlie Marsh", email = "charlie.r.marsh@gmail.com" },
|
||||
|
||||
@@ -29,3 +29,20 @@ else:
|
||||
b = 1
|
||||
else:
|
||||
b = 2
|
||||
|
||||
import sys
|
||||
|
||||
if sys.version_info >= (3, 9):
|
||||
randbytes = random.randbytes
|
||||
else:
|
||||
randbytes = _get_random_bytes
|
||||
|
||||
if sys.platform == "darwin":
|
||||
randbytes = random.randbytes
|
||||
else:
|
||||
randbytes = _get_random_bytes
|
||||
|
||||
if sys.platform.startswith("linux"):
|
||||
randbytes = random.randbytes
|
||||
else:
|
||||
randbytes = _get_random_bytes
|
||||
|
||||
7
resources/test/fixtures/pyflakes/typing_modules.py
vendored
Normal file
7
resources/test/fixtures/pyflakes/typing_modules.py
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
from typing import Union
|
||||
|
||||
from airflow.typing_compat import Literal, Optional
|
||||
|
||||
|
||||
X = Union[Literal[False], Literal["db"]]
|
||||
y = Optional["Class"]
|
||||
@@ -33,7 +33,7 @@
|
||||
]
|
||||
},
|
||||
"dummy-variable-rgx": {
|
||||
"description": "A regular expression used to identify \"dummy\" variables, or those which should be ignored when evaluating (e.g.) unused-variable checks. The default expression matches `_`, `__`, and `_var`, but not `_var_`.",
|
||||
"description": "A regular expression used to identify \"dummy\" variables, or those which should be ignored when enforcing (e.g.) unused-variable rules. The default expression matches `_`, `__`, and `_var`, but not `_var_`.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
@@ -67,7 +67,7 @@
|
||||
}
|
||||
},
|
||||
"extend-ignore": {
|
||||
"description": "A list of check code prefixes to ignore, in addition to those specified by `ignore`.",
|
||||
"description": "A list of rule codes or prefixes to ignore, in addition to those specified by `ignore`.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
@@ -77,7 +77,7 @@
|
||||
}
|
||||
},
|
||||
"extend-select": {
|
||||
"description": "A list of check code prefixes to enable, in addition to those specified by `select`.",
|
||||
"description": "A list of rule codes or prefixes to enable, in addition to those specified by `select`.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
@@ -87,7 +87,7 @@
|
||||
}
|
||||
},
|
||||
"external": {
|
||||
"description": "A list of check codes that are unsupported by Ruff, but should be preserved when (e.g.) validating `# noqa` directives. Useful for retaining `# noqa` directives that cover plugins not yet implemented by Ruff.",
|
||||
"description": "A list of rule codes that are unsupported by Ruff, but should be preserved when (e.g.) validating `# noqa` directives. Useful for retaining `# noqa` directives that cover plugins not yet implemented by Ruff.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
@@ -111,7 +111,7 @@
|
||||
]
|
||||
},
|
||||
"fixable": {
|
||||
"description": "A list of check code prefixes to consider autofix-able.",
|
||||
"description": "A list of rule codes or prefixes to consider autofixable.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
@@ -238,7 +238,7 @@
|
||||
]
|
||||
},
|
||||
"ignore": {
|
||||
"description": "A list of check code prefixes to ignore. Prefixes can specify exact checks (like `F841`), entire categories (like `F`), or anything in between.\n\nWhen breaking ties between enabled and disabled checks (via `select` and `ignore`, respectively), more specific prefixes override less specific prefixes.",
|
||||
"description": "A list of rule codes or prefixes to ignore. Prefixes can specify exact rules (like `F841`), entire categories (like `F`), or anything in between.\n\nWhen breaking ties between enabled and disabled rules (via `select` and `ignore`, respectively), more specific prefixes override less specific prefixes.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
@@ -297,7 +297,7 @@
|
||||
]
|
||||
},
|
||||
"per-file-ignores": {
|
||||
"description": "A list of mappings from file pattern to check code prefixes to exclude, when considering any matching files.",
|
||||
"description": "A list of mappings from file pattern to rule codes or prefixes to exclude, when considering any matching files.",
|
||||
"type": [
|
||||
"object",
|
||||
"null"
|
||||
@@ -361,7 +361,7 @@
|
||||
]
|
||||
},
|
||||
"select": {
|
||||
"description": "A list of check code prefixes to enable. Prefixes can specify exact checks (like `F841`), entire categories (like `F`), or anything in between.\n\nWhen breaking ties between enabled and disabled checks (via `select` and `ignore`, respectively), more specific prefixes override less specific prefixes.",
|
||||
"description": "A list of rule codes or prefixes to enable. Prefixes can specify exact rules (like `F841`), entire categories (like `F`), or anything in between.\n\nWhen breaking ties between enabled and disabled rules (via `select` and `ignore`, respectively), more specific prefixes override less specific prefixes.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
@@ -371,7 +371,7 @@
|
||||
}
|
||||
},
|
||||
"show-source": {
|
||||
"description": "Whether to show source code snippets when reporting lint error violations (overridden by the `--show-source` command-line flag).",
|
||||
"description": "Whether to show source code snippets when reporting lint violations (overridden by the `--show-source` command-line flag).",
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
@@ -399,7 +399,17 @@
|
||||
]
|
||||
},
|
||||
"task-tags": {
|
||||
"description": "A list of task tags to recognize (e.g., \"TODO\", \"FIXME\", \"XXX\").\n\nComments starting with these tags will be ignored by commented-out code detection (`ERA`), and skipped by line-length checks (`E501`) if `ignore-overlong-task-comments` is set to `true`.",
|
||||
"description": "A list of task tags to recognize (e.g., \"TODO\", \"FIXME\", \"XXX\").\n\nComments starting with these tags will be ignored by commented-out code detection (`ERA`), and skipped by line-length rules (`E501`) if `ignore-overlong-task-comments` is set to `true`.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"typing-modules": {
|
||||
"description": "A list of modules whose imports should be treated equivalently to members of the `typing` module.\n\nThis is useful for ensuring proper type annotation inference for projects that re-export `typing` and `typing_extensions` members from a compatibility module. If omitted, any members imported from modules apart from `typing` and `typing_extensions` will be treated as ordinary Python objects.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
@@ -409,7 +419,7 @@
|
||||
}
|
||||
},
|
||||
"unfixable": {
|
||||
"description": "A list of check code prefixes to consider un-autofix-able.",
|
||||
"description": "A list of rule codes or prefixes to consider non-autofix-able.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
@@ -484,14 +494,14 @@
|
||||
]
|
||||
},
|
||||
"suppress-dummy-args": {
|
||||
"description": "Whether to suppress `ANN000`-level errors for arguments matching the \"dummy\" variable regex (like `_`).",
|
||||
"description": "Whether to suppress `ANN000`-level violations for arguments matching the \"dummy\" variable regex (like `_`).",
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"suppress-none-returning": {
|
||||
"description": "Whether to suppress `ANN200`-level errors for functions that meet either of the following criteria:\n\n- Contain no `return` statement. - Explicit `return` statement(s) all return `None` (explicitly or implicitly).",
|
||||
"description": "Whether to suppress `ANN200`-level violations for functions that meet either of the following criteria:\n\n- Contain no `return` statement. - Explicit `return` statement(s) all return `None` (explicitly or implicitly).",
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
@@ -530,7 +540,7 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"extend-immutable-calls": {
|
||||
"description": "Additional callable functions to consider \"immutable\" when evaluating, e.g., `no-mutable-default-argument` checks (`B006`).",
|
||||
"description": "Additional callable functions to consider \"immutable\" when evaluating, e.g., the `no-mutable-default-argument` rule (`B006`).",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
@@ -587,14 +597,14 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"fixture-parentheses": {
|
||||
"description": "Boolean flag specifying whether `@pytest.fixture()` without parameters should have parentheses. If the option is set to `true` (the default), `@pytest.fixture()` is valid and `@pytest.fixture` is an error. If set to `false`, `@pytest.fixture` is valid and `@pytest.fixture()` is an error.",
|
||||
"description": "Boolean flag specifying whether `@pytest.fixture()` without parameters should have parentheses. If the option is set to `true` (the default), `@pytest.fixture()` is valid and `@pytest.fixture` is invalid. If set to `false`, `@pytest.fixture` is valid and `@pytest.fixture()` is invalid.",
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"mark-parentheses": {
|
||||
"description": "Boolean flag specifying whether `@pytest.mark.foo()` without parameters should have parentheses. If the option is set to `true` (the default), `@pytest.mark.foo()` is valid and `@pytest.mark.foo` is an error. If set to `false`, `@pytest.fixture` is valid and `@pytest.mark.foo()` is an error.",
|
||||
"description": "Boolean flag specifying whether `@pytest.mark.foo()` without parameters should have parentheses. If the option is set to `true` (the default), `@pytest.mark.foo()` is valid and `@pytest.mark.foo` is invalid. If set to `false`, `@pytest.fixture` is valid and `@pytest.mark.foo()` is invalid.",
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
@@ -717,7 +727,7 @@
|
||||
]
|
||||
},
|
||||
"banned-api": {
|
||||
"description": "Specific modules or module members that may not be imported or accessed. Note that this check is only meant to flag accidental uses, and can be circumvented via `eval` or `importlib`.",
|
||||
"description": "Specific modules or module members that may not be imported or accessed. Note that this rule is only meant to flag accidental uses, and can be circumvented via `eval` or `importlib`.",
|
||||
"type": [
|
||||
"object",
|
||||
"null"
|
||||
@@ -920,7 +930,7 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ignore-overlong-task-comments": {
|
||||
"description": "Whether or not line-length checks (`E501`) should be triggered for comments starting with `task-tags` (by default: [\"TODO\", \"FIXME\", and \"XXX\"]).",
|
||||
"description": "Whether or not line-length violations (`E501`) should be triggered for comments starting with `task-tags` (by default: [\"TODO\", \"FIXME\", and \"XXX\"]).",
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ruff_dev"
|
||||
version = "0.0.216"
|
||||
version = "0.0.217"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ruff_macros"
|
||||
version = "0.0.216"
|
||||
version = "0.0.217"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate boilerplate for a new check.
|
||||
|
||||
Example usage:
|
||||
|
||||
python scripts/add_check.py \
|
||||
--name PreferListBuiltin \
|
||||
--code PIE807 \
|
||||
--plugin flake8-pie
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
|
||||
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
def dir_name(plugin: str) -> str:
|
||||
return plugin.replace("-", "_")
|
||||
|
||||
|
||||
def pascal_case(plugin: str) -> str:
|
||||
"""Convert from snake-case to PascalCase."""
|
||||
return "".join(word.title() for word in plugin.split("-"))
|
||||
|
||||
|
||||
def snake_case(name: str) -> str:
|
||||
"""Convert from PascalCase to snake_case."""
|
||||
return "".join(f"_{word.lower()}" if word.isupper() else word for word in name).lstrip("_")
|
||||
|
||||
|
||||
def main(*, name: str, code: str, plugin: str) -> None:
|
||||
# Create a test fixture.
|
||||
with open(
|
||||
os.path.join(ROOT_DIR, f"resources/test/fixtures/{dir_name(plugin)}/{code}.py"),
|
||||
"a",
|
||||
):
|
||||
pass
|
||||
|
||||
# Add the relevant `#testcase` macro.
|
||||
with open(os.path.join(ROOT_DIR, f"src/{dir_name(plugin)}/mod.rs"), "r") as fp:
|
||||
content = fp.read()
|
||||
|
||||
with open(os.path.join(ROOT_DIR, f"src/{dir_name(plugin)}/mod.rs"), "w") as fp:
|
||||
for line in content.splitlines():
|
||||
if line.strip() == "fn rules(check_code: RuleCode, path: &Path) -> Result<()> {":
|
||||
indent = line.split("fn rules(check_code: RuleCode, path: &Path) -> Result<()> {")[0]
|
||||
fp.write(f'{indent}#[test_case(RuleCode::{code}, Path::new("{code}.py"); "{code}")]')
|
||||
fp.write("\n")
|
||||
|
||||
fp.write(line)
|
||||
fp.write("\n")
|
||||
|
||||
# Add the relevant plugin function.
|
||||
with open(os.path.join(ROOT_DIR, f"src/{dir_name(plugin)}/plugins.rs"), "a") as fp:
|
||||
fp.write(
|
||||
f"""
|
||||
/// {code}
|
||||
pub fn {snake_case(name)}(checker: &mut Checker) {{}}
|
||||
"""
|
||||
)
|
||||
fp.write("\n")
|
||||
|
||||
# Add the relevant sections to `src/registry.rs`.
|
||||
with open(os.path.join(ROOT_DIR, "src/registry.rs"), "r") as fp:
|
||||
content = fp.read()
|
||||
|
||||
index = 0
|
||||
with open(os.path.join(ROOT_DIR, "src/registry.rs"), "w") as fp:
|
||||
for line in content.splitlines():
|
||||
fp.write(line)
|
||||
fp.write("\n")
|
||||
|
||||
if line.strip() == f"// {plugin}":
|
||||
if index == 0:
|
||||
# `RuleCode` definition
|
||||
indent = line.split(f"// {plugin}")[0]
|
||||
fp.write(f"{indent}{code},")
|
||||
fp.write("\n")
|
||||
|
||||
elif index == 1:
|
||||
# `DiagnosticKind` definition
|
||||
indent = line.split(f"// {plugin}")[0]
|
||||
fp.write(f"{indent}{name},")
|
||||
fp.write("\n")
|
||||
|
||||
elif index == 2:
|
||||
# `RuleCode#kind()`
|
||||
indent = line.split(f"// {plugin}")[0]
|
||||
fp.write(f"{indent}RuleCode::{code} => DiagnosticKind::{name},")
|
||||
fp.write("\n")
|
||||
|
||||
elif index == 3:
|
||||
# `RuleCode#category()`
|
||||
indent = line.split(f"// {plugin}")[0]
|
||||
fp.write(f"{indent}RuleCode::{code} => CheckCategory::{pascal_case(plugin)},")
|
||||
fp.write("\n")
|
||||
|
||||
elif index == 4:
|
||||
# `DiagnosticKind#code()`
|
||||
indent = line.split(f"// {plugin}")[0]
|
||||
fp.write(f"{indent}DiagnosticKind::{name} => &RuleCode::{code},")
|
||||
fp.write("\n")
|
||||
|
||||
elif index == 5:
|
||||
# `RuleCode#body`
|
||||
indent = line.split(f"// {plugin}")[0]
|
||||
fp.write(f'{indent}DiagnosticKind::{name} => todo!("Write message body for {code}"),')
|
||||
fp.write("\n")
|
||||
|
||||
index += 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Generate boilerplate for a new check.",
|
||||
epilog="python scripts/add_check.py --name PreferListBuiltin --code PIE807 --plugin flake8-pie",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--name",
|
||||
type=str,
|
||||
required=True,
|
||||
help="The name of the check to generate, in PascalCase (e.g., 'LineTooLong').",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--code",
|
||||
type=str,
|
||||
required=True,
|
||||
help="The code of the check to generate (e.g., 'A001').",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--plugin",
|
||||
type=str,
|
||||
required=True,
|
||||
help="The plugin with which the check is associated (e.g., 'flake8-builtins').",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
main(name=args.name, code=args.code, plugin=args.plugin)
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate boilerplate for a new plugin.
|
||||
"""Generate boilerplate for a new Flake8 plugin.
|
||||
|
||||
Example usage:
|
||||
|
||||
@@ -31,9 +31,9 @@ def main(*, plugin: str, url: str) -> None:
|
||||
|
||||
# Create the Rust module.
|
||||
os.makedirs(os.path.join(ROOT_DIR, f"src/{dir_name(plugin)}"), exist_ok=True)
|
||||
with open(os.path.join(ROOT_DIR, f"src/{dir_name(plugin)}/rules"), "a"):
|
||||
pass
|
||||
with open(os.path.join(ROOT_DIR, f"src/{dir_name(plugin)}/rules"), "w+") as fp:
|
||||
with open(os.path.join(ROOT_DIR, f"src/{dir_name(plugin)}/rules.rs"), "w+") as fp:
|
||||
fp.write("use crate::checkers::ast::Checker;\n")
|
||||
with open(os.path.join(ROOT_DIR, f"src/{dir_name(plugin)}/mod.rs"), "w+") as fp:
|
||||
fp.write("pub mod rules;\n")
|
||||
fp.write("\n")
|
||||
fp.write(
|
||||
@@ -49,13 +49,13 @@ mod tests {
|
||||
use crate::linter::test_path;
|
||||
use crate::settings;
|
||||
|
||||
fn rules(check_code: RuleCode, path: &Path) -> Result<()> {
|
||||
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy());
|
||||
fn rules(rule_code: RuleCode, path: &Path) -> Result<()> {
|
||||
let snapshot = format!("{}_{}", rule_code.as_ref(), path.to_string_lossy());
|
||||
let diagnostics =test_path(
|
||||
Path::new("./resources/test/fixtures/%s")
|
||||
.join(path)
|
||||
.as_path(),
|
||||
&settings::Settings::for_rule(check_code),
|
||||
&settings::Settings::for_rule(rule_code),
|
||||
)?;
|
||||
insta::assert_yaml_snapshot!(snapshot, diagnostics);
|
||||
Ok(())
|
||||
@@ -67,10 +67,10 @@ mod tests {
|
||||
|
||||
# Add the plugin to `lib.rs`.
|
||||
with open(os.path.join(ROOT_DIR, "src/lib.rs"), "a") as fp:
|
||||
fp.write(f"pub mod {dir_name(plugin)};")
|
||||
fp.write(f"mod {dir_name(plugin)};")
|
||||
|
||||
# Add the relevant sections to `src/registry.rs`.
|
||||
with open(os.path.join(ROOT_DIR, "src/registry.rs"), "r") as fp:
|
||||
with open(os.path.join(ROOT_DIR, "src/registry.rs")) as fp:
|
||||
content = fp.read()
|
||||
|
||||
with open(os.path.join(ROOT_DIR, "src/registry.rs"), "w") as fp:
|
||||
@@ -85,23 +85,37 @@ mod tests {
|
||||
fp.write(f"{indent}{pascal_case(plugin)},")
|
||||
fp.write("\n")
|
||||
|
||||
elif line.strip() == 'CheckCategory::Ruff => "Ruff-specific rules",':
|
||||
indent = line.split('CheckCategory::Ruff => "Ruff-specific rules",')[0]
|
||||
fp.write(f'{indent}CheckCategory::{pascal_case(plugin)} => "{plugin}",')
|
||||
elif line.strip() == 'RuleOrigin::Ruff => "Ruff-specific rules",':
|
||||
indent = line.split('RuleOrigin::Ruff => "Ruff-specific rules",')[0]
|
||||
fp.write(f'{indent}RuleOrigin::{pascal_case(plugin)} => "{plugin}",')
|
||||
fp.write("\n")
|
||||
|
||||
elif line.strip() == "CheckCategory::Ruff => vec![RuleCodePrefix::RUF],":
|
||||
indent = line.split("CheckCategory::Ruff => vec![RuleCodePrefix::RUF],")[0]
|
||||
elif line.strip() == "RuleOrigin::Ruff => vec![RuleCodePrefix::RUF],":
|
||||
indent = line.split("RuleOrigin::Ruff => vec![RuleCodePrefix::RUF],")[0]
|
||||
fp.write(
|
||||
f"{indent}CheckCategory::{pascal_case(plugin)} => vec![\n"
|
||||
f"{indent}RuleOrigin::{pascal_case(plugin)} => vec![\n"
|
||||
f'{indent} todo!("Fill-in prefix after generating codes")\n'
|
||||
f"{indent}],"
|
||||
)
|
||||
fp.write("\n")
|
||||
|
||||
elif line.strip() == "CheckCategory::Ruff => None,":
|
||||
indent = line.split("CheckCategory::Ruff => None,")[0]
|
||||
fp.write(f"{indent}CheckCategory::{pascal_case(plugin)} => " f'Some(("{url}", &Platform::PyPI)),')
|
||||
elif line.strip() == "RuleOrigin::Ruff => None,":
|
||||
indent = line.split("RuleOrigin::Ruff => None,")[0]
|
||||
fp.write(f"{indent}RuleOrigin::{pascal_case(plugin)} => " f'Some(("{url}", &Platform::PyPI)),')
|
||||
fp.write("\n")
|
||||
|
||||
fp.write(line)
|
||||
fp.write("\n")
|
||||
|
||||
# Add the relevant section to `src/violations.rs`.
|
||||
with open(os.path.join(ROOT_DIR, "src/violations.rs")) as fp:
|
||||
content = fp.read()
|
||||
|
||||
with open(os.path.join(ROOT_DIR, "src/violations.rs"), "w") as fp:
|
||||
for line in content.splitlines():
|
||||
if line.strip() == "// Ruff":
|
||||
indent = line.split("// Ruff")[0]
|
||||
fp.write(f"{indent}// {plugin}")
|
||||
fp.write("\n")
|
||||
|
||||
fp.write(line)
|
||||
@@ -110,7 +124,7 @@ mod tests {
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Generate boilerplate for a new plugin.",
|
||||
description="Generate boilerplate for a new Flake8 plugin.",
|
||||
epilog=(
|
||||
"Example usage: python scripts/add_plugin.py flake8-pie "
|
||||
"--url https://pypi.org/project/flake8-pie/0.16.0/"
|
||||
@@ -118,7 +132,6 @@ if __name__ == "__main__":
|
||||
)
|
||||
parser.add_argument(
|
||||
"plugin",
|
||||
required=True,
|
||||
type=str,
|
||||
help="The name of the plugin to generate.",
|
||||
)
|
||||
|
||||
172
scripts/add_rule.py
Normal file
172
scripts/add_rule.py
Normal file
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate boilerplate for a new rule.
|
||||
|
||||
Example usage:
|
||||
|
||||
python scripts/add_rule.py \
|
||||
--name PreferListBuiltin \
|
||||
--code PIE807 \
|
||||
--origin flake8-pie
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
|
||||
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
def dir_name(origin: str) -> str:
|
||||
return origin.replace("-", "_")
|
||||
|
||||
|
||||
def pascal_case(origin: str) -> str:
|
||||
"""Convert from snake-case to PascalCase."""
|
||||
return "".join(word.title() for word in origin.split("-"))
|
||||
|
||||
|
||||
def snake_case(name: str) -> str:
|
||||
"""Convert from PascalCase to snake_case."""
|
||||
return "".join(f"_{word.lower()}" if word.isupper() else word for word in name).lstrip("_")
|
||||
|
||||
|
||||
def main(*, name: str, code: str, origin: str) -> None:
|
||||
# Create a test fixture.
|
||||
with open(
|
||||
os.path.join(ROOT_DIR, f"resources/test/fixtures/{dir_name(origin)}/{code}.py"),
|
||||
"a",
|
||||
):
|
||||
pass
|
||||
|
||||
# Add the relevant `#testcase` macro.
|
||||
with open(os.path.join(ROOT_DIR, f"src/{dir_name(origin)}/mod.rs")) as fp:
|
||||
content = fp.read()
|
||||
|
||||
with open(os.path.join(ROOT_DIR, f"src/{dir_name(origin)}/mod.rs"), "w") as fp:
|
||||
for line in content.splitlines():
|
||||
if line.strip() == "fn rules(rule_code: RuleCode, path: &Path) -> Result<()> {":
|
||||
indent = line.split("fn rules(rule_code: RuleCode, path: &Path) -> Result<()> {")[0]
|
||||
fp.write(f'{indent}#[test_case(RuleCode::{code}, Path::new("{code}.py"); "{code}")]')
|
||||
fp.write("\n")
|
||||
|
||||
fp.write(line)
|
||||
fp.write("\n")
|
||||
|
||||
# Add the relevant rule function.
|
||||
with open(os.path.join(ROOT_DIR, f"src/{dir_name(origin)}/rules.rs"), "a") as fp:
|
||||
fp.write(
|
||||
f"""
|
||||
/// {code}
|
||||
pub fn {snake_case(name)}(checker: &mut Checker) {{}}
|
||||
"""
|
||||
)
|
||||
fp.write("\n")
|
||||
|
||||
# Add the relevant struct to `src/violations.rs`.
|
||||
with open(os.path.join(ROOT_DIR, "src/violations.rs")) as fp:
|
||||
content = fp.read()
|
||||
|
||||
with open(os.path.join(ROOT_DIR, "src/violations.rs"), "w") as fp:
|
||||
for line in content.splitlines():
|
||||
fp.write(line)
|
||||
fp.write("\n")
|
||||
|
||||
if line.startswith(f"// {origin}"):
|
||||
fp.write(
|
||||
"""define_violation!(
|
||||
pub struct %s;
|
||||
);
|
||||
impl Violation for %s {
|
||||
fn message(&self) -> String {
|
||||
todo!("Implement message")
|
||||
}
|
||||
|
||||
fn placeholder() -> Self {
|
||||
%s
|
||||
}
|
||||
}
|
||||
"""
|
||||
% (name, name, name)
|
||||
)
|
||||
fp.write("\n")
|
||||
|
||||
# Add the relevant code-to-violation pair to `src/registry.rs`.
|
||||
with open(os.path.join(ROOT_DIR, "src/registry.rs")) as fp:
|
||||
content = fp.read()
|
||||
|
||||
seen_macro = False
|
||||
has_written = False
|
||||
with open(os.path.join(ROOT_DIR, "src/registry.rs"), "w") as fp:
|
||||
for line in content.splitlines():
|
||||
fp.write(line)
|
||||
fp.write("\n")
|
||||
|
||||
if has_written:
|
||||
continue
|
||||
|
||||
if line.startswith("define_rule_mapping!"):
|
||||
seen_macro = True
|
||||
continue
|
||||
|
||||
if not seen_macro:
|
||||
continue
|
||||
|
||||
if line.strip() == f"// {origin}":
|
||||
indent = line.split("//")[0]
|
||||
fp.write(f"{indent}{code} => violations::{name},")
|
||||
fp.write("\n")
|
||||
has_written = True
|
||||
|
||||
# Add the relevant code-to-origin pair to `src/registry.rs`.
|
||||
with open(os.path.join(ROOT_DIR, "src/registry.rs")) as fp:
|
||||
content = fp.read()
|
||||
|
||||
seen_impl = False
|
||||
has_written = False
|
||||
with open(os.path.join(ROOT_DIR, "src/registry.rs"), "w") as fp:
|
||||
for line in content.splitlines():
|
||||
fp.write(line)
|
||||
fp.write("\n")
|
||||
|
||||
if has_written:
|
||||
continue
|
||||
|
||||
if line.startswith("impl RuleCode"):
|
||||
seen_impl = True
|
||||
continue
|
||||
|
||||
if not seen_impl:
|
||||
continue
|
||||
|
||||
if line.strip() == f"// {origin}":
|
||||
indent = line.split("//")[0]
|
||||
fp.write(f"{indent}RuleCode::{code} => RuleOrigin::{pascal_case(origin)},")
|
||||
fp.write("\n")
|
||||
has_written = True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Generate boilerplate for a new rule.",
|
||||
epilog="python scripts/add_rule.py --name PreferListBuiltin --code PIE807 --origin flake8-pie",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--name",
|
||||
type=str,
|
||||
required=True,
|
||||
help="The name of the check to generate, in PascalCase (e.g., 'LineTooLong').",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--code",
|
||||
type=str,
|
||||
required=True,
|
||||
help="The code of the check to generate (e.g., 'A001').",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--origin",
|
||||
type=str,
|
||||
required=True,
|
||||
help="The source with which the check originated (e.g., 'flake8-builtins').",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
main(name=args.name, code=args.code, origin=args.origin)
|
||||
@@ -179,6 +179,131 @@ pub fn match_call_path(
|
||||
}
|
||||
}
|
||||
|
||||
/// Return `true` if the `Expr` contains a reference to `${module}.${target}`.
|
||||
pub fn contains_call_path(
|
||||
expr: &Expr,
|
||||
module: &str,
|
||||
member: &str,
|
||||
import_aliases: &FxHashMap<&str, &str>,
|
||||
from_imports: &FxHashMap<&str, FxHashSet<&str>>,
|
||||
) -> bool {
|
||||
any_over_expr(expr, &|expr| {
|
||||
let call_path = collect_call_paths(expr);
|
||||
if !call_path.is_empty() {
|
||||
if match_call_path(
|
||||
&dealias_call_path(call_path, import_aliases),
|
||||
module,
|
||||
member,
|
||||
from_imports,
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
})
|
||||
}
|
||||
|
||||
/// Call `func` over every `Expr` in `expr`, returning `true` if any expression
|
||||
/// returns `true`..
|
||||
pub fn any_over_expr<F>(expr: &Expr, func: &F) -> bool
|
||||
where
|
||||
F: Fn(&Expr) -> bool,
|
||||
{
|
||||
if func(expr) {
|
||||
return true;
|
||||
}
|
||||
match &expr.node {
|
||||
ExprKind::BoolOp { values, .. } | ExprKind::JoinedStr { values } => {
|
||||
values.iter().any(|expr| any_over_expr(expr, func))
|
||||
}
|
||||
ExprKind::NamedExpr { target, value } => {
|
||||
any_over_expr(target, func) || any_over_expr(value, func)
|
||||
}
|
||||
ExprKind::BinOp { left, right, .. } => {
|
||||
any_over_expr(left, func) || any_over_expr(right, func)
|
||||
}
|
||||
ExprKind::UnaryOp { operand, .. } => any_over_expr(operand, func),
|
||||
ExprKind::Lambda { body, .. } => any_over_expr(body, func),
|
||||
ExprKind::IfExp { test, body, orelse } => {
|
||||
any_over_expr(test, func) || any_over_expr(body, func) || any_over_expr(orelse, func)
|
||||
}
|
||||
ExprKind::Dict { keys, values } => values
|
||||
.iter()
|
||||
.chain(keys.iter())
|
||||
.any(|expr| any_over_expr(expr, func)),
|
||||
ExprKind::Set { elts } | ExprKind::List { elts, .. } | ExprKind::Tuple { elts, .. } => {
|
||||
elts.iter().any(|expr| any_over_expr(expr, func))
|
||||
}
|
||||
ExprKind::ListComp { elt, generators }
|
||||
| ExprKind::SetComp { elt, generators }
|
||||
| ExprKind::GeneratorExp { elt, generators } => {
|
||||
any_over_expr(elt, func)
|
||||
|| generators.iter().any(|generator| {
|
||||
any_over_expr(&generator.target, func)
|
||||
|| any_over_expr(&generator.iter, func)
|
||||
|| generator.ifs.iter().any(|expr| any_over_expr(expr, func))
|
||||
})
|
||||
}
|
||||
ExprKind::DictComp {
|
||||
key,
|
||||
value,
|
||||
generators,
|
||||
} => {
|
||||
any_over_expr(key, func)
|
||||
|| any_over_expr(value, func)
|
||||
|| generators.iter().any(|generator| {
|
||||
any_over_expr(&generator.target, func)
|
||||
|| any_over_expr(&generator.iter, func)
|
||||
|| generator.ifs.iter().any(|expr| any_over_expr(expr, func))
|
||||
})
|
||||
}
|
||||
ExprKind::Await { value }
|
||||
| ExprKind::YieldFrom { value }
|
||||
| ExprKind::Attribute { value, .. }
|
||||
| ExprKind::Starred { value, .. } => any_over_expr(value, func),
|
||||
ExprKind::Yield { value } => value
|
||||
.as_ref()
|
||||
.map_or(false, |value| any_over_expr(value, func)),
|
||||
ExprKind::Compare {
|
||||
left, comparators, ..
|
||||
} => any_over_expr(left, func) || comparators.iter().any(|expr| any_over_expr(expr, func)),
|
||||
ExprKind::Call {
|
||||
func: call_func,
|
||||
args,
|
||||
keywords,
|
||||
} => {
|
||||
any_over_expr(call_func, func)
|
||||
|| args.iter().any(|expr| any_over_expr(expr, func))
|
||||
|| keywords
|
||||
.iter()
|
||||
.any(|keyword| any_over_expr(&keyword.node.value, func))
|
||||
}
|
||||
ExprKind::FormattedValue {
|
||||
value, format_spec, ..
|
||||
} => {
|
||||
any_over_expr(value, func)
|
||||
|| format_spec
|
||||
.as_ref()
|
||||
.map_or(false, |value| any_over_expr(value, func))
|
||||
}
|
||||
ExprKind::Subscript { value, slice, .. } => {
|
||||
any_over_expr(value, func) || any_over_expr(slice, func)
|
||||
}
|
||||
ExprKind::Slice { lower, upper, step } => {
|
||||
lower
|
||||
.as_ref()
|
||||
.map_or(false, |value| any_over_expr(value, func))
|
||||
|| upper
|
||||
.as_ref()
|
||||
.map_or(false, |value| any_over_expr(value, func))
|
||||
|| step
|
||||
.as_ref()
|
||||
.map_or(false, |value| any_over_expr(value, func))
|
||||
}
|
||||
ExprKind::Name { .. } | ExprKind::Constant { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
static DUNDER_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"__[^\s]+__").unwrap());
|
||||
|
||||
/// Return `true` if the `Stmt` is an assignment to a dunder (like `__all__`).
|
||||
@@ -191,12 +316,12 @@ pub fn is_assignment_to_a_dunder(stmt: &Stmt) -> bool {
|
||||
return false;
|
||||
}
|
||||
match &targets[0].node {
|
||||
ExprKind::Name { id, ctx: _ } => DUNDER_REGEX.is_match(id),
|
||||
ExprKind::Name { id, .. } => DUNDER_REGEX.is_match(id),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
StmtKind::AnnAssign { target, .. } => match &target.node {
|
||||
ExprKind::Name { id, ctx: _ } => DUNDER_REGEX.is_match(id),
|
||||
ExprKind::Name { id, .. } => DUNDER_REGEX.is_match(id),
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
|
||||
@@ -4,6 +4,7 @@ use rustpython_parser::ast::{Constant, Expr, ExprKind, Stmt, StmtKind};
|
||||
use rustpython_parser::lexer;
|
||||
use rustpython_parser::lexer::Tok;
|
||||
|
||||
use crate::ast::helpers::any_over_expr;
|
||||
use crate::ast::types::{Binding, BindingKind, Scope};
|
||||
use crate::ast::visitor;
|
||||
use crate::ast::visitor::Visitor;
|
||||
@@ -129,76 +130,13 @@ pub fn in_nested_block<'a>(mut parents: impl Iterator<Item = &'a Stmt>) -> bool
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns `true` if `parent` contains `child`.
|
||||
fn contains(parent: &Expr, child: &Expr) -> bool {
|
||||
match &parent.node {
|
||||
ExprKind::BoolOp { values, .. } => values.iter().any(|parent| contains(parent, child)),
|
||||
ExprKind::NamedExpr { target, value } => contains(target, child) || contains(value, child),
|
||||
ExprKind::BinOp { left, right, .. } => contains(left, child) || contains(right, child),
|
||||
ExprKind::UnaryOp { operand, .. } => contains(operand, child),
|
||||
ExprKind::Lambda { body, .. } => contains(body, child),
|
||||
ExprKind::IfExp { test, body, orelse } => {
|
||||
contains(test, child) || contains(body, child) || contains(orelse, child)
|
||||
}
|
||||
ExprKind::Dict { keys, values } => keys
|
||||
.iter()
|
||||
.chain(values.iter())
|
||||
.any(|parent| contains(parent, child)),
|
||||
ExprKind::Set { elts } => elts.iter().any(|parent| contains(parent, child)),
|
||||
ExprKind::ListComp { elt, .. } => contains(elt, child),
|
||||
ExprKind::SetComp { elt, .. } => contains(elt, child),
|
||||
ExprKind::DictComp { key, value, .. } => contains(key, child) || contains(value, child),
|
||||
ExprKind::GeneratorExp { elt, .. } => contains(elt, child),
|
||||
ExprKind::Await { value } => contains(value, child),
|
||||
ExprKind::Yield { value } => value.as_ref().map_or(false, |value| contains(value, child)),
|
||||
ExprKind::YieldFrom { value } => contains(value, child),
|
||||
ExprKind::Compare {
|
||||
left, comparators, ..
|
||||
} => contains(left, child) || comparators.iter().any(|parent| contains(parent, child)),
|
||||
ExprKind::Call {
|
||||
func,
|
||||
args,
|
||||
keywords,
|
||||
} => {
|
||||
contains(func, child)
|
||||
|| args.iter().any(|parent| contains(parent, child))
|
||||
|| keywords
|
||||
.iter()
|
||||
.any(|keyword| contains(&keyword.node.value, child))
|
||||
}
|
||||
ExprKind::FormattedValue {
|
||||
value, format_spec, ..
|
||||
} => {
|
||||
contains(value, child)
|
||||
|| format_spec
|
||||
.as_ref()
|
||||
.map_or(false, |value| contains(value, child))
|
||||
}
|
||||
ExprKind::JoinedStr { values } => values.iter().any(|parent| contains(parent, child)),
|
||||
ExprKind::Constant { .. } => false,
|
||||
ExprKind::Attribute { value, .. } => contains(value, child),
|
||||
ExprKind::Subscript { value, slice, .. } => {
|
||||
contains(value, child) || contains(slice, child)
|
||||
}
|
||||
ExprKind::Starred { value, .. } => contains(value, child),
|
||||
ExprKind::Name { .. } => parent == child,
|
||||
ExprKind::List { elts, .. } => elts.iter().any(|parent| contains(parent, child)),
|
||||
ExprKind::Tuple { elts, .. } => elts.iter().any(|parent| contains(parent, child)),
|
||||
ExprKind::Slice { lower, upper, step } => {
|
||||
lower.as_ref().map_or(false, |value| contains(value, child))
|
||||
|| upper.as_ref().map_or(false, |value| contains(value, child))
|
||||
|| step.as_ref().map_or(false, |value| contains(value, child))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if a node represents an unpacking assignment.
|
||||
pub fn is_unpacking_assignment(parent: &Stmt, child: &Expr) -> bool {
|
||||
match &parent.node {
|
||||
StmtKind::With { items, .. } => items.iter().any(|item| {
|
||||
if let Some(optional_vars) = &item.optional_vars {
|
||||
if matches!(optional_vars.node, ExprKind::Tuple { .. }) {
|
||||
if contains(optional_vars, child) {
|
||||
if any_over_expr(optional_vars, &|expr| expr == child) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -227,7 +165,7 @@ pub fn is_unpacking_assignment(parent: &Stmt, child: &Expr) -> bool {
|
||||
matches!(
|
||||
item.node,
|
||||
ExprKind::Set { .. } | ExprKind::List { .. } | ExprKind::Tuple { .. }
|
||||
) && contains(item, child)
|
||||
) && any_over_expr(item, &|expr| expr == child)
|
||||
});
|
||||
|
||||
// If our child is a tuple, and value is not, it's always an unpacking
|
||||
|
||||
@@ -174,9 +174,26 @@ impl<'a> Checker<'a> {
|
||||
|
||||
/// Return `true` if the call path is a reference to `typing.${target}`.
|
||||
pub fn match_typing_call_path(&self, call_path: &[&str], target: &str) -> bool {
|
||||
match_call_path(call_path, "typing", target, &self.from_imports)
|
||||
|| (typing::in_extensions(target)
|
||||
&& match_call_path(call_path, "typing_extensions", target, &self.from_imports))
|
||||
if match_call_path(call_path, "typing", target, &self.from_imports) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if typing::TYPING_EXTENSIONS.contains(target) {
|
||||
if match_call_path(call_path, "typing_extensions", target, &self.from_imports) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if self
|
||||
.settings
|
||||
.typing_modules
|
||||
.iter()
|
||||
.any(|module| match_call_path(call_path, module, target, &self.from_imports))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
/// Return the current `Binding` for a given `name`.
|
||||
@@ -2954,6 +2971,7 @@ where
|
||||
value,
|
||||
&self.from_imports,
|
||||
&self.import_aliases,
|
||||
self.settings.typing_modules.iter().map(String::as_str),
|
||||
|member| self.is_builtin(member),
|
||||
) {
|
||||
Some(subscript) => {
|
||||
|
||||
@@ -47,7 +47,7 @@ pub fn check_noqa(
|
||||
continue;
|
||||
}
|
||||
|
||||
// Is the check ignored by a `noqa` directive on the parent line?
|
||||
// Is the violation ignored by a `noqa` directive on the parent line?
|
||||
if let Some(parent_lineno) = diagnostic.parent.map(|location| location.row()) {
|
||||
let noqa_lineno = noqa_line_for.get(&parent_lineno).unwrap_or(&parent_lineno);
|
||||
if commented_lines.contains(noqa_lineno) {
|
||||
|
||||
34
src/cli.rs
34
src/cli.rs
@@ -25,26 +25,26 @@ pub struct Cli {
|
||||
/// Enable verbose logging.
|
||||
#[arg(short, long, group = "verbosity")]
|
||||
pub verbose: bool,
|
||||
/// Only log errors.
|
||||
/// Print lint violations, but nothing else.
|
||||
#[arg(short, long, group = "verbosity")]
|
||||
pub quiet: bool,
|
||||
/// Disable all logging (but still exit with status code "1" upon detecting
|
||||
/// errors).
|
||||
/// lint violations).
|
||||
#[arg(short, long, group = "verbosity")]
|
||||
pub silent: bool,
|
||||
/// Exit with status code "0", even upon detecting errors.
|
||||
/// Exit with status code "0", even upon detecting lint violations.
|
||||
#[arg(short, long)]
|
||||
pub exit_zero: bool,
|
||||
/// Run in watch mode by re-running whenever files change.
|
||||
#[arg(short, long)]
|
||||
pub watch: bool,
|
||||
/// Attempt to automatically fix lint errors.
|
||||
/// Attempt to automatically fix lint violations.
|
||||
#[arg(long, overrides_with("no_fix"))]
|
||||
fix: bool,
|
||||
#[clap(long, overrides_with("fix"), hide = true)]
|
||||
no_fix: bool,
|
||||
/// Fix any fixable lint errors, but don't report on leftover violations.
|
||||
/// Implies `--fix`.
|
||||
/// Fix any fixable lint violations, but don't report on leftover
|
||||
/// violations. Implies `--fix`.
|
||||
#[arg(long, overrides_with("no_fix_only"))]
|
||||
fix_only: bool,
|
||||
#[clap(long, overrides_with("fix_only"), hide = true)]
|
||||
@@ -63,36 +63,36 @@ pub struct Cli {
|
||||
/// rules).
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
pub select: Option<Vec<RuleCodePrefix>>,
|
||||
/// Like --select, but adds additional error codes on top of the selected
|
||||
/// Like --select, but adds additional rule codes on top of the selected
|
||||
/// ones.
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
pub extend_select: Option<Vec<RuleCodePrefix>>,
|
||||
/// Comma-separated list of error codes to disable.
|
||||
/// Comma-separated list of rule codes to disable.
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
pub ignore: Option<Vec<RuleCodePrefix>>,
|
||||
/// Like --ignore, but adds additional error codes on top of the ignored
|
||||
/// Like --ignore, but adds additional rule codes on top of the ignored
|
||||
/// ones.
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
pub extend_ignore: Option<Vec<RuleCodePrefix>>,
|
||||
/// List of paths, used to exclude files and/or directories from checks.
|
||||
/// List of paths, used to omit files and/or directories from analysis.
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
pub exclude: Option<Vec<FilePattern>>,
|
||||
/// Like --exclude, but adds additional files and directories on top of the
|
||||
/// excluded ones.
|
||||
/// Like --exclude, but adds additional files and directories on top of
|
||||
/// those already excluded.
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
pub extend_exclude: Option<Vec<FilePattern>>,
|
||||
/// List of error codes to treat as eligible for autofix. Only applicable
|
||||
/// List of rule codes to treat as eligible for autofix. Only applicable
|
||||
/// when autofix itself is enabled (e.g., via `--fix`).
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
pub fixable: Option<Vec<RuleCodePrefix>>,
|
||||
/// List of error codes to treat as ineligible for autofix. Only applicable
|
||||
/// List of rule codes to treat as ineligible for autofix. Only applicable
|
||||
/// when autofix itself is enabled (e.g., via `--fix`).
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
pub unfixable: Option<Vec<RuleCodePrefix>>,
|
||||
/// List of mappings from file pattern to code to exclude
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
pub per_file_ignores: Option<Vec<PatternPrefixPair>>,
|
||||
/// Output serialization format for error messages.
|
||||
/// Output serialization format for violations.
|
||||
#[arg(long, value_enum, env = "RUFF_FORMAT")]
|
||||
pub format: Option<SerializationFormat>,
|
||||
/// The name of the file when passing it through stdin.
|
||||
@@ -129,7 +129,7 @@ pub struct Cli {
|
||||
/// The minimum Python version that should be supported.
|
||||
#[arg(long)]
|
||||
pub target_version: Option<PythonVersion>,
|
||||
/// Set the line-length for length-associated checks and automatic
|
||||
/// Set the line-length for length-associated rules and automatic
|
||||
/// formatting.
|
||||
#[arg(long)]
|
||||
pub line_length: Option<usize>,
|
||||
@@ -212,7 +212,7 @@ pub struct Cli {
|
||||
conflicts_with = "watch",
|
||||
)]
|
||||
pub show_files: bool,
|
||||
/// See the settings Ruff will use to check a given Python file.
|
||||
/// See the settings Ruff will use to lint a given Python file.
|
||||
#[arg(
|
||||
long,
|
||||
// Fake subcommands.
|
||||
|
||||
@@ -26,7 +26,7 @@ pub struct Options {
|
||||
value_type = "bool",
|
||||
example = "suppress-dummy-args = true"
|
||||
)]
|
||||
/// Whether to suppress `ANN000`-level errors for arguments matching the
|
||||
/// Whether to suppress `ANN000`-level violations for arguments matching the
|
||||
/// "dummy" variable regex (like `_`).
|
||||
pub suppress_dummy_args: Option<bool>,
|
||||
#[option(
|
||||
@@ -34,8 +34,8 @@ pub struct Options {
|
||||
value_type = "bool",
|
||||
example = "suppress-none-returning = true"
|
||||
)]
|
||||
/// Whether to suppress `ANN200`-level errors for functions that meet either
|
||||
/// of the following criteria:
|
||||
/// Whether to suppress `ANN200`-level violations for functions that meet
|
||||
/// either of the following criteria:
|
||||
///
|
||||
/// - Contain no `return` statement.
|
||||
/// - Explicit `return` statement(s) all return `None` (explicitly or
|
||||
|
||||
@@ -22,7 +22,7 @@ pub struct Options {
|
||||
"#
|
||||
)]
|
||||
/// Additional callable functions to consider "immutable" when evaluating,
|
||||
/// e.g., `no-mutable-default-argument` checks (`B006`).
|
||||
/// e.g., the `no-mutable-default-argument` rule (`B006`).
|
||||
pub extend_immutable_calls: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
|
||||
@@ -36,9 +36,9 @@ pub struct Options {
|
||||
)]
|
||||
/// Boolean flag specifying whether `@pytest.fixture()` without parameters
|
||||
/// should have parentheses. If the option is set to `true` (the
|
||||
/// default), `@pytest.fixture()` is valid and `@pytest.fixture` is an
|
||||
/// error. If set to `false`, `@pytest.fixture` is valid and
|
||||
/// `@pytest.fixture()` is an error.
|
||||
/// default), `@pytest.fixture()` is valid and `@pytest.fixture` is
|
||||
/// invalid. If set to `false`, `@pytest.fixture` is valid and
|
||||
/// `@pytest.fixture()` is invalid.
|
||||
pub fixture_parentheses: Option<bool>,
|
||||
#[option(
|
||||
default = "tuple",
|
||||
@@ -104,9 +104,9 @@ pub struct Options {
|
||||
)]
|
||||
/// Boolean flag specifying whether `@pytest.mark.foo()` without parameters
|
||||
/// should have parentheses. If the option is set to `true` (the
|
||||
/// default), `@pytest.mark.foo()` is valid and `@pytest.mark.foo` is an
|
||||
/// error. If set to `false`, `@pytest.fixture` is valid and
|
||||
/// `@pytest.mark.foo()` is an error.
|
||||
/// default), `@pytest.mark.foo()` is valid and `@pytest.mark.foo` is
|
||||
/// invalid. If set to `false`, `@pytest.fixture` is valid and
|
||||
/// `@pytest.mark.foo()` is invalid.
|
||||
pub mark_parentheses: Option<bool>,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use rustpython_ast::{Constant, Expr, ExprKind, Stmt, StmtKind};
|
||||
|
||||
use crate::ast::helpers::{create_expr, create_stmt, unparse_expr, unparse_stmt};
|
||||
use crate::ast::helpers::{
|
||||
contains_call_path, create_expr, create_stmt, unparse_expr, unparse_stmt,
|
||||
};
|
||||
use crate::ast::types::Range;
|
||||
use crate::autofix::Fix;
|
||||
use crate::checkers::ast::Checker;
|
||||
@@ -144,7 +146,28 @@ pub fn use_ternary_operator(checker: &mut Checker, stmt: &Stmt, parent: Option<&
|
||||
return;
|
||||
}
|
||||
|
||||
let target_var = &body_targets[0];
|
||||
// Avoid suggesting ternary for `if sys.version_info >= ...`-style checks.
|
||||
if contains_call_path(
|
||||
test,
|
||||
"sys",
|
||||
"version_info",
|
||||
&checker.import_aliases,
|
||||
&checker.from_imports,
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Avoid suggesting ternary for `if sys.platform.startswith("...")`-style
|
||||
// checks.
|
||||
if contains_call_path(
|
||||
test,
|
||||
"sys",
|
||||
"platform",
|
||||
&checker.import_aliases,
|
||||
&checker.from_imports,
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// It's part of a bigger if-elif block:
|
||||
// https://github.com/MartinThoma/flake8-simplify/issues/115
|
||||
@@ -176,6 +199,7 @@ pub fn use_ternary_operator(checker: &mut Checker, stmt: &Stmt, parent: Option<&
|
||||
}
|
||||
}
|
||||
|
||||
let target_var = &body_targets[0];
|
||||
let ternary = ternary(target_var, body_value, test, orelse_value);
|
||||
let content = unparse_stmt(&ternary, checker.style);
|
||||
let mut diagnostic = Diagnostic::new(
|
||||
|
||||
@@ -54,7 +54,7 @@ pub struct Options {
|
||||
"#
|
||||
)]
|
||||
/// Specific modules or module members that may not be imported or accessed.
|
||||
/// Note that this check is only meant to flag accidental uses,
|
||||
/// Note that this rule is only meant to flag accidental uses,
|
||||
/// and can be circumvented via `eval` or `importlib`.
|
||||
pub banned_api: Option<FxHashMap<String, BannedApi>>,
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
#[wasm_bindgen(typescript_custom_section)]
|
||||
const TYPES: &'static str = r#"
|
||||
export interface Check {
|
||||
export interface Diagnostic {
|
||||
code: string;
|
||||
message: string;
|
||||
location: {
|
||||
@@ -112,6 +112,7 @@ pub fn defaultSettings() -> Result<JsValue, JsValue> {
|
||||
show_source: None,
|
||||
src: None,
|
||||
unfixable: None,
|
||||
typing_modules: None,
|
||||
task_tags: None,
|
||||
update_check: None,
|
||||
// Use default options for all plugins.
|
||||
|
||||
@@ -169,7 +169,7 @@ fn add_noqa_inner(
|
||||
count += 1;
|
||||
}
|
||||
Directive::Codes(_, start, _, existing) => {
|
||||
// Reconstruct the line based on the preserved check codes.
|
||||
// Reconstruct the line based on the preserved rule codes.
|
||||
// This enables us to tally the number of edits.
|
||||
let mut formatted = String::new();
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ pub struct Options {
|
||||
ignore-overlong-task-comments = true
|
||||
"#
|
||||
)]
|
||||
/// Whether or not line-length checks (`E501`) should be triggered for
|
||||
/// Whether or not line-length violations (`E501`) should be triggered for
|
||||
/// comments starting with `task-tags` (by default: ["TODO", "FIXME",
|
||||
/// and "XXX"]).
|
||||
pub ignore_overlong_task_comments: Option<bool>,
|
||||
|
||||
@@ -163,6 +163,29 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_typing_modules() -> Result<()> {
|
||||
let diagnostics = test_path(
|
||||
Path::new("./resources/test/fixtures/pyflakes/typing_modules.py"),
|
||||
&settings::Settings::for_rules(vec![RuleCode::F821]),
|
||||
)?;
|
||||
insta::assert_yaml_snapshot!(diagnostics);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_typing_modules() -> Result<()> {
|
||||
let diagnostics = test_path(
|
||||
Path::new("./resources/test/fixtures/pyflakes/typing_modules.py"),
|
||||
&settings::Settings {
|
||||
typing_modules: vec!["airflow.typing_compat".to_string()],
|
||||
..settings::Settings::for_rules(vec![RuleCode::F821])
|
||||
},
|
||||
)?;
|
||||
insta::assert_yaml_snapshot!(diagnostics);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn future_annotations() -> Result<()> {
|
||||
let diagnostics = test_path(
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
source: src/pyflakes/mod.rs
|
||||
expression: diagnostics
|
||||
---
|
||||
- kind:
|
||||
UndefinedName: db
|
||||
location:
|
||||
row: 6
|
||||
column: 34
|
||||
end_location:
|
||||
row: 6
|
||||
column: 38
|
||||
fix: ~
|
||||
parent: ~
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
source: src/pyflakes/mod.rs
|
||||
expression: diagnostics
|
||||
---
|
||||
- kind:
|
||||
UndefinedName: Class
|
||||
location:
|
||||
row: 7
|
||||
column: 13
|
||||
end_location:
|
||||
row: 7
|
||||
column: 20
|
||||
fix: ~
|
||||
parent: ~
|
||||
|
||||
@@ -5,7 +5,7 @@ use rustpython_ast::{Expr, ExprKind};
|
||||
use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path};
|
||||
|
||||
// See: https://pypi.org/project/typing-extensions/
|
||||
static TYPING_EXTENSIONS: Lazy<FxHashSet<&'static str>> = Lazy::new(|| {
|
||||
pub static TYPING_EXTENSIONS: Lazy<FxHashSet<&'static str>> = Lazy::new(|| {
|
||||
FxHashSet::from_iter([
|
||||
"Annotated",
|
||||
"Any",
|
||||
@@ -61,159 +61,157 @@ static TYPING_EXTENSIONS: Lazy<FxHashSet<&'static str>> = Lazy::new(|| {
|
||||
])
|
||||
});
|
||||
|
||||
pub fn in_extensions(name: &str) -> bool {
|
||||
TYPING_EXTENSIONS.contains(name)
|
||||
}
|
||||
// See: https://docs.python.org/3/library/typing.html
|
||||
static SUBSCRIPTS: Lazy<FxHashMap<&'static str, Vec<&'static str>>> = Lazy::new(|| {
|
||||
let mut subscripts: FxHashMap<&'static str, Vec<&'static str>> = FxHashMap::default();
|
||||
for (module, name) in [
|
||||
// builtins
|
||||
("", "dict"),
|
||||
("", "frozenset"),
|
||||
("", "list"),
|
||||
("", "set"),
|
||||
("", "tuple"),
|
||||
("", "type"),
|
||||
// `collections`
|
||||
("collections", "ChainMap"),
|
||||
("collections", "Counter"),
|
||||
("collections", "OrderedDict"),
|
||||
("collections", "defaultdict"),
|
||||
("collections", "deque"),
|
||||
// `collections.abc`
|
||||
("collections.abc", "AsyncGenerator"),
|
||||
("collections.abc", "AsyncIterable"),
|
||||
("collections.abc", "AsyncIterator"),
|
||||
("collections.abc", "Awaitable"),
|
||||
("collections.abc", "ByteString"),
|
||||
("collections.abc", "Callable"),
|
||||
("collections.abc", "Collection"),
|
||||
("collections.abc", "Container"),
|
||||
("collections.abc", "Coroutine"),
|
||||
("collections.abc", "Generator"),
|
||||
("collections.abc", "ItemsView"),
|
||||
("collections.abc", "Iterable"),
|
||||
("collections.abc", "Iterator"),
|
||||
("collections.abc", "KeysView"),
|
||||
("collections.abc", "Mapping"),
|
||||
("collections.abc", "MappingView"),
|
||||
("collections.abc", "MutableMapping"),
|
||||
("collections.abc", "MutableSequence"),
|
||||
("collections.abc", "MutableSet"),
|
||||
("collections.abc", "Reversible"),
|
||||
("collections.abc", "Sequence"),
|
||||
("collections.abc", "Set"),
|
||||
("collections.abc", "ValuesView"),
|
||||
// `contextlib`
|
||||
("contextlib", "AbstractAsyncContextManager"),
|
||||
("contextlib", "AbstractContextManager"),
|
||||
// `re`
|
||||
("re", "Match"),
|
||||
("re", "Pattern"),
|
||||
// `typing`
|
||||
("typing", "AbstractSet"),
|
||||
("typing", "AsyncContextManager"),
|
||||
("typing", "AsyncGenerator"),
|
||||
("typing", "AsyncIterator"),
|
||||
("typing", "Awaitable"),
|
||||
("typing", "BinaryIO"),
|
||||
("typing", "ByteString"),
|
||||
("typing", "Callable"),
|
||||
("typing", "ChainMap"),
|
||||
("typing", "ClassVar"),
|
||||
("typing", "Collection"),
|
||||
("typing", "Concatenate"),
|
||||
("typing", "Container"),
|
||||
("typing", "ContextManager"),
|
||||
("typing", "Coroutine"),
|
||||
("typing", "Counter"),
|
||||
("typing", "DefaultDict"),
|
||||
("typing", "Deque"),
|
||||
("typing", "Dict"),
|
||||
("typing", "Final"),
|
||||
("typing", "FrozenSet"),
|
||||
("typing", "Generator"),
|
||||
("typing", "Generic"),
|
||||
("typing", "IO"),
|
||||
("typing", "ItemsView"),
|
||||
("typing", "Iterable"),
|
||||
("typing", "Iterator"),
|
||||
("typing", "KeysView"),
|
||||
("typing", "List"),
|
||||
("typing", "Mapping"),
|
||||
("typing", "Match"),
|
||||
("typing", "MutableMapping"),
|
||||
("typing", "MutableSequence"),
|
||||
("typing", "MutableSet"),
|
||||
("typing", "Optional"),
|
||||
("typing", "OrderedDict"),
|
||||
("typing", "Pattern"),
|
||||
("typing", "Reversible"),
|
||||
("typing", "Sequence"),
|
||||
("typing", "Set"),
|
||||
("typing", "TextIO"),
|
||||
("typing", "Tuple"),
|
||||
("typing", "Type"),
|
||||
("typing", "TypeGuard"),
|
||||
("typing", "Union"),
|
||||
("typing", "Unpack"),
|
||||
("typing", "ValuesView"),
|
||||
// `typing.io`
|
||||
("typing.io", "BinaryIO"),
|
||||
("typing.io", "IO"),
|
||||
("typing.io", "TextIO"),
|
||||
// `typing.re`
|
||||
("typing.re", "Match"),
|
||||
("typing.re", "Pattern"),
|
||||
// `typing_extensions`
|
||||
("typing_extensions", "AsyncContextManager"),
|
||||
("typing_extensions", "AsyncGenerator"),
|
||||
("typing_extensions", "AsyncIterable"),
|
||||
("typing_extensions", "AsyncIterator"),
|
||||
("typing_extensions", "Awaitable"),
|
||||
("typing_extensions", "ChainMap"),
|
||||
("typing_extensions", "ClassVar"),
|
||||
("typing_extensions", "Concatenate"),
|
||||
("typing_extensions", "ContextManager"),
|
||||
("typing_extensions", "Coroutine"),
|
||||
("typing_extensions", "Counter"),
|
||||
("typing_extensions", "DefaultDict"),
|
||||
("typing_extensions", "Deque"),
|
||||
("typing_extensions", "Type"),
|
||||
// `weakref`
|
||||
("weakref", "WeakKeyDictionary"),
|
||||
("weakref", "WeakSet"),
|
||||
("weakref", "WeakValueDictionary"),
|
||||
] {
|
||||
subscripts.entry(name).or_default().push(module);
|
||||
}
|
||||
subscripts
|
||||
});
|
||||
|
||||
// See: https://docs.python.org/3/library/typing.html
|
||||
const SUBSCRIPTS: &[(&str, &str)] = &[
|
||||
// builtins
|
||||
("", "dict"),
|
||||
("", "frozenset"),
|
||||
("", "list"),
|
||||
("", "set"),
|
||||
("", "tuple"),
|
||||
("", "type"),
|
||||
// `collections`
|
||||
("collections", "ChainMap"),
|
||||
("collections", "Counter"),
|
||||
("collections", "OrderedDict"),
|
||||
("collections", "defaultdict"),
|
||||
("collections", "deque"),
|
||||
// `collections.abc`
|
||||
("collections.abc", "AsyncGenerator"),
|
||||
("collections.abc", "AsyncIterable"),
|
||||
("collections.abc", "AsyncIterator"),
|
||||
("collections.abc", "Awaitable"),
|
||||
("collections.abc", "ByteString"),
|
||||
("collections.abc", "Callable"),
|
||||
("collections.abc", "Collection"),
|
||||
("collections.abc", "Container"),
|
||||
("collections.abc", "Coroutine"),
|
||||
("collections.abc", "Generator"),
|
||||
("collections.abc", "ItemsView"),
|
||||
("collections.abc", "Iterable"),
|
||||
("collections.abc", "Iterator"),
|
||||
("collections.abc", "KeysView"),
|
||||
("collections.abc", "Mapping"),
|
||||
("collections.abc", "MappingView"),
|
||||
("collections.abc", "MutableMapping"),
|
||||
("collections.abc", "MutableSequence"),
|
||||
("collections.abc", "MutableSet"),
|
||||
("collections.abc", "Reversible"),
|
||||
("collections.abc", "Sequence"),
|
||||
("collections.abc", "Set"),
|
||||
("collections.abc", "ValuesView"),
|
||||
// `contextlib`
|
||||
("contextlib", "AbstractAsyncContextManager"),
|
||||
("contextlib", "AbstractContextManager"),
|
||||
// `re`
|
||||
("re", "Match"),
|
||||
("re", "Pattern"),
|
||||
// `typing`
|
||||
("typing", "AbstractSet"),
|
||||
("typing", "AsyncContextManager"),
|
||||
("typing", "AsyncGenerator"),
|
||||
("typing", "AsyncIterator"),
|
||||
("typing", "Awaitable"),
|
||||
("typing", "BinaryIO"),
|
||||
("typing", "ByteString"),
|
||||
("typing", "Callable"),
|
||||
("typing", "ChainMap"),
|
||||
("typing", "ClassVar"),
|
||||
("typing", "Collection"),
|
||||
("typing", "Concatenate"),
|
||||
("typing", "Container"),
|
||||
("typing", "ContextManager"),
|
||||
("typing", "Coroutine"),
|
||||
("typing", "Counter"),
|
||||
("typing", "DefaultDict"),
|
||||
("typing", "Deque"),
|
||||
("typing", "Dict"),
|
||||
("typing", "Final"),
|
||||
("typing", "FrozenSet"),
|
||||
("typing", "Generator"),
|
||||
("typing", "Generic"),
|
||||
("typing", "IO"),
|
||||
("typing", "ItemsView"),
|
||||
("typing", "Iterable"),
|
||||
("typing", "Iterator"),
|
||||
("typing", "KeysView"),
|
||||
("typing", "List"),
|
||||
("typing", "Mapping"),
|
||||
("typing", "Match"),
|
||||
("typing", "MutableMapping"),
|
||||
("typing", "MutableSequence"),
|
||||
("typing", "MutableSet"),
|
||||
("typing", "Optional"),
|
||||
("typing", "OrderedDict"),
|
||||
("typing", "Pattern"),
|
||||
("typing", "Reversible"),
|
||||
("typing", "Sequence"),
|
||||
("typing", "Set"),
|
||||
("typing", "TextIO"),
|
||||
("typing", "Tuple"),
|
||||
("typing", "Type"),
|
||||
("typing", "TypeGuard"),
|
||||
("typing", "Union"),
|
||||
("typing", "Unpack"),
|
||||
("typing", "ValuesView"),
|
||||
// `typing.io`
|
||||
("typing.io", "BinaryIO"),
|
||||
("typing.io", "IO"),
|
||||
("typing.io", "TextIO"),
|
||||
// `typing.re`
|
||||
("typing.re", "Match"),
|
||||
("typing.re", "Pattern"),
|
||||
// `typing_extensions`
|
||||
("typing_extensions", "AsyncContextManager"),
|
||||
("typing_extensions", "AsyncGenerator"),
|
||||
("typing_extensions", "AsyncIterable"),
|
||||
("typing_extensions", "AsyncIterator"),
|
||||
("typing_extensions", "Awaitable"),
|
||||
("typing_extensions", "ChainMap"),
|
||||
("typing_extensions", "ClassVar"),
|
||||
("typing_extensions", "Concatenate"),
|
||||
("typing_extensions", "ContextManager"),
|
||||
("typing_extensions", "Coroutine"),
|
||||
("typing_extensions", "Counter"),
|
||||
("typing_extensions", "DefaultDict"),
|
||||
("typing_extensions", "Deque"),
|
||||
("typing_extensions", "Type"),
|
||||
// `weakref`
|
||||
("weakref", "WeakKeyDictionary"),
|
||||
("weakref", "WeakSet"),
|
||||
("weakref", "WeakValueDictionary"),
|
||||
];
|
||||
|
||||
// See: https://docs.python.org/3/library/typing.html
|
||||
const PEP_583_SUBSCRIPTS: &[(&str, &str)] = &[
|
||||
// `typing`
|
||||
("typing", "Annotated"),
|
||||
// `typing_extensions`
|
||||
("typing_extensions", "Annotated"),
|
||||
];
|
||||
|
||||
// See: https://peps.python.org/pep-0585/
|
||||
const PEP_585_BUILTINS_ELIGIBLE: &[(&str, &str)] = &[
|
||||
("typing", "Dict"),
|
||||
("typing", "FrozenSet"),
|
||||
("typing", "List"),
|
||||
("typing", "Set"),
|
||||
("typing", "Tuple"),
|
||||
("typing", "Type"),
|
||||
("typing_extensions", "Type"),
|
||||
];
|
||||
static PEP_593_SUBSCRIPTS: Lazy<FxHashMap<&'static str, Vec<&'static str>>> = Lazy::new(|| {
|
||||
let mut subscripts: FxHashMap<&'static str, Vec<&'static str>> = FxHashMap::default();
|
||||
for (module, name) in [
|
||||
// `typing`
|
||||
("typing", "Annotated"),
|
||||
// `typing_extensions`
|
||||
("typing_extensions", "Annotated"),
|
||||
] {
|
||||
subscripts.entry(name).or_default().push(module);
|
||||
}
|
||||
subscripts
|
||||
});
|
||||
|
||||
pub enum SubscriptKind {
|
||||
AnnotatedSubscript,
|
||||
PEP593AnnotatedSubscript,
|
||||
}
|
||||
|
||||
pub fn match_annotated_subscript<F>(
|
||||
pub fn match_annotated_subscript<'a, F>(
|
||||
expr: &Expr,
|
||||
from_imports: &FxHashMap<&str, FxHashSet<&str>>,
|
||||
import_aliases: &FxHashMap<&str, &str>,
|
||||
typing_modules: impl Iterator<Item = &'a str>,
|
||||
is_builtin: F,
|
||||
) -> Option<SubscriptKind>
|
||||
where
|
||||
@@ -226,23 +224,49 @@ where
|
||||
return None;
|
||||
}
|
||||
let call_path = dealias_call_path(collect_call_paths(expr), import_aliases);
|
||||
if !call_path.is_empty() {
|
||||
for (module, member) in SUBSCRIPTS {
|
||||
if match_call_path(&call_path, module, member, from_imports)
|
||||
&& (!module.is_empty() || is_builtin(member))
|
||||
{
|
||||
return Some(SubscriptKind::AnnotatedSubscript);
|
||||
if let Some(member) = call_path.last() {
|
||||
if let Some(modules) = SUBSCRIPTS.get(member) {
|
||||
for module in modules {
|
||||
if match_call_path(&call_path, module, member, from_imports)
|
||||
&& (!module.is_empty() || is_builtin(member))
|
||||
{
|
||||
return Some(SubscriptKind::AnnotatedSubscript);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (module, member) in PEP_583_SUBSCRIPTS {
|
||||
if match_call_path(&call_path, module, member, from_imports) {
|
||||
return Some(SubscriptKind::PEP593AnnotatedSubscript);
|
||||
for module in typing_modules {
|
||||
if match_call_path(&call_path, module, member, from_imports) {
|
||||
return Some(SubscriptKind::AnnotatedSubscript);
|
||||
}
|
||||
}
|
||||
} else if let Some(modules) = PEP_593_SUBSCRIPTS.get(member) {
|
||||
for module in modules {
|
||||
if match_call_path(&call_path, module, member, from_imports)
|
||||
&& (!module.is_empty() || is_builtin(member))
|
||||
{
|
||||
return Some(SubscriptKind::PEP593AnnotatedSubscript);
|
||||
}
|
||||
}
|
||||
for module in typing_modules {
|
||||
if match_call_path(&call_path, module, member, from_imports) {
|
||||
return Some(SubscriptKind::PEP593AnnotatedSubscript);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// See: https://peps.python.org/pep-0585/
|
||||
const PEP_585_BUILTINS_ELIGIBLE: &[(&str, &str)] = &[
|
||||
("typing", "Dict"),
|
||||
("typing", "FrozenSet"),
|
||||
("typing", "List"),
|
||||
("typing", "Set"),
|
||||
("typing", "Tuple"),
|
||||
("typing", "Type"),
|
||||
("typing_extensions", "Type"),
|
||||
];
|
||||
|
||||
/// Returns `true` if `Expr` represents a reference to a typing object with a
|
||||
/// PEP 585 built-in.
|
||||
pub fn is_pep585_builtin(
|
||||
|
||||
@@ -52,8 +52,9 @@ pub struct Configuration {
|
||||
pub show_source: Option<bool>,
|
||||
pub src: Option<Vec<PathBuf>>,
|
||||
pub target_version: Option<PythonVersion>,
|
||||
pub unfixable: Option<Vec<RuleCodePrefix>>,
|
||||
pub task_tags: Option<Vec<String>>,
|
||||
pub typing_modules: Option<Vec<String>>,
|
||||
pub unfixable: Option<Vec<RuleCodePrefix>>,
|
||||
pub update_check: Option<bool>,
|
||||
// Plugins
|
||||
pub flake8_annotations: Option<flake8_annotations::settings::Options>,
|
||||
@@ -153,8 +154,9 @@ impl Configuration {
|
||||
.map(|src| resolve_src(&src, project_root))
|
||||
.transpose()?,
|
||||
target_version: options.target_version,
|
||||
unfixable: options.unfixable,
|
||||
task_tags: options.task_tags,
|
||||
typing_modules: options.typing_modules,
|
||||
unfixable: options.unfixable,
|
||||
update_check: options.update_check,
|
||||
// Plugins
|
||||
flake8_annotations: options.flake8_annotations,
|
||||
@@ -217,8 +219,9 @@ impl Configuration {
|
||||
show_source: self.show_source.or(config.show_source),
|
||||
src: self.src.or(config.src),
|
||||
target_version: self.target_version.or(config.target_version),
|
||||
unfixable: self.unfixable.or(config.unfixable),
|
||||
task_tags: self.task_tags.or(config.task_tags),
|
||||
typing_modules: self.typing_modules.or(config.typing_modules),
|
||||
unfixable: self.unfixable.or(config.unfixable),
|
||||
update_check: self.update_check.or(config.update_check),
|
||||
// Plugins
|
||||
flake8_annotations: self.flake8_annotations.or(config.flake8_annotations),
|
||||
|
||||
@@ -61,6 +61,7 @@ pub struct Settings {
|
||||
pub src: Vec<PathBuf>,
|
||||
pub target_version: PythonVersion,
|
||||
pub task_tags: Vec<String>,
|
||||
pub typing_modules: Vec<String>,
|
||||
pub update_check: bool,
|
||||
// Plugins
|
||||
pub flake8_annotations: flake8_annotations::settings::Settings,
|
||||
@@ -180,6 +181,7 @@ impl Settings {
|
||||
task_tags: config.task_tags.unwrap_or_else(|| {
|
||||
vec!["TODO".to_string(), "FIXME".to_string(), "XXX".to_string()]
|
||||
}),
|
||||
typing_modules: config.typing_modules.unwrap_or_default(),
|
||||
update_check: config.update_check.unwrap_or(true),
|
||||
// Plugins
|
||||
flake8_annotations: config
|
||||
@@ -238,7 +240,8 @@ impl Settings {
|
||||
show_source: false,
|
||||
src: vec![path_dedot::CWD.clone()],
|
||||
target_version: PythonVersion::Py310,
|
||||
task_tags: vec!["TODO".to_string(), "FIXME".to_string()],
|
||||
task_tags: vec!["TODO".to_string(), "FIXME".to_string(), "XXX".to_string()],
|
||||
typing_modules: vec![],
|
||||
update_check: false,
|
||||
flake8_annotations: flake8_annotations::settings::Settings::default(),
|
||||
flake8_bandit: flake8_bandit::settings::Settings::default(),
|
||||
@@ -281,7 +284,8 @@ impl Settings {
|
||||
show_source: false,
|
||||
src: vec![path_dedot::CWD.clone()],
|
||||
target_version: PythonVersion::Py310,
|
||||
task_tags: vec!["TODO".to_string()],
|
||||
task_tags: vec!["TODO".to_string(), "FIXME".to_string(), "XXX".to_string()],
|
||||
typing_modules: vec![],
|
||||
update_check: false,
|
||||
flake8_annotations: flake8_annotations::settings::Settings::default(),
|
||||
flake8_bandit: flake8_bandit::settings::Settings::default(),
|
||||
@@ -321,6 +325,7 @@ impl Hash for Settings {
|
||||
for confusable in &self.allowed_confusables {
|
||||
confusable.hash(state);
|
||||
}
|
||||
self.builtins.hash(state);
|
||||
self.dummy_variable_rgx.as_str().hash(state);
|
||||
for value in self.enabled.iter().sorted() {
|
||||
value.hash(state);
|
||||
@@ -343,6 +348,8 @@ impl Hash for Settings {
|
||||
self.show_source.hash(state);
|
||||
self.src.hash(state);
|
||||
self.target_version.hash(state);
|
||||
self.task_tags.hash(state);
|
||||
self.typing_modules.hash(state);
|
||||
// Add plugin properties in alphabetical order.
|
||||
self.flake8_annotations.hash(state);
|
||||
self.flake8_bandit.hash(state);
|
||||
@@ -396,7 +403,7 @@ struct RuleCodeSpec<'a> {
|
||||
}
|
||||
|
||||
/// Given a set of selected and ignored prefixes, resolve the set of enabled
|
||||
/// error codes.
|
||||
/// rule codes.
|
||||
fn resolve_codes<'a>(specs: impl Iterator<Item = RuleCodeSpec<'a>>) -> FxHashSet<RuleCode> {
|
||||
let mut codes: FxHashSet<RuleCode> = FxHashSet::default();
|
||||
for spec in specs {
|
||||
|
||||
@@ -65,7 +65,7 @@ pub struct Options {
|
||||
"#
|
||||
)]
|
||||
/// A regular expression used to identify "dummy" variables, or those which
|
||||
/// should be ignored when evaluating (e.g.) unused-variable checks. The
|
||||
/// should be ignored when enforcing (e.g.) unused-variable rules. The
|
||||
/// default expression matches `_`, `__`, and `_var`, but not `_var_`.
|
||||
pub dummy_variable_rgx: Option<String>,
|
||||
#[option(
|
||||
@@ -123,12 +123,12 @@ pub struct Options {
|
||||
default = "[]",
|
||||
value_type = "Vec<RuleCodePrefix>",
|
||||
example = r#"
|
||||
# Skip unused variable checks (`F841`).
|
||||
# Skip unused variable rules (`F841`).
|
||||
extend-ignore = ["F841"]
|
||||
"#
|
||||
)]
|
||||
/// A list of check code prefixes to ignore, in addition to those specified
|
||||
/// by `ignore`.
|
||||
/// A list of rule codes or prefixes to ignore, in addition to those
|
||||
/// specified by `ignore`.
|
||||
pub extend_ignore: Option<Vec<RuleCodePrefix>>,
|
||||
#[option(
|
||||
default = "[]",
|
||||
@@ -138,8 +138,8 @@ pub struct Options {
|
||||
extend-select = ["B", "Q"]
|
||||
"#
|
||||
)]
|
||||
/// A list of check code prefixes to enable, in addition to those specified
|
||||
/// by `select`.
|
||||
/// A list of rule codes or prefixes to enable, in addition to those
|
||||
/// specified by `select`.
|
||||
pub extend_select: Option<Vec<RuleCodePrefix>>,
|
||||
#[option(
|
||||
default = "[]",
|
||||
@@ -150,7 +150,7 @@ pub struct Options {
|
||||
external = ["V101"]
|
||||
"#
|
||||
)]
|
||||
/// A list of check codes that are unsupported by Ruff, but should be
|
||||
/// A list of rule codes that are unsupported by Ruff, but should be
|
||||
/// preserved when (e.g.) validating `# noqa` directives. Useful for
|
||||
/// retaining `# noqa` directives that cover plugins not yet implemented
|
||||
/// by Ruff.
|
||||
@@ -166,11 +166,11 @@ pub struct Options {
|
||||
default = r#"["A", "ANN", "ARG", "B", "BLE", "C", "D", "E", "ERA", "F", "FBT", "I", "ICN", "N", "PGH", "PLC", "PLE", "PLR", "PLW", "Q", "RET", "RUF", "S", "T", "TID", "UP", "W", "YTT"]"#,
|
||||
value_type = "Vec<RuleCodePrefix>",
|
||||
example = r#"
|
||||
# Only allow autofix behavior for `E` and `F` checks.
|
||||
# Only allow autofix behavior for `E` and `F` rules.
|
||||
fixable = ["E", "F"]
|
||||
"#
|
||||
)]
|
||||
/// A list of check code prefixes to consider autofix-able.
|
||||
/// A list of rule codes or prefixes to consider autofixable.
|
||||
pub fixable: Option<Vec<RuleCodePrefix>>,
|
||||
#[option(
|
||||
default = r#""text""#,
|
||||
@@ -208,15 +208,15 @@ pub struct Options {
|
||||
default = "[]",
|
||||
value_type = "Vec<RuleCodePrefix>",
|
||||
example = r#"
|
||||
# Skip unused variable checks (`F841`).
|
||||
# Skip unused variable rules (`F841`).
|
||||
ignore = ["F841"]
|
||||
"#
|
||||
)]
|
||||
/// A list of check code prefixes to ignore. Prefixes can specify exact
|
||||
/// checks (like `F841`), entire categories (like `F`), or anything in
|
||||
/// A list of rule codes or prefixes to ignore. Prefixes can specify exact
|
||||
/// rules (like `F841`), entire categories (like `F`), or anything in
|
||||
/// between.
|
||||
///
|
||||
/// When breaking ties between enabled and disabled checks (via `select` and
|
||||
/// When breaking ties between enabled and disabled rules (via `select` and
|
||||
/// `ignore`, respectively), more specific prefixes override less
|
||||
/// specific prefixes.
|
||||
pub ignore: Option<Vec<RuleCodePrefix>>,
|
||||
@@ -274,11 +274,11 @@ pub struct Options {
|
||||
select = ["E", "F", "B", "Q"]
|
||||
"#
|
||||
)]
|
||||
/// A list of check code prefixes to enable. Prefixes can specify exact
|
||||
/// checks (like `F841`), entire categories (like `F`), or anything in
|
||||
/// A list of rule codes or prefixes to enable. Prefixes can specify exact
|
||||
/// rules (like `F841`), entire categories (like `F`), or anything in
|
||||
/// between.
|
||||
///
|
||||
/// When breaking ties between enabled and disabled checks (via `select` and
|
||||
/// When breaking ties between enabled and disabled rules (via `select` and
|
||||
/// `ignore`, respectively), more specific prefixes override less
|
||||
/// specific prefixes.
|
||||
pub select: Option<Vec<RuleCodePrefix>>,
|
||||
@@ -290,8 +290,8 @@ pub struct Options {
|
||||
show-source = true
|
||||
"#
|
||||
)]
|
||||
/// Whether to show source code snippets when reporting lint error
|
||||
/// violations (overridden by the `--show-source` command-line flag).
|
||||
/// Whether to show source code snippets when reporting lint violations
|
||||
/// (overridden by the `--show-source` command-line flag).
|
||||
pub show_source: Option<bool>,
|
||||
#[option(
|
||||
default = r#"["."]"#,
|
||||
@@ -339,16 +339,6 @@ pub struct Options {
|
||||
/// version will _not_ be inferred from the _current_ Python version,
|
||||
/// and instead must be specified explicitly (as seen below).
|
||||
pub target_version: Option<PythonVersion>,
|
||||
#[option(
|
||||
default = "[]",
|
||||
value_type = "Vec<RuleCodePrefix>",
|
||||
example = r#"
|
||||
# Disable autofix for unused imports (`F401`).
|
||||
unfixable = ["F401"]
|
||||
"#
|
||||
)]
|
||||
/// A list of check code prefixes to consider un-autofix-able.
|
||||
pub unfixable: Option<Vec<RuleCodePrefix>>,
|
||||
#[option(
|
||||
default = r#"["TODO", "FIXME", "XXX"]"#,
|
||||
value_type = "Vec<String>",
|
||||
@@ -357,9 +347,33 @@ pub struct Options {
|
||||
/// A list of task tags to recognize (e.g., "TODO", "FIXME", "XXX").
|
||||
///
|
||||
/// Comments starting with these tags will be ignored by commented-out code
|
||||
/// detection (`ERA`), and skipped by line-length checks (`E501`) if
|
||||
/// detection (`ERA`), and skipped by line-length rules (`E501`) if
|
||||
/// `ignore-overlong-task-comments` is set to `true`.
|
||||
pub task_tags: Option<Vec<String>>,
|
||||
#[option(
|
||||
default = r#"[]"#,
|
||||
value_type = "Vec<String>",
|
||||
example = r#"typing-modules = ["airflow.typing_compat"]"#
|
||||
)]
|
||||
/// A list of modules whose imports should be treated equivalently to
|
||||
/// members of the `typing` module.
|
||||
///
|
||||
/// This is useful for ensuring proper type annotation inference for
|
||||
/// projects that re-export `typing` and `typing_extensions` members
|
||||
/// from a compatibility module. If omitted, any members imported from
|
||||
/// modules apart from `typing` and `typing_extensions` will be treated
|
||||
/// as ordinary Python objects.
|
||||
pub typing_modules: Option<Vec<String>>,
|
||||
#[option(
|
||||
default = "[]",
|
||||
value_type = "Vec<RuleCodePrefix>",
|
||||
example = r#"
|
||||
# Disable autofix for unused imports (`F401`).
|
||||
unfixable = ["F401"]
|
||||
"#
|
||||
)]
|
||||
/// A list of rule codes or prefixes to consider non-autofix-able.
|
||||
pub unfixable: Option<Vec<RuleCodePrefix>>,
|
||||
#[option(
|
||||
default = "true",
|
||||
value_type = "bool",
|
||||
@@ -424,7 +438,7 @@ pub struct Options {
|
||||
"path/to/file.py" = ["E402"]
|
||||
"#
|
||||
)]
|
||||
/// A list of mappings from file pattern to check code prefixes to exclude,
|
||||
/// when considering any matching files.
|
||||
/// A list of mappings from file pattern to rule codes or prefixes to
|
||||
/// exclude, when considering any matching files.
|
||||
pub per_file_ignores: Option<FxHashMap<String, Vec<RuleCodePrefix>>>,
|
||||
}
|
||||
|
||||
@@ -189,6 +189,7 @@ mod tests {
|
||||
src: None,
|
||||
target_version: None,
|
||||
unfixable: None,
|
||||
typing_modules: None,
|
||||
task_tags: None,
|
||||
update_check: None,
|
||||
flake8_annotations: None,
|
||||
@@ -246,6 +247,7 @@ line-length = 79
|
||||
src: None,
|
||||
target_version: None,
|
||||
unfixable: None,
|
||||
typing_modules: None,
|
||||
task_tags: None,
|
||||
update_check: None,
|
||||
cache_dir: None,
|
||||
@@ -305,6 +307,7 @@ exclude = ["foo.py"]
|
||||
src: None,
|
||||
target_version: None,
|
||||
unfixable: None,
|
||||
typing_modules: None,
|
||||
task_tags: None,
|
||||
update_check: None,
|
||||
flake8_annotations: None,
|
||||
@@ -363,6 +366,7 @@ select = ["E501"]
|
||||
src: None,
|
||||
target_version: None,
|
||||
unfixable: None,
|
||||
typing_modules: None,
|
||||
task_tags: None,
|
||||
update_check: None,
|
||||
flake8_annotations: None,
|
||||
@@ -422,6 +426,7 @@ ignore = ["E501"]
|
||||
src: None,
|
||||
target_version: None,
|
||||
unfixable: None,
|
||||
typing_modules: None,
|
||||
task_tags: None,
|
||||
update_check: None,
|
||||
flake8_annotations: None,
|
||||
@@ -511,6 +516,7 @@ other-attribute = 1
|
||||
format: None,
|
||||
force_exclude: None,
|
||||
unfixable: None,
|
||||
typing_modules: None,
|
||||
task_tags: None,
|
||||
update_check: None,
|
||||
cache_dir: None,
|
||||
|
||||
@@ -5086,7 +5086,7 @@ define_violation!(
|
||||
);
|
||||
impl Violation for BlanketTypeIgnore {
|
||||
fn message(&self) -> String {
|
||||
"Use specific error codes when ignoring type issues".to_string()
|
||||
"Use specific rule codes when ignoring type issues".to_string()
|
||||
}
|
||||
|
||||
fn placeholder() -> Self {
|
||||
@@ -5099,7 +5099,7 @@ define_violation!(
|
||||
);
|
||||
impl Violation for BlanketNOQA {
|
||||
fn message(&self) -> String {
|
||||
"Use specific error codes when using `noqa`".to_string()
|
||||
"Use specific rule codes when using `noqa`".to_string()
|
||||
}
|
||||
|
||||
fn placeholder() -> Self {
|
||||
|
||||
Reference in New Issue
Block a user