Compare commits
41 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d83f99dbf | ||
|
|
5123b38758 | ||
|
|
e9a4c8ba13 | ||
|
|
927d716edd | ||
|
|
df6a48fced | ||
|
|
91a8277ac0 | ||
|
|
5797884262 | ||
|
|
5aa8455258 | ||
|
|
8fd713739b | ||
|
|
5de1fcd653 | ||
|
|
032f4f3f12 | ||
|
|
621db96e7f | ||
|
|
05867ef260 | ||
|
|
0cd8b75f06 | ||
|
|
5f07e1d6b5 | ||
|
|
1ce4585c88 | ||
|
|
f3f010cdf5 | ||
|
|
7e5e03fb15 | ||
|
|
062c41b6f5 | ||
|
|
78889efa37 | ||
|
|
97fc281779 | ||
|
|
138b06c98a | ||
|
|
2415d73260 | ||
|
|
b060ae2f22 | ||
|
|
9aa91d3d3c | ||
|
|
dcedb801e5 | ||
|
|
d3e7fdabb5 | ||
|
|
dfa5a4f0f7 | ||
|
|
58a2d600da | ||
|
|
7ecbfe4f6a | ||
|
|
d8248104a7 | ||
|
|
6eb09122c0 | ||
|
|
f84c1f1fa1 | ||
|
|
3aa9528229 | ||
|
|
5a3f06bab1 | ||
|
|
db59d5b558 | ||
|
|
2fcbf3ab62 | ||
|
|
fa9b10be72 | ||
|
|
c495cef529 | ||
|
|
c0c8dff6ce | ||
|
|
80b00cc89f |
8
.github/workflows/ci.yaml
vendored
8
.github/workflows/ci.yaml
vendored
@@ -27,7 +27,7 @@ jobs:
|
||||
${{ runner.os }}-build-${{ env.cache-name }}-
|
||||
${{ runner.os }}-build-
|
||||
${{ runner.os }}-
|
||||
- run: cargo build --release
|
||||
- run: cargo build --all --release
|
||||
|
||||
cargo_fmt:
|
||||
name: "cargo fmt"
|
||||
@@ -49,7 +49,7 @@ jobs:
|
||||
${{ runner.os }}-build-${{ env.cache-name }}-
|
||||
${{ runner.os }}-build-
|
||||
${{ runner.os }}-
|
||||
- run: cargo fmt --check
|
||||
- run: cargo fmt --all --check
|
||||
|
||||
cargo_clippy:
|
||||
name: "cargo clippy"
|
||||
@@ -71,7 +71,7 @@ jobs:
|
||||
${{ runner.os }}-build-${{ env.cache-name }}-
|
||||
${{ runner.os }}-build-
|
||||
${{ runner.os }}-
|
||||
- run: cargo clippy -- -D warnings
|
||||
- run: cargo clippy --all -- -D warnings
|
||||
|
||||
cargo_test:
|
||||
name: "cargo test"
|
||||
@@ -93,7 +93,7 @@ jobs:
|
||||
${{ runner.os }}-build-${{ env.cache-name }}-
|
||||
${{ runner.os }}-build-
|
||||
${{ runner.os }}-
|
||||
- run: cargo test
|
||||
- run: cargo test --all
|
||||
|
||||
maturin_build:
|
||||
name: "maturin build"
|
||||
|
||||
298
.github/workflows/flake8-to-ruff.yaml
vendored
Normal file
298
.github/workflows/flake8-to-ruff.yaml
vendored
Normal file
@@ -0,0 +1,298 @@
|
||||
name: "[flake8-to-ruff] Release"
|
||||
|
||||
on: workflow_dispatch
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
PACKAGE_NAME: flake8-to-ruff
|
||||
CRATE_NAME: flake8_to_ruff
|
||||
PYTHON_VERSION: "3.7" # to build abi3 wheels
|
||||
|
||||
jobs:
|
||||
macos-x86_64:
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
architecture: x64
|
||||
- name: Install Rust toolchain
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
default: true
|
||||
- name: Build wheels - x86_64
|
||||
uses: messense/maturin-action@v1
|
||||
with:
|
||||
target: x86_64
|
||||
args: --release --out dist --sdist -m ./crates/${{ env.CRATE_NAME }}/Cargo.toml
|
||||
maturin-version: "v0.13.0"
|
||||
- name: Install built wheel - x86_64
|
||||
run: |
|
||||
pip install dist/${{ env.CRATE_NAME }}-*.whl --force-reinstall
|
||||
- name: Upload wheels
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: wheels
|
||||
path: dist
|
||||
macos-universal:
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
architecture: x64
|
||||
- name: Install Rust toolchain
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
default: true
|
||||
- name: Build wheels - universal2
|
||||
uses: messense/maturin-action@v1
|
||||
with:
|
||||
args: --release --universal2 --out dist -m ./crates/${{ env.CRATE_NAME }}/Cargo.toml
|
||||
maturin-version: "v0.13.0"
|
||||
- name: Install built wheel - universal2
|
||||
run: |
|
||||
pip install dist/${{ env.CRATE_NAME }}-*universal2.whl --force-reinstall
|
||||
- name: Upload wheels
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: wheels
|
||||
path: dist
|
||||
|
||||
windows:
|
||||
runs-on: windows-latest
|
||||
strategy:
|
||||
matrix:
|
||||
target: [x64, x86]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
architecture: ${{ matrix.target }}
|
||||
- name: Install Rust toolchain
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
default: true
|
||||
- name: Build wheels
|
||||
uses: messense/maturin-action@v1
|
||||
with:
|
||||
target: ${{ matrix.target }}
|
||||
args: --release --out dist -m ./crates/${{ env.CRATE_NAME }}/Cargo.toml
|
||||
maturin-version: "v0.13.0"
|
||||
- name: Install built wheel
|
||||
shell: bash
|
||||
run: |
|
||||
python -m pip install dist/${{ env.CRATE_NAME }}-*.whl --force-reinstall
|
||||
- name: Upload wheels
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: wheels
|
||||
path: dist
|
||||
|
||||
linux:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
target: [x86_64, i686]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
architecture: x64
|
||||
- name: Build wheels
|
||||
uses: messense/maturin-action@v1
|
||||
with:
|
||||
target: ${{ matrix.target }}
|
||||
manylinux: auto
|
||||
args: --release --out dist -m ./crates/${{ env.CRATE_NAME }}/Cargo.toml
|
||||
maturin-version: "v0.13.0"
|
||||
- name: Install built wheel
|
||||
if: matrix.target == 'x86_64'
|
||||
run: |
|
||||
pip install dist/${{ env.CRATE_NAME }}-*.whl --force-reinstall
|
||||
- name: Upload wheels
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: wheels
|
||||
path: dist
|
||||
|
||||
linux-cross:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
target: [aarch64, armv7, s390x, ppc64le, ppc64]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
- name: Build wheels
|
||||
uses: messense/maturin-action@v1
|
||||
with:
|
||||
target: ${{ matrix.target }}
|
||||
manylinux: auto
|
||||
args: --no-default-features --release --out dist -m ./crates/${{ env.CRATE_NAME }}/Cargo.toml
|
||||
maturin-version: "v0.13.0"
|
||||
- uses: uraimo/run-on-arch-action@v2.0.5
|
||||
if: matrix.target != 'ppc64'
|
||||
name: Install built wheel
|
||||
with:
|
||||
arch: ${{ matrix.target }}
|
||||
distro: ubuntu20.04
|
||||
githubToken: ${{ github.token }}
|
||||
install: |
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends python3 python3-pip
|
||||
pip3 install -U pip
|
||||
run: |
|
||||
pip3 install ${{ env.PACKAGE_NAME }} --no-index --find-links dist/ --force-reinstall
|
||||
- name: Upload wheels
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: wheels
|
||||
path: dist
|
||||
|
||||
musllinux:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
target:
|
||||
- x86_64-unknown-linux-musl
|
||||
- i686-unknown-linux-musl
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
architecture: x64
|
||||
- name: Build wheels
|
||||
uses: messense/maturin-action@v1
|
||||
with:
|
||||
target: ${{ matrix.target }}
|
||||
manylinux: musllinux_1_2
|
||||
args: --release --out dist -m ./crates/${{ env.CRATE_NAME }}/Cargo.toml
|
||||
maturin-version: "v0.13.0"
|
||||
- name: Install built wheel
|
||||
if: matrix.target == 'x86_64-unknown-linux-musl'
|
||||
uses: addnab/docker-run-action@v3
|
||||
with:
|
||||
image: alpine:latest
|
||||
options: -v ${{ github.workspace }}:/io -w /io
|
||||
run: |
|
||||
apk add py3-pip
|
||||
pip3 install ${{ env.PACKAGE_NAME }} --no-index --find-links /io/dist/ --force-reinstall
|
||||
- name: Upload wheels
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: wheels
|
||||
path: dist
|
||||
|
||||
musllinux-cross:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
platform:
|
||||
- target: aarch64-unknown-linux-musl
|
||||
arch: aarch64
|
||||
- target: armv7-unknown-linux-musleabihf
|
||||
arch: armv7
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
- name: Build wheels
|
||||
uses: messense/maturin-action@v1
|
||||
with:
|
||||
target: ${{ matrix.platform.target }}
|
||||
manylinux: musllinux_1_2
|
||||
args: --release --out dist -m ./crates/${{ env.CRATE_NAME }}/Cargo.toml
|
||||
maturin-version: "v0.13.0"
|
||||
- uses: uraimo/run-on-arch-action@master
|
||||
name: Install built wheel
|
||||
with:
|
||||
arch: ${{ matrix.platform.arch }}
|
||||
distro: alpine_latest
|
||||
githubToken: ${{ github.token }}
|
||||
install: |
|
||||
apk add py3-pip
|
||||
run: |
|
||||
pip3 install ${{ env.PACKAGE_NAME }} --no-index --find-links dist/ --force-reinstall
|
||||
- name: Upload wheels
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: wheels
|
||||
path: dist
|
||||
|
||||
pypy:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
target: [x86_64, aarch64]
|
||||
python-version:
|
||||
- "3.7"
|
||||
- "3.8"
|
||||
- "3.9"
|
||||
exclude:
|
||||
- os: macos-latest
|
||||
target: aarch64
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: pypy${{ matrix.python-version }}
|
||||
- name: Build wheels
|
||||
uses: messense/maturin-action@v1
|
||||
with:
|
||||
maturin-version: "v0.13.0"
|
||||
target: ${{ matrix.target }}
|
||||
manylinux: auto
|
||||
args: --release --out dist -i pypy${{ matrix.python-version }} -m ./crates/${{ env.CRATE_NAME }}/Cargo.toml
|
||||
- name: Install built wheel
|
||||
if: matrix.target == 'x86_64'
|
||||
run: |
|
||||
pip install dist/${{ env.CRATE_NAME }}-*.whl --force-reinstall
|
||||
- name: Upload wheels
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: wheels
|
||||
path: dist
|
||||
|
||||
release:
|
||||
name: Release
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- macos-universal
|
||||
- macos-x86_64
|
||||
- windows
|
||||
- linux
|
||||
- linux-cross
|
||||
- musllinux
|
||||
- musllinux-cross
|
||||
- pypy
|
||||
steps:
|
||||
- uses: actions/download-artifact@v2
|
||||
with:
|
||||
name: wheels
|
||||
- uses: actions/setup-python@v4
|
||||
- name: Publish to PyPi
|
||||
env:
|
||||
TWINE_USERNAME: __token__
|
||||
TWINE_PASSWORD: ${{ secrets.FLAKE8_TO_RUFF_TOKEN }}
|
||||
run: |
|
||||
pip install --upgrade twine
|
||||
twine upload --skip-existing *
|
||||
@@ -1,8 +1,6 @@
|
||||
name: Release
|
||||
name: "[ruff] Release"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
create:
|
||||
tags:
|
||||
- v*
|
||||
@@ -297,7 +295,7 @@ jobs:
|
||||
- name: Publish to PyPi
|
||||
env:
|
||||
TWINE_USERNAME: __token__
|
||||
TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}
|
||||
TWINE_PASSWORD: ${{ secrets.RUFF_TOKEN }}
|
||||
run: |
|
||||
pip install --upgrade twine
|
||||
twine upload --skip-existing *
|
||||
@@ -1,6 +1,6 @@
|
||||
repos:
|
||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||
rev: v0.0.89
|
||||
rev: v0.0.94
|
||||
hooks:
|
||||
- id: ruff
|
||||
|
||||
|
||||
190
Cargo.lock
generated
190
Cargo.lock
generated
@@ -37,6 +37,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anes"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
|
||||
|
||||
[[package]]
|
||||
name = "annotate-snippets"
|
||||
version = "0.6.1"
|
||||
@@ -368,6 +374,12 @@ version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1db59621ec70f09c5e9b597b220c7a2b43611f4710dc03ceb8748637775692c"
|
||||
|
||||
[[package]]
|
||||
name = "cast"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.0.73"
|
||||
@@ -416,6 +428,45 @@ version = "1.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fff857943da45f546682664a79488be82e69e43c1a7a2307679ab9afb3a66d2e"
|
||||
|
||||
[[package]]
|
||||
name = "ciborium"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b0c137568cc60b904a7724001b35ce2630fd00d5d84805fbb608ab89509d788f"
|
||||
dependencies = [
|
||||
"ciborium-io",
|
||||
"ciborium-ll",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ciborium-io"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "346de753af073cc87b52b2083a506b38ac176a44cfb05497b622e27be899b369"
|
||||
|
||||
[[package]]
|
||||
name = "ciborium-ll"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "213030a2b5a4e0c0892b6652260cf6ccac84827b83a85a534e178e3906c4cf1b"
|
||||
dependencies = [
|
||||
"ciborium-io",
|
||||
"half",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "3.2.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "71655c45cb9845d3270c9d6df84ebe72b4dad3c2ba3f7023ad47c144e4e473a5"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"clap_lex 0.2.4",
|
||||
"indexmap",
|
||||
"textwrap 0.16.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.0.15"
|
||||
@@ -425,7 +476,7 @@ dependencies = [
|
||||
"atty",
|
||||
"bitflags",
|
||||
"clap_derive",
|
||||
"clap_lex",
|
||||
"clap_lex 0.3.0",
|
||||
"once_cell",
|
||||
"strsim",
|
||||
"termcolor",
|
||||
@@ -444,6 +495,15 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5"
|
||||
dependencies = [
|
||||
"os_str_bytes",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "0.3.0"
|
||||
@@ -511,6 +571,12 @@ dependencies = [
|
||||
"cache-padded",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "configparser"
|
||||
version = "3.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5458d9d1a587efaf5091602c59d299696a3877a439c8f6d461a2d3cce11df87a"
|
||||
|
||||
[[package]]
|
||||
name = "console"
|
||||
version = "0.15.2"
|
||||
@@ -548,6 +614,42 @@ dependencies = [
|
||||
"cfg-if 1.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "criterion"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c76e09c1aae2bc52b3d2f29e13c6572553b30c4aa1b8a49fd70de6412654cb"
|
||||
dependencies = [
|
||||
"anes",
|
||||
"atty",
|
||||
"cast",
|
||||
"ciborium",
|
||||
"clap 3.2.23",
|
||||
"criterion-plot",
|
||||
"itertools",
|
||||
"lazy_static",
|
||||
"num-traits",
|
||||
"oorandom",
|
||||
"plotters",
|
||||
"rayon",
|
||||
"regex",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"tinytemplate",
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "criterion-plot"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1"
|
||||
dependencies = [
|
||||
"cast",
|
||||
"itertools",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-channel"
|
||||
version = "0.5.6"
|
||||
@@ -816,6 +918,21 @@ version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
|
||||
|
||||
[[package]]
|
||||
name = "flake8-to-ruff"
|
||||
version = "0.0.94-dev.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap 4.0.15",
|
||||
"configparser",
|
||||
"once_cell",
|
||||
"regex",
|
||||
"ruff",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"toml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flate2"
|
||||
version = "1.0.24"
|
||||
@@ -1041,6 +1158,12 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "half"
|
||||
version = "1.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.12.3"
|
||||
@@ -1571,6 +1694,12 @@ version = "1.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e82dad04139b71a90c080c8463fe0dc7902db5192d939bd0950f074d014339e1"
|
||||
|
||||
[[package]]
|
||||
name = "oorandom"
|
||||
version = "11.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575"
|
||||
|
||||
[[package]]
|
||||
name = "opaque-debug"
|
||||
version = "0.2.3"
|
||||
@@ -1779,6 +1908,34 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
|
||||
|
||||
[[package]]
|
||||
name = "plotters"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2538b639e642295546c50fcd545198c9d64ee2a38620a628724a3b266d5fbf97"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
"plotters-backend",
|
||||
"plotters-svg",
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "plotters-backend"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "193228616381fecdc1224c62e96946dfbc73ff4384fba576e052ff8c1bea8142"
|
||||
|
||||
[[package]]
|
||||
name = "plotters-svg"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9a81d2759aae1dae668f783c308bc5c8ebd191ff4184aaa1b37f65a6ae5a56f"
|
||||
dependencies = [
|
||||
"plotters-backend",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "polling"
|
||||
version = "2.3.0"
|
||||
@@ -2054,18 +2211,19 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ruff"
|
||||
version = "0.0.89"
|
||||
version = "0.0.94"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"assert_cmd",
|
||||
"bincode",
|
||||
"cacache",
|
||||
"chrono",
|
||||
"clap",
|
||||
"clap 4.0.15",
|
||||
"clearscreen",
|
||||
"codegen",
|
||||
"colored",
|
||||
"common-path",
|
||||
"criterion",
|
||||
"dirs 4.0.0",
|
||||
"fern",
|
||||
"filetime",
|
||||
@@ -2089,7 +2247,7 @@ dependencies = [
|
||||
"strum",
|
||||
"strum_macros",
|
||||
"test-case",
|
||||
"textwrap",
|
||||
"textwrap 0.15.1",
|
||||
"titlecase",
|
||||
"toml",
|
||||
"update-informer",
|
||||
@@ -2111,7 +2269,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustpython-ast"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/charliermarsh/RustPython.git?rev=1b253a12705f84972cd76e8dc1cdaaccb233e5a5#1b253a12705f84972cd76e8dc1cdaaccb233e5a5"
|
||||
source = "git+https://github.com/RustPython/RustPython.git?rev=77b821a1941019fe34f73ce17cea013ae1b98fd0#77b821a1941019fe34f73ce17cea013ae1b98fd0"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"rustpython-common",
|
||||
@@ -2121,7 +2279,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustpython-common"
|
||||
version = "0.0.0"
|
||||
source = "git+https://github.com/charliermarsh/RustPython.git?rev=1b253a12705f84972cd76e8dc1cdaaccb233e5a5#1b253a12705f84972cd76e8dc1cdaaccb233e5a5"
|
||||
source = "git+https://github.com/RustPython/RustPython.git?rev=77b821a1941019fe34f73ce17cea013ae1b98fd0#77b821a1941019fe34f73ce17cea013ae1b98fd0"
|
||||
dependencies = [
|
||||
"ascii",
|
||||
"cfg-if 1.0.0",
|
||||
@@ -2144,7 +2302,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustpython-compiler-core"
|
||||
version = "0.1.2"
|
||||
source = "git+https://github.com/charliermarsh/RustPython.git?rev=1b253a12705f84972cd76e8dc1cdaaccb233e5a5#1b253a12705f84972cd76e8dc1cdaaccb233e5a5"
|
||||
source = "git+https://github.com/RustPython/RustPython.git?rev=77b821a1941019fe34f73ce17cea013ae1b98fd0#77b821a1941019fe34f73ce17cea013ae1b98fd0"
|
||||
dependencies = [
|
||||
"bincode",
|
||||
"bitflags",
|
||||
@@ -2161,7 +2319,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustpython-parser"
|
||||
version = "0.1.2"
|
||||
source = "git+https://github.com/charliermarsh/RustPython.git?rev=1b253a12705f84972cd76e8dc1cdaaccb233e5a5#1b253a12705f84972cd76e8dc1cdaaccb233e5a5"
|
||||
source = "git+https://github.com/RustPython/RustPython.git?rev=77b821a1941019fe34f73ce17cea013ae1b98fd0#77b821a1941019fe34f73ce17cea013ae1b98fd0"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"anyhow",
|
||||
@@ -2549,6 +2707,12 @@ dependencies = [
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "textwrap"
|
||||
version = "0.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d"
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "1.0.37"
|
||||
@@ -2589,6 +2753,16 @@ dependencies = [
|
||||
"crunchy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinytemplate"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinyvec"
|
||||
version = "1.6.0"
|
||||
|
||||
18
Cargo.toml
18
Cargo.toml
@@ -1,6 +1,11 @@
|
||||
[workspace]
|
||||
members = [
|
||||
"crates/flake8_to_ruff",
|
||||
]
|
||||
|
||||
[package]
|
||||
name = "ruff"
|
||||
version = "0.0.89"
|
||||
version = "0.0.94"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
@@ -26,9 +31,9 @@ once_cell = { version = "1.13.1" }
|
||||
path-absolutize = { version = "3.0.14", features = ["once_cell_cache", "use_unix_paths_on_wasm"] }
|
||||
rayon = { version = "1.5.3" }
|
||||
regex = { version = "1.6.0" }
|
||||
rustpython-ast = { features = ["unparse"], git = "https://github.com/charliermarsh/RustPython.git", rev = "1b253a12705f84972cd76e8dc1cdaaccb233e5a5" }
|
||||
rustpython-common = { git = "https://github.com/charliermarsh/RustPython.git", rev = "1b253a12705f84972cd76e8dc1cdaaccb233e5a5" }
|
||||
rustpython-parser = { features = ["lalrpop"], git = "https://github.com/charliermarsh/RustPython.git", rev = "1b253a12705f84972cd76e8dc1cdaaccb233e5a5" }
|
||||
rustpython-ast = { features = ["unparse"], git = "https://github.com/RustPython/RustPython.git", rev = "77b821a1941019fe34f73ce17cea013ae1b98fd0" }
|
||||
rustpython-common = { git = "https://github.com/RustPython/RustPython.git", rev = "77b821a1941019fe34f73ce17cea013ae1b98fd0" }
|
||||
rustpython-parser = { features = ["lalrpop"], git = "https://github.com/RustPython/RustPython.git", rev = "77b821a1941019fe34f73ce17cea013ae1b98fd0" }
|
||||
serde = { version = "1.0.143", features = ["derive"] }
|
||||
serde_json = { version = "1.0.83" }
|
||||
strum = { version = "0.24.1", features = ["strum_macros"] }
|
||||
@@ -51,6 +56,7 @@ getrandom = { version = "0.2.7", features = ["js"] }
|
||||
[dev-dependencies]
|
||||
assert_cmd = { version = "2.0.4" }
|
||||
codegen = { version = "0.2.0" }
|
||||
criterion = { version = "0.4.0" }
|
||||
insta = { version = "1.19.1", features = ["yaml"] }
|
||||
test-case = { version = "2.2.2" }
|
||||
|
||||
@@ -69,3 +75,7 @@ opt-level = 3
|
||||
|
||||
[profile.dev.package.similar]
|
||||
opt-level = 3
|
||||
|
||||
[[bench]]
|
||||
name = "source_code_locator"
|
||||
harness = false
|
||||
|
||||
39
README.md
39
README.md
@@ -38,13 +38,25 @@ Read the [launch blog post](https://notes.crmarsh.com/python-tooling-could-be-mu
|
||||
1. [Installation and Usage](#installation-and-usage)
|
||||
2. [Configuration](#configuration)
|
||||
3. [Supported Rules](#supported-rules)
|
||||
4. [Editor Integrations](#editor-integrations)
|
||||
5. [FAQ](#faq)
|
||||
6. [Development](#development)
|
||||
7. [Releases](#releases)
|
||||
8. [Benchmarks](#benchmarks)
|
||||
9. [License](#license)
|
||||
10. [Contributing](#contributing)
|
||||
1. [Pyflakes](#pyflakes)
|
||||
2. [pycodestyle (error)](#pycodestyle-error)
|
||||
3. [pycodestyle (warning)](#pycodestyle-warning)
|
||||
4. [pydocstyle](#pydocstyle)
|
||||
5. [pyupgrade](#pyupgrade)
|
||||
6. [pep8-naming](#pep8-naming)
|
||||
7. [flake8-comprehensions](#flake8-comprehensions)
|
||||
8. [flake8-bugbear](#flake8-bugbear)
|
||||
9. [flake8-builtins](#flake8-builtins)
|
||||
10. [flake8-print](#flake8-print)
|
||||
11. [flake8-quotes](#flake8-quotes)
|
||||
12. [Meta rules](#meta-rules)
|
||||
5. [Editor Integrations](#editor-integrations)
|
||||
6. [FAQ](#faq)
|
||||
7. [Development](#development)
|
||||
8. [Releases](#releases)
|
||||
9. [Benchmarks](#benchmarks)
|
||||
10. [License](#license)
|
||||
11. [Contributing](#contributing)
|
||||
|
||||
## Installation and Usage
|
||||
|
||||
@@ -77,7 +89,7 @@ Ruff also works with [pre-commit](https://pre-commit.com):
|
||||
```yaml
|
||||
repos:
|
||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||
rev: v0.0.89
|
||||
rev: v0.0.94
|
||||
hooks:
|
||||
- id: ruff
|
||||
```
|
||||
@@ -260,7 +272,7 @@ The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` com
|
||||
| F634 | IfTuple | If test is a tuple, which is always `True` | |
|
||||
| F701 | BreakOutsideLoop | `break` outside loop | |
|
||||
| F702 | ContinueOutsideLoop | `continue` not properly in loop | |
|
||||
| F704 | YieldOutsideFunction | `yield` or `yield from` statement outside of a function/method | |
|
||||
| F704 | YieldOutsideFunction | `yield` or `yield from` statement outside of a function | |
|
||||
| F706 | ReturnOutsideFunction | `return` statement outside of a function/method | |
|
||||
| F707 | DefaultExceptNotLast | An `except:` block as not the last exception handler | |
|
||||
| F722 | ForwardAnnotationSyntaxError | Syntax error in forward annotation: `...` | |
|
||||
@@ -329,7 +341,7 @@ The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` com
|
||||
| D400 | EndsInPeriod | First line should end with a period | |
|
||||
| D402 | NoSignature | First line should not be the function's signature | |
|
||||
| D403 | FirstLineCapitalized | First word of the first line should be properly capitalized | |
|
||||
| D404 | NoThisPrefix | First word of the docstring should not be `This` | |
|
||||
| D404 | NoThisPrefix | First word of the docstring should not be 'This' | |
|
||||
| D405 | CapitalizeSectionName | Section name should be properly capitalized ("returns") | 🛠 |
|
||||
| D406 | NewLineAfterSectionName | Section name should end with a newline ("Returns") | 🛠 |
|
||||
| D407 | DashedUnderlineAfterSection | Missing dashed underline after section ("Returns") | 🛠 |
|
||||
@@ -343,7 +355,7 @@ The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` com
|
||||
| D415 | EndsInPunctuation | First line should end with a period, question mark, or exclamation point | |
|
||||
| D416 | SectionNameEndsInColon | Section name should end with a colon ("Returns") | 🛠 |
|
||||
| D417 | DocumentAllArguments | Missing argument descriptions in the docstring: `x`, `y` | |
|
||||
| D418 | SkipDocstring | Function decorated with @overload shouldn't contain a docstring | |
|
||||
| D418 | SkipDocstring | Function decorated with `@overload` shouldn't contain a docstring | |
|
||||
| D419 | NonEmpty | Docstring is empty | |
|
||||
|
||||
### pyupgrade
|
||||
@@ -397,7 +409,7 @@ The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` com
|
||||
| C413 | UnnecessaryCallAroundSorted | Unnecessary `(list\|reversed)` call around `sorted()` | |
|
||||
| C414 | UnnecessaryDoubleCastOrProcess | Unnecessary `(list\|reversed\|set\|sorted\|tuple)` call within `(list\|set\|sorted\|tuple)()` | |
|
||||
| C415 | UnnecessarySubscriptReversal | Unnecessary subscript reversal of iterable within `(reversed\|set\|sorted)()` | |
|
||||
| C416 | UnnecessaryComprehension | Unnecessary `(list\|set)` comprehension (rewrite using `(list\|set)()`) | |
|
||||
| C416 | UnnecessaryComprehension | Unnecessary `(list\|set)` comprehension (rewrite using `(list\|set)()`) | |
|
||||
| C417 | UnnecessaryMap | Unnecessary `map` usage (rewrite using a `(list\|set\|dict)` comprehension) | |
|
||||
|
||||
### flake8-bugbear
|
||||
@@ -405,6 +417,7 @@ The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` com
|
||||
| Code | Name | Message | Fix |
|
||||
| ---- | ---- | ------- | --- |
|
||||
| B002 | UnaryPrefixIncrement | Python does not support the unary prefix increment. | |
|
||||
| B006 | MutableArgumentDefault | Do not use mutable data structures for argument defaults. | |
|
||||
| B007 | UnusedLoopControlVariable | Loop control variable `i` not used within the loop body. | 🛠 |
|
||||
| B011 | DoNotAssertFalse | Do not `assert False` (`python -O` removes these calls), raise `AssertionError()` | 🛠 |
|
||||
| B013 | RedundantTupleInExceptionHandler | A length-one tuple literal is redundant. Write `except ValueError:` instead of `except (ValueError,):`. | |
|
||||
@@ -532,7 +545,7 @@ Today, Ruff can be used to replace Flake8 when used with any of the following pl
|
||||
- [`flake8-print`](https://pypi.org/project/flake8-print/)
|
||||
- [`flake8-quotes`](https://pypi.org/project/flake8-quotes/)
|
||||
- [`flake8-comprehensions`](https://pypi.org/project/flake8-comprehensions/)
|
||||
- [`flake8-bugbear`](https://pypi.org/project/flake8-bugbear/) (9/32)
|
||||
- [`flake8-bugbear`](https://pypi.org/project/flake8-bugbear/) (10/32)
|
||||
|
||||
Ruff also implements the functionality that you get from [`yesqa`](https://github.com/asottile/yesqa),
|
||||
and a subset of the rules implemented in [`pyupgrade`](https://pypi.org/project/pyupgrade/) (8/34).
|
||||
|
||||
16
benches/source_code_locator.rs
Normal file
16
benches/source_code_locator.rs
Normal file
@@ -0,0 +1,16 @@
|
||||
use std::path::Path;
|
||||
|
||||
use criterion::{black_box, criterion_group, criterion_main, Criterion};
|
||||
|
||||
use ruff::fs;
|
||||
use ruff::source_code_locator::compute_offsets;
|
||||
|
||||
fn criterion_benchmark(c: &mut Criterion) {
|
||||
let contents = fs::read_file(Path::new("resources/test/fixtures/D.py")).unwrap();
|
||||
c.bench_function("compute_offsets", |b| {
|
||||
b.iter(|| compute_offsets(black_box(&contents)))
|
||||
});
|
||||
}
|
||||
|
||||
criterion_group!(benches, criterion_benchmark);
|
||||
criterion_main!(benches);
|
||||
2964
crates/flake8_to_ruff/Cargo.lock
generated
Normal file
2964
crates/flake8_to_ruff/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
22
crates/flake8_to_ruff/Cargo.toml
Normal file
22
crates/flake8_to_ruff/Cargo.toml
Normal file
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "flake8-to-ruff"
|
||||
version = "0.0.94-dev.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
name = "flake8_to_ruff"
|
||||
|
||||
[dependencies]
|
||||
anyhow = { version = "1.0.60" }
|
||||
clap = { version = "4.0.1", features = ["derive"] }
|
||||
configparser = { version = "3.0.2" }
|
||||
once_cell = { version = "1.13.1" }
|
||||
regex = { version = "1.6.0" }
|
||||
ruff = { path = "../..", default-features = false }
|
||||
serde = { version = "1.0.143", features = ["derive"] }
|
||||
serde_json = { version = "1.0.83" }
|
||||
toml = { version = "0.5.9" }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
[features]
|
||||
47
crates/flake8_to_ruff/README.md
Normal file
47
crates/flake8_to_ruff/README.md
Normal file
@@ -0,0 +1,47 @@
|
||||
# flake8-to-ruff
|
||||
|
||||
Convert existing Flake8 configuration files (`setup.cfg`, `tox.ini`, or `.flake8`) for use with
|
||||
[Ruff](https://github.com/charliermarsh/ruff).
|
||||
|
||||
Generates a Ruff-compatible `pyproject.toml` section.
|
||||
|
||||
## Installation and Usage
|
||||
|
||||
### Installation
|
||||
|
||||
Available as [`flake8-to-ruff`](https://pypi.org/project/flake8-to-ruff/) on PyPI:
|
||||
|
||||
```shell
|
||||
pip install flake8-to-ruff
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
To run Ruff, try any of the following:
|
||||
|
||||
```shell
|
||||
flake8-to-ruff path/to/setup.cfg
|
||||
flake8-to-ruff path/to/tox.ini
|
||||
flake8-to-ruff path/to/.flake8
|
||||
```
|
||||
|
||||
## Limitations
|
||||
|
||||
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
|
||||
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.)
|
||||
3. `flake8-to-ruff` does not auto-detect your Flake8 plugins, so any reliance on Flake8 plugins that
|
||||
implicitly enable third-party checks will be ignored. Instead, add those error codes to your
|
||||
`select` or `extend-select` fields, so that `flake8-to-ruff` can pick them up.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are welcome and hugely appreciated. To get started, check out the
|
||||
[contributing guidelines](https://github.com/charliermarsh/ruff/blob/main/CONTRIBUTING.md).
|
||||
33
crates/flake8_to_ruff/pyproject.toml
Normal file
33
crates/flake8_to_ruff/pyproject.toml
Normal file
@@ -0,0 +1,33 @@
|
||||
[project]
|
||||
name = "flake8-to-ruff"
|
||||
keywords = ["automation", "flake8", "pycodestyle", "pyflakes", "pylint", "clippy"]
|
||||
classifiers = [
|
||||
"Development Status :: 3 - Alpha",
|
||||
"Environment :: Console",
|
||||
"Intended Audience :: Developers",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python",
|
||||
"Programming Language :: Python :: 3.7",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3 :: Only",
|
||||
"Topic :: Software Development :: Libraries :: Python Modules",
|
||||
"Topic :: Software Development :: Quality Assurance",
|
||||
]
|
||||
author = "Charlie Marsh"
|
||||
author_email = "charlie.r.marsh@gmail.com"
|
||||
description = "Convert existing Flake8 configuration to Ruff."
|
||||
requires-python = ">=3.7"
|
||||
|
||||
[project.urls]
|
||||
repository = "https://github.com/charliermarsh/ruff#subdirectory=crates/flake8_to_ruff"
|
||||
|
||||
[build-system]
|
||||
requires = ["maturin>=0.13,<0.14"]
|
||||
build-backend = "maturin"
|
||||
|
||||
[tool.maturin]
|
||||
bindings = "bin"
|
||||
strip = true
|
||||
59
crates/flake8_to_ruff/src/converter.rs
Normal file
59
crates/flake8_to_ruff/src/converter.rs
Normal file
@@ -0,0 +1,59 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use anyhow::Result;
|
||||
|
||||
use ruff::settings::options::Options;
|
||||
use ruff::settings::pyproject::Pyproject;
|
||||
|
||||
use crate::parser;
|
||||
|
||||
pub fn convert(config: HashMap<String, HashMap<String, Option<String>>>) -> Result<Pyproject> {
|
||||
// Extract the Flake8 section.
|
||||
let flake8 = config
|
||||
.get("flake8")
|
||||
.expect("Unable to find flake8 section in INI file.");
|
||||
|
||||
// Parse each supported option.
|
||||
let mut options: Options = Default::default();
|
||||
for (key, value) in flake8 {
|
||||
if let Some(value) = value {
|
||||
match key.as_str() {
|
||||
"line-length" | "line_length" => match value.clone().parse::<usize>() {
|
||||
Ok(line_length) => options.line_length = Some(line_length),
|
||||
Err(e) => eprintln!("Unable to parse '{key}' property: {e}"),
|
||||
},
|
||||
"select" => {
|
||||
options.select = Some(parser::parse_prefix_codes(value.as_ref()));
|
||||
}
|
||||
"extend-select" | "extend_select" => {
|
||||
options.extend_select = Some(parser::parse_prefix_codes(value.as_ref()));
|
||||
}
|
||||
"ignore" => {
|
||||
options.ignore = Some(parser::parse_prefix_codes(value.as_ref()));
|
||||
}
|
||||
"extend-ignore" | "extend_ignore" => {
|
||||
options.extend_ignore = Some(parser::parse_prefix_codes(value.as_ref()));
|
||||
}
|
||||
"exclude" => {
|
||||
options.exclude = Some(parser::parse_strings(value.as_ref()));
|
||||
}
|
||||
"extend-exclude" | "extend_exclude" => {
|
||||
options.extend_exclude = Some(parser::parse_strings(value.as_ref()));
|
||||
}
|
||||
"per-file-ignores" | "per_file_ignores" => {
|
||||
match parser::parse_files_to_codes_mapping(value.as_ref()) {
|
||||
Ok(per_file_ignores) => {
|
||||
options.per_file_ignores =
|
||||
Some(parser::collect_per_file_ignores(per_file_ignores))
|
||||
}
|
||||
Err(e) => eprintln!("Unable to parse '{key}' property: {e}"),
|
||||
}
|
||||
}
|
||||
_ => eprintln!("Skipping unsupported property: {key}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create the pyproject.toml.
|
||||
Ok(Pyproject::new(options))
|
||||
}
|
||||
4
crates/flake8_to_ruff/src/lib.rs
Normal file
4
crates/flake8_to_ruff/src/lib.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
#![allow(clippy::collapsible_if, clippy::collapsible_else_if)]
|
||||
|
||||
pub mod converter;
|
||||
mod parser;
|
||||
35
crates/flake8_to_ruff/src/main.rs
Normal file
35
crates/flake8_to_ruff/src/main.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
//! Utility to generate Ruff's pyproject.toml section from a Flake8 INI file.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::Parser;
|
||||
use configparser::ini::Ini;
|
||||
|
||||
use flake8_to_ruff::converter;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
about = "Convert existing Flake8 configuration to Ruff.",
|
||||
long_about = None
|
||||
)]
|
||||
struct Cli {
|
||||
/// Path to the Flake8 configuration file (e.g., 'setup.cfg', 'tox.ini', or '.flake8').
|
||||
#[arg(required = true)]
|
||||
file: PathBuf,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
|
||||
// Read the INI file.
|
||||
let mut ini = Ini::new_cs();
|
||||
ini.set_multiline(true);
|
||||
let config = ini.load(cli.file).map_err(|msg| anyhow::anyhow!(msg))?;
|
||||
|
||||
// Create the pyproject.toml.
|
||||
let pyproject = converter::convert(config)?;
|
||||
println!("{}", toml::to_string_pretty(&pyproject)?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
374
crates/flake8_to_ruff/src/parser.rs
Normal file
374
crates/flake8_to_ruff/src/parser.rs
Normal file
@@ -0,0 +1,374 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::str::FromStr;
|
||||
|
||||
use anyhow::Result;
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
|
||||
use ruff::checks_gen::CheckCodePrefix;
|
||||
use ruff::settings::types::PatternPrefixPair;
|
||||
|
||||
static COMMA_SEPARATED_LIST_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"[,\s]").unwrap());
|
||||
|
||||
/// Parse a comma-separated list of `CheckCodePrefix` values (e.g., "F401,E501").
|
||||
pub fn parse_prefix_codes(value: &str) -> Vec<CheckCodePrefix> {
|
||||
let mut codes: Vec<CheckCodePrefix> = vec![];
|
||||
for code in COMMA_SEPARATED_LIST_RE.split(value) {
|
||||
let code = code.trim();
|
||||
if code.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Ok(code) = CheckCodePrefix::from_str(code) {
|
||||
codes.push(code);
|
||||
} else {
|
||||
eprintln!("Unsupported prefix code: {code}");
|
||||
}
|
||||
}
|
||||
codes
|
||||
}
|
||||
|
||||
/// Parse a comma-separated list of strings (e.g., "__init__.py,__main__.py").
|
||||
pub fn parse_strings(value: &str) -> Vec<String> {
|
||||
COMMA_SEPARATED_LIST_RE
|
||||
.split(value)
|
||||
.map(|part| part.trim())
|
||||
.filter(|part| !part.is_empty())
|
||||
.map(String::from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Token {
|
||||
token_name: TokenType,
|
||||
src: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum TokenType {
|
||||
Code,
|
||||
File,
|
||||
Colon,
|
||||
Comma,
|
||||
Ws,
|
||||
Eof,
|
||||
}
|
||||
|
||||
struct State {
|
||||
seen_sep: bool,
|
||||
seen_colon: bool,
|
||||
filenames: Vec<String>,
|
||||
codes: Vec<String>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
seen_sep: true,
|
||||
seen_colon: false,
|
||||
filenames: vec![],
|
||||
codes: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate the list of `StrCheckCodePair` pairs for the current state.
|
||||
fn parse(&self) -> Vec<PatternPrefixPair> {
|
||||
let mut codes: Vec<PatternPrefixPair> = vec![];
|
||||
for code in &self.codes {
|
||||
match CheckCodePrefix::from_str(code) {
|
||||
Ok(code) => {
|
||||
for filename in &self.filenames {
|
||||
codes.push(PatternPrefixPair {
|
||||
pattern: filename.clone(),
|
||||
prefix: code.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(_) => eprintln!("Skipping unrecognized prefix: {}", code),
|
||||
}
|
||||
}
|
||||
codes
|
||||
}
|
||||
}
|
||||
|
||||
/// Tokenize the raw 'files-to-codes' mapping.
|
||||
fn tokenize_files_to_codes_mapping(value: &str) -> Vec<Token> {
|
||||
let mut tokens = vec![];
|
||||
let mut i = 0;
|
||||
while i < value.len() {
|
||||
for (token_re, token_name) in [
|
||||
(
|
||||
Regex::new(r"([A-Z]+[0-9]*)(?:$|\s|,)").unwrap(),
|
||||
TokenType::Code,
|
||||
),
|
||||
(Regex::new(r"([^\s:,]+)").unwrap(), TokenType::File),
|
||||
(Regex::new(r"(\s*:\s*)").unwrap(), TokenType::Colon),
|
||||
(Regex::new(r"(\s*,\s*)").unwrap(), TokenType::Comma),
|
||||
(Regex::new(r"(\s+)").unwrap(), TokenType::Ws),
|
||||
] {
|
||||
if let Some(cap) = token_re.captures(&value[i..]) {
|
||||
let mat = cap.get(1).unwrap();
|
||||
if mat.start() == 0 {
|
||||
tokens.push(Token {
|
||||
token_name,
|
||||
src: mat.as_str().to_string().trim().to_string(),
|
||||
});
|
||||
i += mat.end();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tokens.push(Token {
|
||||
token_name: TokenType::Eof,
|
||||
src: "".to_string(),
|
||||
});
|
||||
tokens
|
||||
}
|
||||
|
||||
/// Parse a 'files-to-codes' mapping, mimicking Flake8's internal logic.
|
||||
///
|
||||
/// See: https://github.com/PyCQA/flake8/blob/7dfe99616fc2f07c0017df2ba5fa884158f3ea8a/src/flake8/utils.py#L45
|
||||
pub fn parse_files_to_codes_mapping(value: &str) -> Result<Vec<PatternPrefixPair>> {
|
||||
if value.trim().is_empty() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let mut codes: Vec<PatternPrefixPair> = vec![];
|
||||
let mut state = State::new();
|
||||
for token in tokenize_files_to_codes_mapping(value) {
|
||||
if matches!(token.token_name, TokenType::Comma | TokenType::Ws) {
|
||||
state.seen_sep = true;
|
||||
} else if !state.seen_colon {
|
||||
if matches!(token.token_name, TokenType::Colon) {
|
||||
state.seen_colon = true;
|
||||
state.seen_sep = true;
|
||||
} else if state.seen_sep && matches!(token.token_name, TokenType::File) {
|
||||
state.filenames.push(token.src);
|
||||
state.seen_sep = false;
|
||||
} else {
|
||||
return Err(anyhow::anyhow!("Unexpected token: {:?}", token.token_name));
|
||||
}
|
||||
} else {
|
||||
if matches!(token.token_name, TokenType::Eof) {
|
||||
codes.extend(state.parse());
|
||||
state = State::new();
|
||||
} else if state.seen_sep && matches!(token.token_name, TokenType::Code) {
|
||||
state.codes.push(token.src);
|
||||
state.seen_sep = false;
|
||||
} else if state.seen_sep && matches!(token.token_name, TokenType::File) {
|
||||
codes.extend(state.parse());
|
||||
state = State::new();
|
||||
state.filenames.push(token.src);
|
||||
state.seen_sep = false;
|
||||
} else {
|
||||
return Err(anyhow::anyhow!("Unexpected token: {:?}", token.token_name));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(codes)
|
||||
}
|
||||
|
||||
/// Collect a list of `PatternPrefixPair` structs as a `BTreeMap`.
|
||||
pub fn collect_per_file_ignores(
|
||||
pairs: Vec<PatternPrefixPair>,
|
||||
) -> BTreeMap<String, Vec<CheckCodePrefix>> {
|
||||
let mut per_file_ignores: BTreeMap<String, Vec<CheckCodePrefix>> = BTreeMap::new();
|
||||
for pair in pairs {
|
||||
per_file_ignores
|
||||
.entry(pair.pattern)
|
||||
.or_insert_with(Vec::new)
|
||||
.push(pair.prefix);
|
||||
}
|
||||
per_file_ignores
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use anyhow::Result;
|
||||
|
||||
use ruff::checks_gen::CheckCodePrefix;
|
||||
use ruff::settings::types::PatternPrefixPair;
|
||||
|
||||
use crate::parser::{parse_files_to_codes_mapping, parse_prefix_codes, parse_strings};
|
||||
|
||||
#[test]
|
||||
fn it_parses_prefix_codes() {
|
||||
let actual = parse_prefix_codes("");
|
||||
let expected: Vec<CheckCodePrefix> = vec![];
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
let actual = parse_prefix_codes(" ");
|
||||
let expected: Vec<CheckCodePrefix> = vec![];
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
let actual = parse_prefix_codes("F401");
|
||||
let expected = vec![CheckCodePrefix::F401];
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
let actual = parse_prefix_codes("F401,");
|
||||
let expected = vec![CheckCodePrefix::F401];
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
let actual = parse_prefix_codes("F401,E501");
|
||||
let expected = vec![CheckCodePrefix::F401, CheckCodePrefix::E501];
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
let actual = parse_prefix_codes("F401, E501");
|
||||
let expected = vec![CheckCodePrefix::F401, CheckCodePrefix::E501];
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_parses_strings() {
|
||||
let actual = parse_strings("");
|
||||
let expected: Vec<String> = vec![];
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
let actual = parse_strings(" ");
|
||||
let expected: Vec<String> = vec![];
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
let actual = parse_strings("__init__.py");
|
||||
let expected = vec!["__init__.py".to_string()];
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
let actual = parse_strings("__init__.py,");
|
||||
let expected = vec!["__init__.py".to_string()];
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
let actual = parse_strings("__init__.py,__main__.py");
|
||||
let expected = vec!["__init__.py".to_string(), "__main__.py".to_string()];
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
let actual = parse_strings("__init__.py, __main__.py");
|
||||
let expected = vec!["__init__.py".to_string(), "__main__.py".to_string()];
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_parse_files_to_codes_mapping() -> Result<()> {
|
||||
let actual = parse_files_to_codes_mapping("")?;
|
||||
let expected: Vec<PatternPrefixPair> = vec![];
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
let actual = parse_files_to_codes_mapping(" ")?;
|
||||
let expected: Vec<PatternPrefixPair> = vec![];
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
// Ex) locust
|
||||
let actual = parse_files_to_codes_mapping(
|
||||
"per-file-ignores =
|
||||
locust/test/*: F841
|
||||
examples/*: F841
|
||||
*.pyi: E302,E704"
|
||||
.strip_prefix("per-file-ignores =")
|
||||
.unwrap(),
|
||||
)?;
|
||||
let expected: Vec<PatternPrefixPair> = vec![
|
||||
PatternPrefixPair {
|
||||
pattern: "locust/test/*".to_string(),
|
||||
prefix: CheckCodePrefix::F841,
|
||||
},
|
||||
PatternPrefixPair {
|
||||
pattern: "examples/*".to_string(),
|
||||
prefix: CheckCodePrefix::F841,
|
||||
},
|
||||
];
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
// Ex) celery
|
||||
let actual = parse_files_to_codes_mapping(
|
||||
"per-file-ignores =
|
||||
t/*,setup.py,examples/*,docs/*,extra/*:
|
||||
D,"
|
||||
.strip_prefix("per-file-ignores =")
|
||||
.unwrap(),
|
||||
)?;
|
||||
let expected: Vec<PatternPrefixPair> = vec![
|
||||
PatternPrefixPair {
|
||||
pattern: "t/*".to_string(),
|
||||
prefix: CheckCodePrefix::D,
|
||||
},
|
||||
PatternPrefixPair {
|
||||
pattern: "setup.py".to_string(),
|
||||
prefix: CheckCodePrefix::D,
|
||||
},
|
||||
PatternPrefixPair {
|
||||
pattern: "examples/*".to_string(),
|
||||
prefix: CheckCodePrefix::D,
|
||||
},
|
||||
PatternPrefixPair {
|
||||
pattern: "docs/*".to_string(),
|
||||
prefix: CheckCodePrefix::D,
|
||||
},
|
||||
PatternPrefixPair {
|
||||
pattern: "extra/*".to_string(),
|
||||
prefix: CheckCodePrefix::D,
|
||||
},
|
||||
];
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
// Ex) scrapy
|
||||
let actual = parse_files_to_codes_mapping(
|
||||
"per-file-ignores =
|
||||
scrapy/__init__.py:E402
|
||||
scrapy/core/downloader/handlers/http.py:F401
|
||||
scrapy/http/__init__.py:F401
|
||||
scrapy/linkextractors/__init__.py:E402,F401
|
||||
scrapy/selector/__init__.py:F401
|
||||
scrapy/spiders/__init__.py:E402,F401
|
||||
scrapy/utils/url.py:F403,F405
|
||||
tests/test_loader.py:E741"
|
||||
.strip_prefix("per-file-ignores =")
|
||||
.unwrap(),
|
||||
)?;
|
||||
let expected: Vec<PatternPrefixPair> = vec![
|
||||
PatternPrefixPair {
|
||||
pattern: "scrapy/__init__.py".to_string(),
|
||||
prefix: CheckCodePrefix::E402,
|
||||
},
|
||||
PatternPrefixPair {
|
||||
pattern: "scrapy/core/downloader/handlers/http.py".to_string(),
|
||||
prefix: CheckCodePrefix::F401,
|
||||
},
|
||||
PatternPrefixPair {
|
||||
pattern: "scrapy/http/__init__.py".to_string(),
|
||||
prefix: CheckCodePrefix::F401,
|
||||
},
|
||||
PatternPrefixPair {
|
||||
pattern: "scrapy/linkextractors/__init__.py".to_string(),
|
||||
prefix: CheckCodePrefix::E402,
|
||||
},
|
||||
PatternPrefixPair {
|
||||
pattern: "scrapy/linkextractors/__init__.py".to_string(),
|
||||
prefix: CheckCodePrefix::F401,
|
||||
},
|
||||
PatternPrefixPair {
|
||||
pattern: "scrapy/selector/__init__.py".to_string(),
|
||||
prefix: CheckCodePrefix::F401,
|
||||
},
|
||||
PatternPrefixPair {
|
||||
pattern: "scrapy/spiders/__init__.py".to_string(),
|
||||
prefix: CheckCodePrefix::E402,
|
||||
},
|
||||
PatternPrefixPair {
|
||||
pattern: "scrapy/spiders/__init__.py".to_string(),
|
||||
prefix: CheckCodePrefix::F401,
|
||||
},
|
||||
PatternPrefixPair {
|
||||
pattern: "scrapy/utils/url.py".to_string(),
|
||||
prefix: CheckCodePrefix::F403,
|
||||
},
|
||||
PatternPrefixPair {
|
||||
pattern: "scrapy/utils/url.py".to_string(),
|
||||
prefix: CheckCodePrefix::F405,
|
||||
},
|
||||
PatternPrefixPair {
|
||||
pattern: "tests/test_loader.py".to_string(),
|
||||
prefix: CheckCodePrefix::E741,
|
||||
},
|
||||
];
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -96,7 +96,7 @@ fn main() {
|
||||
|
||||
println!("//! File automatically generated by examples/generate_check_code_prefix.rs.");
|
||||
println!();
|
||||
println!("use serde::{{Deserialize, Serialize}};");
|
||||
println!("use serde::{{Serialize, Deserialize}};");
|
||||
println!("use strum_macros::EnumString;");
|
||||
println!();
|
||||
println!("use crate::checks::CheckCode;");
|
||||
|
||||
187
resources/test/fixtures/B006_B008.py
vendored
Normal file
187
resources/test/fixtures/B006_B008.py
vendored
Normal file
@@ -0,0 +1,187 @@
|
||||
import collections
|
||||
import datetime as dt
|
||||
import logging
|
||||
import operator
|
||||
import random
|
||||
import re
|
||||
import time
|
||||
import types
|
||||
from operator import attrgetter, itemgetter, methodcaller
|
||||
from types import MappingProxyType
|
||||
|
||||
|
||||
# B006
|
||||
# Allow immutable literals/calls/comprehensions
|
||||
def this_is_okay(value=(1, 2, 3)):
|
||||
...
|
||||
|
||||
|
||||
async def and_this_also(value=tuple()):
|
||||
pass
|
||||
|
||||
|
||||
def frozenset_also_okay(value=frozenset()):
|
||||
pass
|
||||
|
||||
|
||||
def mappingproxytype_okay(
|
||||
value=MappingProxyType({}), value2=types.MappingProxyType({})
|
||||
):
|
||||
pass
|
||||
|
||||
|
||||
def re_compile_ok(value=re.compile("foo")):
|
||||
pass
|
||||
|
||||
|
||||
def operators_ok(
|
||||
v=operator.attrgetter("foo"),
|
||||
v2=operator.itemgetter("foo"),
|
||||
v3=operator.methodcaller("foo"),
|
||||
):
|
||||
pass
|
||||
|
||||
|
||||
def operators_ok_unqualified(
|
||||
v=attrgetter("foo"),
|
||||
v2=itemgetter("foo"),
|
||||
v3=methodcaller("foo"),
|
||||
):
|
||||
pass
|
||||
|
||||
|
||||
def kwonlyargs_immutable(*, value=()):
|
||||
...
|
||||
|
||||
|
||||
# Flag mutable literals/comprehensions
|
||||
|
||||
|
||||
def this_is_wrong(value=[1, 2, 3]):
|
||||
...
|
||||
|
||||
|
||||
def this_is_also_wrong(value={}):
|
||||
...
|
||||
|
||||
|
||||
def and_this(value=set()):
|
||||
...
|
||||
|
||||
|
||||
def this_too(value=collections.OrderedDict()):
|
||||
...
|
||||
|
||||
|
||||
async def async_this_too(value=collections.defaultdict()):
|
||||
...
|
||||
|
||||
|
||||
def dont_forget_me(value=collections.deque()):
|
||||
...
|
||||
|
||||
|
||||
# N.B. we're also flagging the function call in the comprehension
|
||||
def list_comprehension_also_not_okay(default=[i**2 for i in range(3)]):
|
||||
pass
|
||||
|
||||
|
||||
def dict_comprehension_also_not_okay(default={i: i**2 for i in range(3)}):
|
||||
pass
|
||||
|
||||
|
||||
def set_comprehension_also_not_okay(default={i**2 for i in range(3)}):
|
||||
pass
|
||||
|
||||
|
||||
def kwonlyargs_mutable(*, value=[]):
|
||||
...
|
||||
|
||||
|
||||
# Recommended approach for mutable defaults
|
||||
def do_this_instead(value=None):
|
||||
if value is None:
|
||||
value = set()
|
||||
|
||||
|
||||
# B008
|
||||
# Flag function calls as default args (including if they are part of a sub-expression)
|
||||
def in_fact_all_calls_are_wrong(value=time.time()):
|
||||
...
|
||||
|
||||
|
||||
def f(when=dt.datetime.now() + dt.timedelta(days=7)):
|
||||
pass
|
||||
|
||||
|
||||
def can_even_catch_lambdas(a=(lambda x: x)()):
|
||||
...
|
||||
|
||||
|
||||
# Recommended approach for function calls as default args
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def do_this_instead_of_calls_in_defaults(logger=LOGGER):
|
||||
# That makes it more obvious that this one value is reused.
|
||||
...
|
||||
|
||||
|
||||
# Handle inf/infinity/nan special case
|
||||
def float_inf_okay(value=float("inf")):
|
||||
pass
|
||||
|
||||
|
||||
def float_infinity_okay(value=float("infinity")):
|
||||
pass
|
||||
|
||||
|
||||
def float_plus_infinity_okay(value=float("+infinity")):
|
||||
pass
|
||||
|
||||
|
||||
def float_minus_inf_okay(value=float("-inf")):
|
||||
pass
|
||||
|
||||
|
||||
def float_nan_okay(value=float("nan")):
|
||||
pass
|
||||
|
||||
|
||||
def float_minus_NaN_okay(value=float("-NaN")):
|
||||
pass
|
||||
|
||||
|
||||
def float_infinity_literal(value=float("1e999")):
|
||||
pass
|
||||
|
||||
|
||||
# But don't allow standard floats
|
||||
def float_int_is_wrong(value=float(3)):
|
||||
pass
|
||||
|
||||
|
||||
def float_str_not_inf_or_nan_is_wrong(value=float("3.14")):
|
||||
pass
|
||||
|
||||
|
||||
# B006 and B008
|
||||
# We should handle arbitrary nesting of these B008.
|
||||
def nested_combo(a=[float(3), dt.datetime.now()]):
|
||||
pass
|
||||
|
||||
|
||||
# Don't flag nested B006 since we can't guarantee that
|
||||
# it isn't made mutable by the outer operation.
|
||||
def no_nested_b006(a=map(lambda s: s.upper(), ["a", "b", "c"])):
|
||||
pass
|
||||
|
||||
|
||||
# B008-ception.
|
||||
def nested_b008(a=random.randint(0, dt.datetime.now().year)):
|
||||
pass
|
||||
|
||||
|
||||
# Ignore lambda contents since they are evaluated at call time.
|
||||
def foo(f=lambda x: print(x)):
|
||||
f(1)
|
||||
3
resources/test/fixtures/C402.py
vendored
3
resources/test/fixtures/C402.py
vendored
@@ -1 +1,2 @@
|
||||
d = dict((x, x) for x in range(3))
|
||||
dict((x, x) for x in range(3))
|
||||
dict(((x, x) for x in range(3)), z=3)
|
||||
|
||||
3
resources/test/fixtures/C404.py
vendored
3
resources/test/fixtures/C404.py
vendored
@@ -1 +1,2 @@
|
||||
d = dict([(i, i) for i in range(3)])
|
||||
dict([(i, i) for i in range(3)])
|
||||
dict([(i, i) for i in range(3)], z=4)
|
||||
|
||||
30
resources/test/fixtures/F821_1.py
vendored
Normal file
30
resources/test/fixtures/F821_1.py
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
"""Test: typing module imports."""
|
||||
from foo import cast
|
||||
|
||||
# OK
|
||||
x = cast("Model")
|
||||
|
||||
from typing import cast
|
||||
|
||||
|
||||
# F821 Undefined name `Model`
|
||||
x = cast("Model", x)
|
||||
|
||||
|
||||
import typing
|
||||
|
||||
|
||||
# F821 Undefined name `Model`
|
||||
x = typing.cast("Model", x)
|
||||
|
||||
|
||||
from typing import Pattern
|
||||
|
||||
# F821 Undefined name `Model`
|
||||
x = Pattern["Model"]
|
||||
|
||||
|
||||
from typing.re import Match
|
||||
|
||||
# F821 Undefined name `Model`
|
||||
x = Match["Model"]
|
||||
32
resources/test/fixtures/pyproject.toml
vendored
32
resources/test/fixtures/pyproject.toml
vendored
@@ -1,16 +1,36 @@
|
||||
[tool.ruff]
|
||||
line-length = 88
|
||||
extend-exclude = [
|
||||
"excluded.py",
|
||||
"migrations",
|
||||
"directory/also_excluded.py",
|
||||
]
|
||||
per-file-ignores = [
|
||||
"__init__.py:F401",
|
||||
"excluded.py",
|
||||
"migrations",
|
||||
"directory/also_excluded.py",
|
||||
]
|
||||
per-file-ignores = { "__init__.py" = ["F401"] }
|
||||
|
||||
[tool.ruff.flake8-quotes]
|
||||
inline-quotes = "single"
|
||||
multiline-quotes = "double"
|
||||
docstring-quotes = "double"
|
||||
avoid-escape = true
|
||||
|
||||
[tool.ruff.pep8-naming]
|
||||
ignore-names = [
|
||||
"setUp",
|
||||
"tearDown",
|
||||
"setUpClass",
|
||||
"tearDownClass",
|
||||
"setUpModule",
|
||||
"tearDownModule",
|
||||
"asyncSetUp",
|
||||
"asyncTearDown",
|
||||
"setUpTestData",
|
||||
"failureException",
|
||||
"longMessage",
|
||||
"maxDiff",
|
||||
]
|
||||
classmethod-decorators = [
|
||||
"classmethod",
|
||||
]
|
||||
staticmethod-decorators = [
|
||||
"staticmethod",
|
||||
]
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
use rustpython_ast::{Excepthandler, ExcepthandlerKind, Expr, ExprKind, Location, StmtKind};
|
||||
|
||||
use crate::python::typing;
|
||||
|
||||
fn compose_call_path_inner<'a>(expr: &'a Expr, parts: &mut Vec<&'a str>) {
|
||||
match &expr.node {
|
||||
ExprKind::Call { func, .. } => {
|
||||
@@ -30,6 +30,7 @@ pub fn compose_call_path(expr: &Expr) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Return `true` if the `Expr` is a name or attribute reference to `${target}`.
|
||||
pub fn match_name_or_attr(expr: &Expr, target: &str) -> bool {
|
||||
match &expr.node {
|
||||
ExprKind::Attribute { attr, .. } => target == attr,
|
||||
@@ -38,32 +39,27 @@ pub fn match_name_or_attr(expr: &Expr, target: &str) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
pub enum SubscriptKind {
|
||||
AnnotatedSubscript,
|
||||
PEP593AnnotatedSubscript,
|
||||
}
|
||||
|
||||
pub fn match_annotated_subscript(expr: &Expr) -> Option<SubscriptKind> {
|
||||
/// Return `true` if the `Expr` is a reference to `${module}.${target}`.
|
||||
///
|
||||
/// Useful for, e.g., ensuring that a `Union` reference represents `typing.Union`.
|
||||
pub fn match_name_or_attr_from_module(
|
||||
expr: &Expr,
|
||||
target: &str,
|
||||
module: &str,
|
||||
imports: Option<&BTreeSet<&str>>,
|
||||
) -> bool {
|
||||
match &expr.node {
|
||||
ExprKind::Attribute { attr, .. } => {
|
||||
if typing::is_annotated_subscript(attr) {
|
||||
Some(SubscriptKind::AnnotatedSubscript)
|
||||
} else if typing::is_pep593_annotated_subscript(attr) {
|
||||
Some(SubscriptKind::PEP593AnnotatedSubscript)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
ExprKind::Attribute { value, attr, .. } => match &value.node {
|
||||
ExprKind::Name { id, .. } => id == module && target == attr,
|
||||
_ => false,
|
||||
},
|
||||
ExprKind::Name { id, .. } => {
|
||||
if typing::is_annotated_subscript(id) {
|
||||
Some(SubscriptKind::AnnotatedSubscript)
|
||||
} else if typing::is_pep593_annotated_subscript(id) {
|
||||
Some(SubscriptKind::PEP593AnnotatedSubscript)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
target == id
|
||||
&& imports
|
||||
.map(|imports| imports.contains(&id.as_str()))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
_ => None,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,7 +133,7 @@ pub fn to_absolute(relative: &Location, base: &Location) -> Location {
|
||||
if relative.row() == 1 {
|
||||
Location::new(
|
||||
relative.row() + base.row() - 1,
|
||||
relative.column() + base.column() - 1,
|
||||
relative.column() + base.column(),
|
||||
)
|
||||
} else {
|
||||
Location::new(relative.row() + base.row() - 1, relative.column())
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use rustpython_parser::ast::{Constant, Expr, ExprKind, Location, Stmt, StmtKind};
|
||||
use rustpython_parser::ast::{Constant, Expr, ExprKind, Stmt, StmtKind};
|
||||
|
||||
use crate::ast::types::{BindingKind, Range, Scope};
|
||||
use crate::ast::types::{BindingKind, Scope};
|
||||
|
||||
/// Extract the names bound to a given __all__ assignment.
|
||||
pub fn extract_all_names(stmt: &Stmt, scope: &Scope) -> Vec<String> {
|
||||
@@ -117,82 +117,3 @@ pub fn is_unpacking_assignment(stmt: &Stmt) -> bool {
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Struct used to efficiently slice source code at (row, column) Locations.
|
||||
pub struct SourceCodeLocator<'a> {
|
||||
content: &'a str,
|
||||
offsets: Vec<Vec<usize>>,
|
||||
}
|
||||
|
||||
impl<'a> SourceCodeLocator<'a> {
|
||||
pub fn new(content: &'a str) -> Self {
|
||||
SourceCodeLocator {
|
||||
content,
|
||||
offsets: Self::compute_offsets(content),
|
||||
}
|
||||
}
|
||||
|
||||
fn compute_offsets(content: &str) -> Vec<Vec<usize>> {
|
||||
let mut offsets = vec![];
|
||||
let mut offset = 0;
|
||||
for line in content.lines() {
|
||||
let mut newline = 0;
|
||||
let mut line_offsets: Vec<usize> = vec![];
|
||||
for (i, char) in line.char_indices() {
|
||||
line_offsets.push(offset + i);
|
||||
newline = i + char.len_utf8();
|
||||
}
|
||||
line_offsets.push(offset + newline);
|
||||
offsets.push(line_offsets);
|
||||
offset += newline + 1;
|
||||
}
|
||||
offsets.push(vec![offset]);
|
||||
offsets
|
||||
}
|
||||
|
||||
pub fn slice_source_code_at(&self, location: &Location) -> &'a str {
|
||||
let offset = self.offsets[location.row() - 1][location.column() - 1];
|
||||
&self.content[offset..]
|
||||
}
|
||||
|
||||
pub fn slice_source_code_range(&self, range: &Range) -> &'a str {
|
||||
let start = self.offsets[range.location.row() - 1][range.location.column() - 1];
|
||||
let end = self.offsets[range.end_location.row() - 1][range.end_location.column() - 1];
|
||||
&self.content[start..end]
|
||||
}
|
||||
|
||||
pub fn partition_source_code_at(
|
||||
&self,
|
||||
outer: &Range,
|
||||
inner: &Range,
|
||||
) -> (&'a str, &'a str, &'a str) {
|
||||
let outer_start = self.offsets[outer.location.row() - 1][outer.location.column() - 1];
|
||||
let outer_end = self.offsets[outer.end_location.row() - 1][outer.end_location.column() - 1];
|
||||
let inner_start = self.offsets[inner.location.row() - 1][inner.location.column() - 1];
|
||||
let inner_end = self.offsets[inner.end_location.row() - 1][inner.end_location.column() - 1];
|
||||
(
|
||||
&self.content[outer_start..inner_start],
|
||||
&self.content[inner_start..inner_end],
|
||||
&self.content[inner_end..outer_end],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::SourceCodeLocator;
|
||||
|
||||
#[test]
|
||||
fn source_code_locator_init() {
|
||||
let content = "# \u{4e9c}\nclass Foo:\n \"\"\".\"\"\"";
|
||||
let locator = SourceCodeLocator::new(content);
|
||||
assert_eq!(locator.offsets.len(), 4);
|
||||
assert_eq!(locator.offsets[0], [0, 1, 2, 5]);
|
||||
assert_eq!(locator.offsets[1], [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
|
||||
assert_eq!(
|
||||
locator.offsets[2],
|
||||
[17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]
|
||||
);
|
||||
assert_eq!(locator.offsets[3], [29]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,19 +69,18 @@ fn apply_fixes<'a>(fixes: impl Iterator<Item = &'a mut Fix>, contents: &str) ->
|
||||
|
||||
if fix.patch.location.row() > last_pos.row() {
|
||||
if last_pos.row() > 0 || last_pos.column() > 0 {
|
||||
output.push_str(&lines[last_pos.row() - 1][last_pos.column() - 1..]);
|
||||
output.push_str(&lines[last_pos.row() - 1][last_pos.column()..]);
|
||||
output.push('\n');
|
||||
}
|
||||
for line in &lines[last_pos.row()..fix.patch.location.row() - 1] {
|
||||
output.push_str(line);
|
||||
output.push('\n');
|
||||
}
|
||||
output
|
||||
.push_str(&lines[fix.patch.location.row() - 1][..fix.patch.location.column() - 1]);
|
||||
output.push_str(&lines[fix.patch.location.row() - 1][..fix.patch.location.column()]);
|
||||
output.push_str(&fix.patch.content);
|
||||
} else {
|
||||
output.push_str(
|
||||
&lines[last_pos.row() - 1][last_pos.column() - 1..fix.patch.location.column() - 1],
|
||||
&lines[last_pos.row() - 1][last_pos.column()..fix.patch.location.column()],
|
||||
);
|
||||
output.push_str(&fix.patch.content);
|
||||
}
|
||||
@@ -95,7 +94,7 @@ fn apply_fixes<'a>(fixes: impl Iterator<Item = &'a mut Fix>, contents: &str) ->
|
||||
&& (last_pos.row() - 1) < lines.len()
|
||||
&& (last_pos.row() > 0 || last_pos.column() > 0)
|
||||
{
|
||||
output.push_str(&lines[last_pos.row() - 1][last_pos.column() - 1..]);
|
||||
output.push_str(&lines[last_pos.row() - 1][last_pos.column()..]);
|
||||
output.push('\n');
|
||||
}
|
||||
if last_pos.row() < lines.len() {
|
||||
@@ -133,8 +132,8 @@ mod tests {
|
||||
let mut fixes = vec![Fix {
|
||||
patch: Patch {
|
||||
content: "Bar".to_string(),
|
||||
location: Location::new(1, 9),
|
||||
end_location: Location::new(1, 15),
|
||||
location: Location::new(1, 8),
|
||||
end_location: Location::new(1, 14),
|
||||
},
|
||||
applied: false,
|
||||
}];
|
||||
@@ -159,8 +158,8 @@ mod tests {
|
||||
let mut fixes = vec![Fix {
|
||||
patch: Patch {
|
||||
content: "".to_string(),
|
||||
location: Location::new(1, 8),
|
||||
end_location: Location::new(1, 16),
|
||||
location: Location::new(1, 7),
|
||||
end_location: Location::new(1, 15),
|
||||
},
|
||||
applied: false,
|
||||
}];
|
||||
@@ -186,16 +185,16 @@ mod tests {
|
||||
Fix {
|
||||
patch: Patch {
|
||||
content: "".to_string(),
|
||||
location: Location::new(1, 8),
|
||||
end_location: Location::new(1, 17),
|
||||
location: Location::new(1, 7),
|
||||
end_location: Location::new(1, 16),
|
||||
},
|
||||
applied: false,
|
||||
},
|
||||
Fix {
|
||||
patch: Patch {
|
||||
content: "".to_string(),
|
||||
location: Location::new(1, 17),
|
||||
end_location: Location::new(1, 24),
|
||||
location: Location::new(1, 16),
|
||||
end_location: Location::new(1, 23),
|
||||
},
|
||||
applied: false,
|
||||
},
|
||||
@@ -222,16 +221,16 @@ mod tests {
|
||||
Fix {
|
||||
patch: Patch {
|
||||
content: "".to_string(),
|
||||
location: Location::new(1, 8),
|
||||
end_location: Location::new(1, 16),
|
||||
location: Location::new(1, 7),
|
||||
end_location: Location::new(1, 15),
|
||||
},
|
||||
applied: false,
|
||||
},
|
||||
Fix {
|
||||
patch: Patch {
|
||||
content: "ignored".to_string(),
|
||||
location: Location::new(1, 10),
|
||||
end_location: Location::new(1, 12),
|
||||
location: Location::new(1, 9),
|
||||
end_location: Location::new(1, 11),
|
||||
},
|
||||
applied: false,
|
||||
},
|
||||
|
||||
@@ -82,8 +82,8 @@ pub fn remove_stmt(stmt: &Stmt, parent: Option<&Stmt>, deleted: &[&Stmt]) -> Res
|
||||
// Otherwise, nuke the entire line.
|
||||
// TODO(charlie): This logic assumes that there are no multi-statement physical lines.
|
||||
Ok(Fix::deletion(
|
||||
Location::new(stmt.location.row(), 1),
|
||||
Location::new(stmt.end_location.unwrap().row() + 1, 1),
|
||||
Location::new(stmt.location.row(), 0),
|
||||
Location::new(stmt.end_location.unwrap().row() + 1, 0),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
142
src/check_ast.rs
142
src/check_ast.rs
@@ -5,15 +5,14 @@ use std::ops::Deref;
|
||||
use std::path::Path;
|
||||
|
||||
use log::error;
|
||||
use once_cell::unsync::OnceCell;
|
||||
use rustpython_parser::ast::{
|
||||
Arg, Arguments, Constant, Excepthandler, ExcepthandlerKind, Expr, ExprContext, ExprKind,
|
||||
KeywordData, Operator, Stmt, StmtKind, Suite,
|
||||
};
|
||||
use rustpython_parser::parser;
|
||||
|
||||
use crate::ast::helpers::{extract_handler_names, match_name_or_attr, SubscriptKind};
|
||||
use crate::ast::operations::{extract_all_names, SourceCodeLocator};
|
||||
use crate::ast::helpers::{extract_handler_names, match_name_or_attr_from_module};
|
||||
use crate::ast::operations::extract_all_names;
|
||||
use crate::ast::relocate::relocate_expr;
|
||||
use crate::ast::types::{
|
||||
Binding, BindingContext, BindingKind, CheckLocator, FunctionScope, ImportKind, Range, Scope,
|
||||
@@ -26,26 +25,35 @@ use crate::checks::{Check, CheckCode, CheckKind};
|
||||
use crate::docstrings::definition::{Definition, DefinitionKind, Documentable};
|
||||
use crate::python::builtins::{BUILTINS, MAGIC_GLOBALS};
|
||||
use crate::python::future::ALL_FEATURE_NAMES;
|
||||
use crate::python::typing;
|
||||
use crate::python::typing::SubscriptKind;
|
||||
use crate::settings::types::PythonVersion;
|
||||
use crate::settings::Settings;
|
||||
use crate::source_code_locator::SourceCodeLocator;
|
||||
use crate::visibility::{module_visibility, transition_scope, Modifier, Visibility, VisibleScope};
|
||||
use crate::{
|
||||
docstrings, flake8_bugbear, flake8_builtins, flake8_comprehensions, flake8_print, pep8_naming,
|
||||
pycodestyle, pydocstyle, pyflakes, pyupgrade,
|
||||
};
|
||||
|
||||
pub const GLOBAL_SCOPE_INDEX: usize = 0;
|
||||
const GLOBAL_SCOPE_INDEX: usize = 0;
|
||||
const TRACK_FROM_IMPORTS: [&str; 6] = [
|
||||
"collections",
|
||||
"collections.abc",
|
||||
"contextlib",
|
||||
"re",
|
||||
"typing",
|
||||
"typing.re",
|
||||
];
|
||||
|
||||
pub struct Checker<'a> {
|
||||
// Input data.
|
||||
path: &'a Path,
|
||||
content: &'a str,
|
||||
autofix: &'a fixer::Mode,
|
||||
pub(crate) settings: &'a Settings,
|
||||
pub(crate) locator: &'a SourceCodeLocator<'a>,
|
||||
// Computed checks.
|
||||
checks: Vec<Check>,
|
||||
// Efficient source-code slicing.
|
||||
locator: OnceCell<SourceCodeLocator<'a>>,
|
||||
// Docstring tracking.
|
||||
docstrings: Vec<(Definition<'a>, Visibility)>,
|
||||
// Edit tracking.
|
||||
@@ -72,6 +80,7 @@ pub struct Checker<'a> {
|
||||
futures_allowed: bool,
|
||||
annotations_future_enabled: bool,
|
||||
except_handlers: Vec<Vec<String>>,
|
||||
from_imports: BTreeMap<&'a str, BTreeSet<&'a str>>,
|
||||
}
|
||||
|
||||
impl<'a> Checker<'a> {
|
||||
@@ -79,14 +88,13 @@ impl<'a> Checker<'a> {
|
||||
settings: &'a Settings,
|
||||
autofix: &'a fixer::Mode,
|
||||
path: &'a Path,
|
||||
content: &'a str,
|
||||
locator: &'a SourceCodeLocator,
|
||||
) -> Checker<'a> {
|
||||
Checker {
|
||||
settings,
|
||||
autofix,
|
||||
path,
|
||||
content,
|
||||
locator: OnceCell::new(),
|
||||
locator,
|
||||
checks: Default::default(),
|
||||
docstrings: Default::default(),
|
||||
deletions: Default::default(),
|
||||
@@ -104,26 +112,26 @@ impl<'a> Checker<'a> {
|
||||
modifier: Modifier::Module,
|
||||
visibility: module_visibility(path),
|
||||
},
|
||||
in_f_string: None,
|
||||
in_f_string: Default::default(),
|
||||
in_annotation: Default::default(),
|
||||
in_literal: Default::default(),
|
||||
seen_import_boundary: Default::default(),
|
||||
futures_allowed: true,
|
||||
annotations_future_enabled: Default::default(),
|
||||
except_handlers: Default::default(),
|
||||
from_imports: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get access to a lazily-initialized `SourceCodeLocator` for the file contents.
|
||||
pub fn get_locator(&self) -> &SourceCodeLocator {
|
||||
self.locator
|
||||
.get_or_init(|| SourceCodeLocator::new(self.content))
|
||||
}
|
||||
|
||||
/// Return `true` if a patch should be generated under the given autofix `Mode`.
|
||||
pub fn patch(&self) -> bool {
|
||||
self.autofix.patch()
|
||||
}
|
||||
|
||||
/// Return `true` if the `Expr` is a reference to `typing.${target}`.
|
||||
pub fn match_typing_module(&self, expr: &Expr, target: &str) -> bool {
|
||||
match_name_or_attr_from_module(expr, target, "typing", self.from_imports.get("typing"))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'b> Visitor<'b> for Checker<'a>
|
||||
@@ -236,7 +244,11 @@ where
|
||||
}
|
||||
|
||||
if self.settings.enabled.contains(&CheckCode::N802) {
|
||||
if let Some(check) = pep8_naming::checks::invalid_function_name(stmt, name) {
|
||||
if let Some(check) = pep8_naming::checks::invalid_function_name(
|
||||
stmt,
|
||||
name,
|
||||
&self.settings.pep8_naming,
|
||||
) {
|
||||
self.checks.push(check);
|
||||
}
|
||||
}
|
||||
@@ -247,6 +259,7 @@ where
|
||||
self.current_scope(),
|
||||
decorator_list,
|
||||
args,
|
||||
&self.settings.pep8_naming,
|
||||
)
|
||||
{
|
||||
self.checks.push(check);
|
||||
@@ -258,6 +271,7 @@ where
|
||||
self.current_scope(),
|
||||
decorator_list,
|
||||
args,
|
||||
&self.settings.pep8_naming,
|
||||
) {
|
||||
self.checks.push(check);
|
||||
}
|
||||
@@ -390,7 +404,7 @@ where
|
||||
}
|
||||
StmtKind::Import { names } => {
|
||||
if self.settings.enabled.contains(&CheckCode::E402) {
|
||||
if self.seen_import_boundary && stmt.location.column() == 1 {
|
||||
if self.seen_import_boundary && stmt.location.column() == 0 {
|
||||
self.checks.push(Check::new(
|
||||
CheckKind::ModuleImportNotAtTopOfFile,
|
||||
self.locate_check(Range::from_located(stmt)),
|
||||
@@ -495,8 +509,26 @@ where
|
||||
module,
|
||||
level,
|
||||
} => {
|
||||
// Track `import from` statements, to ensure that we can correctly attribute
|
||||
// references like `from typing import Union`.
|
||||
if level.map(|level| level == 0).unwrap_or(true) {
|
||||
if let Some(module) = module {
|
||||
if TRACK_FROM_IMPORTS.contains(&module.as_str()) {
|
||||
self.from_imports
|
||||
.entry(module)
|
||||
.or_insert_with(BTreeSet::new)
|
||||
.extend(
|
||||
names
|
||||
.iter()
|
||||
.filter(|alias| alias.node.asname.is_none())
|
||||
.map(|alias| alias.node.name.as_str()),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if self.settings.enabled.contains(&CheckCode::E402) {
|
||||
if self.seen_import_boundary && stmt.location.column() == 1 {
|
||||
if self.seen_import_boundary && stmt.location.column() == 0 {
|
||||
self.checks.push(Check::new(
|
||||
CheckKind::ModuleImportNotAtTopOfFile,
|
||||
self.locate_check(Range::from_located(stmt)),
|
||||
@@ -864,7 +896,7 @@ where
|
||||
pyupgrade::plugins::use_pep604_annotation(self, expr, value, slice);
|
||||
}
|
||||
|
||||
if match_name_or_attr(value, "Literal") {
|
||||
if self.match_typing_module(value, "Literal") {
|
||||
self.in_literal = true;
|
||||
}
|
||||
}
|
||||
@@ -889,6 +921,7 @@ where
|
||||
// Ex) List[...]
|
||||
if self.settings.enabled.contains(&CheckCode::U006)
|
||||
&& self.settings.target_version >= PythonVersion::Py39
|
||||
&& typing::is_pep585_builtin(expr, self.from_imports.get("typing"))
|
||||
{
|
||||
pyupgrade::plugins::use_pep585_annotation(self, expr, id);
|
||||
}
|
||||
@@ -911,23 +944,19 @@ where
|
||||
}
|
||||
ExprContext::Del => self.handle_node_delete(expr),
|
||||
},
|
||||
ExprKind::Attribute { value, attr, .. } => {
|
||||
ExprKind::Attribute { attr, .. } => {
|
||||
// Ex) typing.List[...]
|
||||
if self.settings.enabled.contains(&CheckCode::U006)
|
||||
&& self.settings.target_version >= PythonVersion::Py39
|
||||
&& typing::is_pep585_builtin(expr, self.from_imports.get("typing"))
|
||||
{
|
||||
if let ExprKind::Name { id, .. } = &value.node {
|
||||
if id == "typing" {
|
||||
pyupgrade::plugins::use_pep585_annotation(self, expr, attr);
|
||||
}
|
||||
}
|
||||
pyupgrade::plugins::use_pep585_annotation(self, expr, attr);
|
||||
}
|
||||
}
|
||||
ExprKind::Call {
|
||||
func,
|
||||
args,
|
||||
keywords,
|
||||
..
|
||||
} => {
|
||||
if self.settings.enabled.contains(&CheckCode::U005) {
|
||||
pyupgrade::plugins::deprecated_unittest_alias(self, func);
|
||||
@@ -947,25 +976,25 @@ where
|
||||
|
||||
// flake8-comprehensions
|
||||
if self.settings.enabled.contains(&CheckCode::C400) {
|
||||
if let Some(check) =
|
||||
flake8_comprehensions::checks::unnecessary_generator_list(expr, func, args)
|
||||
{
|
||||
if let Some(check) = flake8_comprehensions::checks::unnecessary_generator_list(
|
||||
expr, func, args, keywords,
|
||||
) {
|
||||
self.checks.push(check);
|
||||
};
|
||||
}
|
||||
|
||||
if self.settings.enabled.contains(&CheckCode::C401) {
|
||||
if let Some(check) =
|
||||
flake8_comprehensions::checks::unnecessary_generator_set(expr, func, args)
|
||||
{
|
||||
if let Some(check) = flake8_comprehensions::checks::unnecessary_generator_set(
|
||||
expr, func, args, keywords,
|
||||
) {
|
||||
self.checks.push(check);
|
||||
};
|
||||
}
|
||||
|
||||
if self.settings.enabled.contains(&CheckCode::C402) {
|
||||
if let Some(check) =
|
||||
flake8_comprehensions::checks::unnecessary_generator_dict(expr, func, args)
|
||||
{
|
||||
if let Some(check) = flake8_comprehensions::checks::unnecessary_generator_dict(
|
||||
expr, func, args, keywords,
|
||||
) {
|
||||
self.checks.push(check);
|
||||
};
|
||||
}
|
||||
@@ -973,7 +1002,7 @@ where
|
||||
if self.settings.enabled.contains(&CheckCode::C403) {
|
||||
if let Some(check) =
|
||||
flake8_comprehensions::checks::unnecessary_list_comprehension_set(
|
||||
expr, func, args,
|
||||
expr, func, args, keywords,
|
||||
)
|
||||
{
|
||||
self.checks.push(check);
|
||||
@@ -983,7 +1012,7 @@ where
|
||||
if self.settings.enabled.contains(&CheckCode::C404) {
|
||||
if let Some(check) =
|
||||
flake8_comprehensions::checks::unnecessary_list_comprehension_dict(
|
||||
expr, func, args,
|
||||
expr, func, args, keywords,
|
||||
)
|
||||
{
|
||||
self.checks.push(check);
|
||||
@@ -991,17 +1020,17 @@ where
|
||||
}
|
||||
|
||||
if self.settings.enabled.contains(&CheckCode::C405) {
|
||||
if let Some(check) =
|
||||
flake8_comprehensions::checks::unnecessary_literal_set(expr, func, args)
|
||||
{
|
||||
if let Some(check) = flake8_comprehensions::checks::unnecessary_literal_set(
|
||||
expr, func, args, keywords,
|
||||
) {
|
||||
self.checks.push(check);
|
||||
};
|
||||
}
|
||||
|
||||
if self.settings.enabled.contains(&CheckCode::C406) {
|
||||
if let Some(check) =
|
||||
flake8_comprehensions::checks::unnecessary_literal_dict(expr, func, args)
|
||||
{
|
||||
if let Some(check) = flake8_comprehensions::checks::unnecessary_literal_dict(
|
||||
expr, func, args, keywords,
|
||||
) {
|
||||
self.checks.push(check);
|
||||
};
|
||||
}
|
||||
@@ -1280,12 +1309,12 @@ where
|
||||
args,
|
||||
keywords,
|
||||
} => {
|
||||
if match_name_or_attr(func, "ForwardRef") {
|
||||
if self.match_typing_module(func, "ForwardRef") {
|
||||
self.visit_expr(func);
|
||||
for expr in args {
|
||||
self.visit_annotation(expr);
|
||||
}
|
||||
} else if match_name_or_attr(func, "cast") {
|
||||
} else if self.match_typing_module(func, "cast") {
|
||||
self.visit_expr(func);
|
||||
if !args.is_empty() {
|
||||
self.visit_annotation(&args[0]);
|
||||
@@ -1293,12 +1322,12 @@ where
|
||||
for expr in args.iter().skip(1) {
|
||||
self.visit_expr(expr);
|
||||
}
|
||||
} else if match_name_or_attr(func, "NewType") {
|
||||
} else if self.match_typing_module(func, "NewType") {
|
||||
self.visit_expr(func);
|
||||
for expr in args.iter().skip(1) {
|
||||
self.visit_annotation(expr);
|
||||
}
|
||||
} else if match_name_or_attr(func, "TypeVar") {
|
||||
} else if self.match_typing_module(func, "TypeVar") {
|
||||
self.visit_expr(func);
|
||||
for expr in args.iter().skip(1) {
|
||||
self.visit_annotation(expr);
|
||||
@@ -1315,7 +1344,7 @@ where
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if match_name_or_attr(func, "NamedTuple") {
|
||||
} else if self.match_typing_module(func, "NamedTuple") {
|
||||
self.visit_expr(func);
|
||||
|
||||
// Ex) NamedTuple("a", [("a", int)])
|
||||
@@ -1347,7 +1376,7 @@ where
|
||||
let KeywordData { value, .. } = &keyword.node;
|
||||
self.visit_annotation(value);
|
||||
}
|
||||
} else if match_name_or_attr(func, "TypedDict") {
|
||||
} else if self.match_typing_module(func, "TypedDict") {
|
||||
self.visit_expr(func);
|
||||
|
||||
// Ex) TypedDict("a", {"a": int})
|
||||
@@ -1374,7 +1403,7 @@ where
|
||||
}
|
||||
}
|
||||
ExprKind::Subscript { value, slice, ctx } => {
|
||||
match helpers::match_annotated_subscript(value) {
|
||||
match typing::match_annotated_subscript(value, &self.from_imports) {
|
||||
Some(subscript) => match subscript {
|
||||
// Ex) Optional[int]
|
||||
SubscriptKind::AnnotatedSubscript => {
|
||||
@@ -1507,6 +1536,9 @@ where
|
||||
self.checks
|
||||
.extend(pyflakes::checks::duplicate_arguments(arguments));
|
||||
}
|
||||
if self.settings.enabled.contains(&CheckCode::B006) {
|
||||
flake8_bugbear::plugins::mutable_argument_default(self, arguments)
|
||||
}
|
||||
|
||||
// Bind, but intentionally avoid walking default expressions, as we handle them upstream.
|
||||
for arg in &arguments.posonlyargs {
|
||||
@@ -2140,7 +2172,7 @@ impl<'a> Checker<'a> {
|
||||
ImportKind::ImportFrom => pyflakes::fixes::remove_unused_import_froms,
|
||||
};
|
||||
|
||||
match removal_fn(self.get_locator(), &full_names, child, parent, &deleted) {
|
||||
match removal_fn(self.locator, &full_names, child, parent, &deleted) {
|
||||
Ok(fix) => Some(fix),
|
||||
Err(e) => {
|
||||
error!("Failed to fix unused imports: {}", e);
|
||||
@@ -2300,12 +2332,12 @@ impl<'a> Checker<'a> {
|
||||
|
||||
pub fn check_ast(
|
||||
python_ast: &Suite,
|
||||
contents: &str,
|
||||
locator: &SourceCodeLocator,
|
||||
settings: &Settings,
|
||||
autofix: &fixer::Mode,
|
||||
path: &Path,
|
||||
) -> Vec<Check> {
|
||||
let mut checker = Checker::new(settings, autofix, path, contents);
|
||||
let mut checker = Checker::new(settings, autofix, path, locator);
|
||||
checker.push_scope(Scope::new(ScopeKind::Module));
|
||||
checker.bind_builtins();
|
||||
|
||||
|
||||
@@ -94,8 +94,8 @@ pub fn check_lines(
|
||||
let check = Check::new(
|
||||
CheckKind::LineTooLong(line_length, settings.line_length),
|
||||
Range {
|
||||
location: Location::new(lineno + 1, 1),
|
||||
end_location: Location::new(lineno + 1, line_length + 1),
|
||||
location: Location::new(lineno + 1, 0),
|
||||
end_location: Location::new(lineno + 1, line_length),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -164,14 +164,14 @@ pub fn check_lines(
|
||||
let mut check = Check::new(
|
||||
CheckKind::UnusedNOQA(None),
|
||||
Range {
|
||||
location: Location::new(row + 1, start + 1),
|
||||
end_location: Location::new(row + 1, end + 1),
|
||||
location: Location::new(row + 1, start),
|
||||
end_location: Location::new(row + 1, end),
|
||||
},
|
||||
);
|
||||
if autofix.patch() {
|
||||
check.amend(Fix::deletion(
|
||||
Location::new(row + 1, start + 1),
|
||||
Location::new(row + 1, lines[row].chars().count() + 1),
|
||||
Location::new(row + 1, start),
|
||||
Location::new(row + 1, lines[row].chars().count()),
|
||||
));
|
||||
}
|
||||
line_checks.push(check);
|
||||
@@ -192,21 +192,21 @@ pub fn check_lines(
|
||||
let mut check = Check::new(
|
||||
CheckKind::UnusedNOQA(Some(invalid_codes)),
|
||||
Range {
|
||||
location: Location::new(row + 1, start + 1),
|
||||
end_location: Location::new(row + 1, end + 1),
|
||||
location: Location::new(row + 1, start),
|
||||
end_location: Location::new(row + 1, end),
|
||||
},
|
||||
);
|
||||
if autofix.patch() {
|
||||
if valid_codes.is_empty() {
|
||||
check.amend(Fix::deletion(
|
||||
Location::new(row + 1, start + 1),
|
||||
Location::new(row + 1, lines[row].chars().count() + 1),
|
||||
Location::new(row + 1, start),
|
||||
Location::new(row + 1, lines[row].chars().count()),
|
||||
));
|
||||
} else {
|
||||
check.amend(Fix::replacement(
|
||||
format!(" # noqa: {}", valid_codes.join(", ")),
|
||||
Location::new(row + 1, start + 1),
|
||||
Location::new(row + 1, lines[row].chars().count() + 1),
|
||||
Location::new(row + 1, start),
|
||||
Location::new(row + 1, lines[row].chars().count()),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
|
||||
use rustpython_parser::lexer::{LexResult, Tok};
|
||||
|
||||
use crate::ast::operations::SourceCodeLocator;
|
||||
use crate::checks::{Check, CheckCode};
|
||||
use crate::flake8_quotes::docstring_detection::StateMachine;
|
||||
use crate::source_code_locator::SourceCodeLocator;
|
||||
use crate::{flake8_quotes, pycodestyle, Settings};
|
||||
|
||||
pub fn check_tokens(
|
||||
checks: &mut Vec<Check>,
|
||||
contents: &str,
|
||||
locator: &SourceCodeLocator,
|
||||
tokens: &[LexResult],
|
||||
settings: &Settings,
|
||||
) {
|
||||
@@ -19,16 +19,13 @@ pub fn check_tokens(
|
||||
| settings.enabled.contains(&CheckCode::Q002)
|
||||
| settings.enabled.contains(&CheckCode::Q003);
|
||||
|
||||
// TODO(charlie): Use a shared SourceCodeLocator between this site and the AST traversal.
|
||||
let locator = SourceCodeLocator::new(contents);
|
||||
|
||||
let mut state_machine = StateMachine::new();
|
||||
for (start, tok, end) in tokens.iter().flatten() {
|
||||
// W605
|
||||
if enforce_invalid_escape_sequence {
|
||||
if matches!(tok, Tok::String { .. }) {
|
||||
checks.extend(pycodestyle::checks::invalid_escape_sequence(
|
||||
&locator, start, end,
|
||||
locator, start, end,
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -38,7 +35,7 @@ pub fn check_tokens(
|
||||
let is_docstring = state_machine.consume(tok);
|
||||
if matches!(tok, Tok::String { .. }) {
|
||||
if let Some(check) = flake8_quotes::checks::quotes(
|
||||
&locator,
|
||||
locator,
|
||||
start,
|
||||
end,
|
||||
is_docstring,
|
||||
|
||||
@@ -78,6 +78,7 @@ pub enum CheckCode {
|
||||
A003,
|
||||
// flake8-bugbear
|
||||
B002,
|
||||
B006,
|
||||
B007,
|
||||
B011,
|
||||
B013,
|
||||
@@ -287,6 +288,7 @@ pub enum CheckKind {
|
||||
BuiltinAttributeShadowing(String),
|
||||
// flake8-bugbear
|
||||
UnaryPrefixIncrement,
|
||||
MutableArgumentDefault,
|
||||
UnusedLoopControlVariable(String),
|
||||
DoNotAssertFalse,
|
||||
RedundantTupleInExceptionHandler(String),
|
||||
@@ -465,6 +467,7 @@ impl CheckCode {
|
||||
CheckCode::A003 => CheckKind::BuiltinAttributeShadowing("...".to_string()),
|
||||
// flake8-bugbear
|
||||
CheckCode::B002 => CheckKind::UnaryPrefixIncrement,
|
||||
CheckCode::B006 => CheckKind::MutableArgumentDefault,
|
||||
CheckCode::B007 => CheckKind::UnusedLoopControlVariable("i".to_string()),
|
||||
CheckCode::B011 => CheckKind::DoNotAssertFalse,
|
||||
CheckCode::B013 => {
|
||||
@@ -655,6 +658,7 @@ impl CheckCode {
|
||||
CheckCode::A002 => CheckCategory::Flake8Builtins,
|
||||
CheckCode::A003 => CheckCategory::Flake8Builtins,
|
||||
CheckCode::B002 => CheckCategory::Flake8Bugbear,
|
||||
CheckCode::B006 => CheckCategory::Flake8Bugbear,
|
||||
CheckCode::B007 => CheckCategory::Flake8Bugbear,
|
||||
CheckCode::B011 => CheckCategory::Flake8Bugbear,
|
||||
CheckCode::B013 => CheckCategory::Flake8Bugbear,
|
||||
@@ -811,6 +815,7 @@ impl CheckKind {
|
||||
CheckKind::BuiltinAttributeShadowing(_) => &CheckCode::A003,
|
||||
// flake8-bugbear
|
||||
CheckKind::UnaryPrefixIncrement => &CheckCode::B002,
|
||||
CheckKind::MutableArgumentDefault => &CheckCode::B006,
|
||||
CheckKind::UnusedLoopControlVariable(_) => &CheckCode::B007,
|
||||
CheckKind::DoNotAssertFalse => &CheckCode::B011,
|
||||
CheckKind::RedundantTupleInExceptionHandler(_) => &CheckCode::B013,
|
||||
@@ -1050,7 +1055,7 @@ impl CheckKind {
|
||||
format!("Local variable `{name}` is assigned to but never used")
|
||||
}
|
||||
CheckKind::YieldOutsideFunction => {
|
||||
"`yield` or `yield from` statement outside of a function/method".to_string()
|
||||
"`yield` or `yield from` statement outside of a function".to_string()
|
||||
}
|
||||
// pycodestyle warnings
|
||||
CheckKind::NoNewLineAtEndOfFile => "No newline at end of file".to_string(),
|
||||
@@ -1067,6 +1072,7 @@ impl CheckKind {
|
||||
}
|
||||
// flake8-bugbear
|
||||
CheckKind::UnaryPrefixIncrement => "Python does not support the unary prefix increment. Writing `++n` is equivalent to `+(+(n))`, which equals `n`. You meant `n += 1`.".to_string(),
|
||||
CheckKind::MutableArgumentDefault => "Do not use mutable data structures for argument defaults.".to_string(),
|
||||
CheckKind::UnusedLoopControlVariable(name) => format!("Loop control variable `{name}` not used within the loop body. If this is intended, start the name with an underscore."),
|
||||
CheckKind::DoNotAssertFalse => {
|
||||
"Do not `assert False` (`python -O` removes these calls), raise `AssertionError()`"
|
||||
@@ -1150,7 +1156,7 @@ impl CheckKind {
|
||||
format!("Unnecessary subscript reversal of iterable within `{func}()`")
|
||||
}
|
||||
CheckKind::UnnecessaryComprehension(obj_type) => {
|
||||
format!(" Unnecessary `{obj_type}` comprehension (rewrite using `{obj_type}()`)")
|
||||
format!("Unnecessary `{obj_type}` comprehension (rewrite using `{obj_type}()`)")
|
||||
}
|
||||
CheckKind::UnnecessaryMap(obj_type) => {
|
||||
if obj_type == "generator" {
|
||||
@@ -1191,7 +1197,7 @@ impl CheckKind {
|
||||
}
|
||||
CheckKind::UselessMetaclassType => "`__metaclass__ = type` is implied".to_string(),
|
||||
CheckKind::DeprecatedUnittestAlias(alias, target) => {
|
||||
format!("`{}` is deprecated, use `{}` instead", alias, target)
|
||||
format!("`{alias}` is deprecated, use `{target}` instead")
|
||||
}
|
||||
CheckKind::UselessObjectInheritance(name) => {
|
||||
format!("Class `{name}` inherits from object")
|
||||
@@ -1261,10 +1267,10 @@ impl CheckKind {
|
||||
CheckKind::PublicNestedClass => "Missing docstring in public nested class".to_string(),
|
||||
CheckKind::PublicInit => "Missing docstring in `__init__`".to_string(),
|
||||
CheckKind::NoThisPrefix => {
|
||||
"First word of the docstring should not be `This`".to_string()
|
||||
"First word of the docstring should not be 'This'".to_string()
|
||||
}
|
||||
CheckKind::SkipDocstring => {
|
||||
"Function decorated with @overload shouldn't contain a docstring".to_string()
|
||||
"Function decorated with `@overload` shouldn't contain a docstring".to_string()
|
||||
}
|
||||
CheckKind::CapitalizeSectionName(name) => {
|
||||
format!("Section name should be properly capitalized (\"{name}\")")
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! File automatically generated by examples/generate_check_code_prefix.rs.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use strum_macros::EnumString;
|
||||
use strum_macros::{AsRefStr, EnumString};
|
||||
|
||||
use crate::checks::CheckCode;
|
||||
|
||||
#[derive(EnumString, Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
|
||||
#[derive(AsRefStr, EnumString, Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
|
||||
pub enum CheckCodePrefix {
|
||||
A,
|
||||
A0,
|
||||
@@ -17,6 +17,7 @@ pub enum CheckCodePrefix {
|
||||
B0,
|
||||
B00,
|
||||
B002,
|
||||
B006,
|
||||
B007,
|
||||
B01,
|
||||
B011,
|
||||
@@ -247,6 +248,7 @@ impl CheckCodePrefix {
|
||||
CheckCodePrefix::A003 => vec![CheckCode::A003],
|
||||
CheckCodePrefix::B => vec![
|
||||
CheckCode::B002,
|
||||
CheckCode::B006,
|
||||
CheckCode::B007,
|
||||
CheckCode::B011,
|
||||
CheckCode::B013,
|
||||
@@ -256,6 +258,7 @@ impl CheckCodePrefix {
|
||||
],
|
||||
CheckCodePrefix::B0 => vec![
|
||||
CheckCode::B002,
|
||||
CheckCode::B006,
|
||||
CheckCode::B007,
|
||||
CheckCode::B011,
|
||||
CheckCode::B013,
|
||||
@@ -263,8 +266,9 @@ impl CheckCodePrefix {
|
||||
CheckCode::B017,
|
||||
CheckCode::B025,
|
||||
],
|
||||
CheckCodePrefix::B00 => vec![CheckCode::B002, CheckCode::B007],
|
||||
CheckCodePrefix::B00 => vec![CheckCode::B002, CheckCode::B006, CheckCode::B007],
|
||||
CheckCodePrefix::B002 => vec![CheckCode::B002],
|
||||
CheckCodePrefix::B006 => vec![CheckCode::B006],
|
||||
CheckCodePrefix::B007 => vec![CheckCode::B007],
|
||||
CheckCodePrefix::B01 => vec![
|
||||
CheckCode::B011,
|
||||
@@ -887,6 +891,7 @@ impl CheckCodePrefix {
|
||||
CheckCodePrefix::B0 => PrefixSpecificity::Hundreds,
|
||||
CheckCodePrefix::B00 => PrefixSpecificity::Tens,
|
||||
CheckCodePrefix::B002 => PrefixSpecificity::Explicit,
|
||||
CheckCodePrefix::B006 => PrefixSpecificity::Explicit,
|
||||
CheckCodePrefix::B007 => PrefixSpecificity::Explicit,
|
||||
CheckCodePrefix::B01 => PrefixSpecificity::Tens,
|
||||
CheckCodePrefix::B011 => PrefixSpecificity::Explicit,
|
||||
|
||||
19
src/cli.rs
19
src/cli.rs
@@ -1,3 +1,4 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -8,8 +9,8 @@ use regex::Regex;
|
||||
use crate::checks_gen::CheckCodePrefix;
|
||||
use crate::printer::SerializationFormat;
|
||||
use crate::settings::configuration::Configuration;
|
||||
use crate::settings::types::PatternPrefixPair;
|
||||
use crate::settings::types::PythonVersion;
|
||||
use crate::settings::types::StrCheckCodePair;
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(author, about = "ruff: An extremely fast Python linter.")]
|
||||
@@ -61,7 +62,7 @@ pub struct Cli {
|
||||
pub extend_exclude: Vec<String>,
|
||||
/// List of mappings from file pattern to code to exclude
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
pub per_file_ignores: Vec<StrCheckCodePair>,
|
||||
pub per_file_ignores: Vec<PatternPrefixPair>,
|
||||
/// Output serialization format for error messages.
|
||||
#[arg(long, value_enum, default_value_t=SerializationFormat::Text)]
|
||||
pub format: SerializationFormat,
|
||||
@@ -143,3 +144,17 @@ pub fn warn_on(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Collect a list of `PatternPrefixPair` structs as a `BTreeMap`.
|
||||
pub fn collect_per_file_ignores(
|
||||
pairs: Vec<PatternPrefixPair>,
|
||||
) -> BTreeMap<String, Vec<CheckCodePrefix>> {
|
||||
let mut per_file_ignores: BTreeMap<String, Vec<CheckCodePrefix>> = BTreeMap::new();
|
||||
for pair in pairs {
|
||||
per_file_ignores
|
||||
.entry(pair.pattern)
|
||||
.or_insert_with(Vec::new)
|
||||
.push(pair.prefix);
|
||||
}
|
||||
per_file_ignores
|
||||
}
|
||||
|
||||
@@ -27,8 +27,8 @@ pub fn leading_space(line: &str) -> String {
|
||||
/// Extract the leading indentation from a docstring.
|
||||
pub fn indentation<'a>(checker: &'a Checker, docstring: &Expr) -> &'a str {
|
||||
let range = Range::from_located(docstring);
|
||||
checker.get_locator().slice_source_code_range(&Range {
|
||||
location: Location::new(range.location.row(), 1),
|
||||
checker.locator.slice_source_code_range(&Range {
|
||||
location: Location::new(range.location.row(), 0),
|
||||
end_location: Location::new(range.location.row(), range.location.column()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ pub use assert_false::assert_false;
|
||||
pub use assert_raises_exception::assert_raises_exception;
|
||||
pub use duplicate_exceptions::duplicate_exceptions;
|
||||
pub use duplicate_exceptions::duplicate_handler_exceptions;
|
||||
pub use mutable_argument_default::mutable_argument_default;
|
||||
pub use redundant_tuple_in_exception_handler::redundant_tuple_in_exception_handler;
|
||||
pub use unary_prefix_increment::unary_prefix_increment;
|
||||
pub use unused_loop_control_variable::unused_loop_control_variable;
|
||||
@@ -9,6 +10,7 @@ pub use unused_loop_control_variable::unused_loop_control_variable;
|
||||
mod assert_false;
|
||||
mod assert_raises_exception;
|
||||
mod duplicate_exceptions;
|
||||
mod mutable_argument_default;
|
||||
mod redundant_tuple_in_exception_handler;
|
||||
mod unary_prefix_increment;
|
||||
mod unused_loop_control_variable;
|
||||
|
||||
62
src/flake8_bugbear/plugins/mutable_argument_default.rs
Normal file
62
src/flake8_bugbear/plugins/mutable_argument_default.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
use rustpython_ast::{Arguments, ExprKind};
|
||||
|
||||
use crate::ast::types::{CheckLocator, Range};
|
||||
use crate::check_ast::Checker;
|
||||
use crate::checks::{Check, CheckKind};
|
||||
|
||||
/// B006
|
||||
pub fn mutable_argument_default(checker: &mut Checker, arguments: &Arguments) {
|
||||
for expr in arguments
|
||||
.defaults
|
||||
.iter()
|
||||
.chain(arguments.kw_defaults.iter())
|
||||
{
|
||||
match &expr.node {
|
||||
ExprKind::List { .. }
|
||||
| ExprKind::Dict { .. }
|
||||
| ExprKind::Set { .. }
|
||||
| ExprKind::ListComp { .. }
|
||||
| ExprKind::DictComp { .. }
|
||||
| ExprKind::SetComp { .. } => {
|
||||
checker.add_check(Check::new(
|
||||
CheckKind::MutableArgumentDefault,
|
||||
checker.locate_check(Range::from_located(expr)),
|
||||
));
|
||||
}
|
||||
ExprKind::Call { func, .. } => match &func.node {
|
||||
ExprKind::Name { id, .. }
|
||||
if id == "dict"
|
||||
|| id == "list"
|
||||
|| id == "set"
|
||||
|| id == "Counter"
|
||||
|| id == "OrderedDict"
|
||||
|| id == "defaultdict"
|
||||
|| id == "deque" =>
|
||||
{
|
||||
checker.add_check(Check::new(
|
||||
CheckKind::MutableArgumentDefault,
|
||||
checker.locate_check(Range::from_located(expr)),
|
||||
));
|
||||
}
|
||||
ExprKind::Attribute { value, attr, .. }
|
||||
if (attr == "Counter"
|
||||
|| attr == "OrderedDict"
|
||||
|| attr == "defaultdict"
|
||||
|| attr == "deque") =>
|
||||
{
|
||||
match &value.node {
|
||||
ExprKind::Name { id, .. } if id == "collections" => {
|
||||
checker.add_check(Check::new(
|
||||
CheckKind::MutableArgumentDefault,
|
||||
checker.locate_check(Range::from_located(expr)),
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
use num_bigint::BigInt;
|
||||
use rustpython_ast::{Comprehension, Constant, Expr, ExprKind, KeywordData, Located, Unaryop};
|
||||
use rustpython_ast::{
|
||||
Comprehension, Constant, Expr, ExprKind, Keyword, KeywordData, Located, Unaryop,
|
||||
};
|
||||
|
||||
use crate::ast::types::Range;
|
||||
use crate::checks::{Check, CheckKind};
|
||||
@@ -16,7 +18,11 @@ fn exactly_one_argument_with_matching_function<'a>(
|
||||
name: &str,
|
||||
func: &Expr,
|
||||
args: &'a [Expr],
|
||||
keywords: &[Keyword],
|
||||
) -> Option<&'a ExprKind> {
|
||||
if !keywords.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if args.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
@@ -38,8 +44,13 @@ fn first_argument_with_matching_function<'a>(
|
||||
}
|
||||
|
||||
/// C400 (`list(generator)`)
|
||||
pub fn unnecessary_generator_list(expr: &Expr, func: &Expr, args: &[Expr]) -> Option<Check> {
|
||||
let argument = exactly_one_argument_with_matching_function("list", func, args)?;
|
||||
pub fn unnecessary_generator_list(
|
||||
expr: &Expr,
|
||||
func: &Expr,
|
||||
args: &[Expr],
|
||||
keywords: &[Keyword],
|
||||
) -> Option<Check> {
|
||||
let argument = exactly_one_argument_with_matching_function("list", func, args, keywords)?;
|
||||
if let ExprKind::GeneratorExp { .. } = argument {
|
||||
return Some(Check::new(
|
||||
CheckKind::UnnecessaryGeneratorList,
|
||||
@@ -50,8 +61,13 @@ pub fn unnecessary_generator_list(expr: &Expr, func: &Expr, args: &[Expr]) -> Op
|
||||
}
|
||||
|
||||
/// C401 (`set(generator)`)
|
||||
pub fn unnecessary_generator_set(expr: &Expr, func: &Expr, args: &[Expr]) -> Option<Check> {
|
||||
let argument = exactly_one_argument_with_matching_function("set", func, args)?;
|
||||
pub fn unnecessary_generator_set(
|
||||
expr: &Expr,
|
||||
func: &Expr,
|
||||
args: &[Expr],
|
||||
keywords: &[Keyword],
|
||||
) -> Option<Check> {
|
||||
let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?;
|
||||
if let ExprKind::GeneratorExp { .. } = argument {
|
||||
return Some(Check::new(
|
||||
CheckKind::UnnecessaryGeneratorSet,
|
||||
@@ -62,8 +78,13 @@ pub fn unnecessary_generator_set(expr: &Expr, func: &Expr, args: &[Expr]) -> Opt
|
||||
}
|
||||
|
||||
/// C402 (`dict((x, y) for x, y in iterable)`)
|
||||
pub fn unnecessary_generator_dict(expr: &Expr, func: &Expr, args: &[Expr]) -> Option<Check> {
|
||||
let argument = exactly_one_argument_with_matching_function("dict", func, args)?;
|
||||
pub fn unnecessary_generator_dict(
|
||||
expr: &Expr,
|
||||
func: &Expr,
|
||||
args: &[Expr],
|
||||
keywords: &[Keyword],
|
||||
) -> Option<Check> {
|
||||
let argument = exactly_one_argument_with_matching_function("dict", func, args, keywords)?;
|
||||
if let ExprKind::GeneratorExp { elt, .. } = argument {
|
||||
match &elt.node {
|
||||
ExprKind::Tuple { elts, .. } if elts.len() == 2 => {
|
||||
@@ -83,8 +104,9 @@ pub fn unnecessary_list_comprehension_set(
|
||||
expr: &Expr,
|
||||
func: &Expr,
|
||||
args: &[Expr],
|
||||
keywords: &[Keyword],
|
||||
) -> Option<Check> {
|
||||
let argument = exactly_one_argument_with_matching_function("set", func, args)?;
|
||||
let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?;
|
||||
if let ExprKind::ListComp { .. } = &argument {
|
||||
return Some(Check::new(
|
||||
CheckKind::UnnecessaryListComprehensionSet,
|
||||
@@ -99,8 +121,9 @@ pub fn unnecessary_list_comprehension_dict(
|
||||
expr: &Expr,
|
||||
func: &Expr,
|
||||
args: &[Expr],
|
||||
keywords: &[Keyword],
|
||||
) -> Option<Check> {
|
||||
let argument = exactly_one_argument_with_matching_function("dict", func, args)?;
|
||||
let argument = exactly_one_argument_with_matching_function("dict", func, args, keywords)?;
|
||||
if let ExprKind::ListComp { elt, .. } = &argument {
|
||||
match &elt.node {
|
||||
ExprKind::Tuple { elts, .. } if elts.len() == 2 => {
|
||||
@@ -116,8 +139,13 @@ pub fn unnecessary_list_comprehension_dict(
|
||||
}
|
||||
|
||||
/// C405 (`set([1, 2])`)
|
||||
pub fn unnecessary_literal_set(expr: &Expr, func: &Expr, args: &[Expr]) -> Option<Check> {
|
||||
let argument = exactly_one_argument_with_matching_function("set", func, args)?;
|
||||
pub fn unnecessary_literal_set(
|
||||
expr: &Expr,
|
||||
func: &Expr,
|
||||
args: &[Expr],
|
||||
keywords: &[Keyword],
|
||||
) -> Option<Check> {
|
||||
let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?;
|
||||
let kind = match argument {
|
||||
ExprKind::List { .. } => "list",
|
||||
ExprKind::Tuple { .. } => "tuple",
|
||||
@@ -130,8 +158,13 @@ pub fn unnecessary_literal_set(expr: &Expr, func: &Expr, args: &[Expr]) -> Optio
|
||||
}
|
||||
|
||||
/// C406 (`dict([(1, 2)])`)
|
||||
pub fn unnecessary_literal_dict(expr: &Expr, func: &Expr, args: &[Expr]) -> Option<Check> {
|
||||
let argument = exactly_one_argument_with_matching_function("dict", func, args)?;
|
||||
pub fn unnecessary_literal_dict(
|
||||
expr: &Expr,
|
||||
func: &Expr,
|
||||
args: &[Expr],
|
||||
keywords: &[Keyword],
|
||||
) -> Option<Check> {
|
||||
let argument = exactly_one_argument_with_matching_function("dict", func, args, keywords)?;
|
||||
let (kind, elts) = match argument {
|
||||
ExprKind::Tuple { elts, .. } => ("tuple", elts),
|
||||
ExprKind::List { elts, .. } => ("list", elts),
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use rustpython_ast::Location;
|
||||
|
||||
use crate::ast::operations::SourceCodeLocator;
|
||||
use crate::ast::types::Range;
|
||||
use crate::checks::{Check, CheckKind};
|
||||
use crate::flake8_quotes::settings::{Quote, Settings};
|
||||
use crate::source_code_locator::SourceCodeLocator;
|
||||
|
||||
fn good_single(quote: &Quote) -> char {
|
||||
match quote {
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
//! Settings for the `flake_quotes` plugin.
|
||||
//! Settings for the `flake-quotes` plugin.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub enum Quote {
|
||||
Single,
|
||||
Double,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Deserialize)]
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct Options {
|
||||
pub inline_quotes: Option<Quote>,
|
||||
@@ -27,12 +27,12 @@ pub struct Settings {
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
pub fn from_config(config: Options) -> Self {
|
||||
pub fn from_options(options: Options) -> Self {
|
||||
Self {
|
||||
inline_quotes: config.inline_quotes.unwrap_or(Quote::Single),
|
||||
multiline_quotes: config.multiline_quotes.unwrap_or(Quote::Double),
|
||||
docstring_quotes: config.docstring_quotes.unwrap_or(Quote::Double),
|
||||
avoid_escape: config.avoid_escape.unwrap_or(true),
|
||||
inline_quotes: options.inline_quotes.unwrap_or(Quote::Single),
|
||||
multiline_quotes: options.multiline_quotes.unwrap_or(Quote::Double),
|
||||
docstring_quotes: options.docstring_quotes.unwrap_or(Quote::Double),
|
||||
avoid_escape: options.avoid_escape.unwrap_or(true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,45 +6,45 @@ expression: checks
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 5
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 7
|
||||
column: 4
|
||||
column: 3
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 16
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 18
|
||||
column: 8
|
||||
column: 7
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 21
|
||||
column: 21
|
||||
column: 20
|
||||
end_location:
|
||||
row: 22
|
||||
column: 38
|
||||
column: 37
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 30
|
||||
column: 9
|
||||
column: 8
|
||||
end_location:
|
||||
row: 32
|
||||
column: 12
|
||||
column: 11
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 35
|
||||
column: 13
|
||||
column: 12
|
||||
end_location:
|
||||
row: 37
|
||||
column: 16
|
||||
column: 15
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,18 +6,18 @@ expression: checks
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 3
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 3
|
||||
column: 28
|
||||
column: 27
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 5
|
||||
column: 23
|
||||
column: 22
|
||||
end_location:
|
||||
row: 5
|
||||
column: 44
|
||||
column: 43
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,45 +6,45 @@ expression: checks
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 3
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 3
|
||||
column: 27
|
||||
column: 26
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 11
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 11
|
||||
column: 27
|
||||
column: 26
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 15
|
||||
column: 39
|
||||
column: 38
|
||||
end_location:
|
||||
row: 17
|
||||
column: 3
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 17
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 17
|
||||
column: 5
|
||||
end_location:
|
||||
row: 17
|
||||
column: 20
|
||||
column: 19
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 21
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 21
|
||||
column: 28
|
||||
column: 27
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,18 +6,18 @@ expression: checks
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 4
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 6
|
||||
column: 4
|
||||
column: 3
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 9
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 11
|
||||
column: 4
|
||||
column: 3
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,18 +6,18 @@ expression: checks
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 2
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 2
|
||||
column: 32
|
||||
column: 31
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 6
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 6
|
||||
column: 32
|
||||
column: 31
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,27 +6,27 @@ expression: checks
|
||||
BadQuotesDocstring: double
|
||||
location:
|
||||
row: 1
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 3
|
||||
column: 4
|
||||
column: 3
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesDocstring: double
|
||||
location:
|
||||
row: 14
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 16
|
||||
column: 8
|
||||
column: 7
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesDocstring: double
|
||||
location:
|
||||
row: 26
|
||||
column: 9
|
||||
column: 8
|
||||
end_location:
|
||||
row: 28
|
||||
column: 12
|
||||
column: 11
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,27 +6,27 @@ expression: checks
|
||||
BadQuotesDocstring: double
|
||||
location:
|
||||
row: 2
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 2
|
||||
column: 54
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesDocstring: double
|
||||
location:
|
||||
row: 6
|
||||
column: 9
|
||||
end_location:
|
||||
row: 6
|
||||
column: 58
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesDocstring: double
|
||||
location:
|
||||
row: 9
|
||||
column: 29
|
||||
end_location:
|
||||
row: 9
|
||||
column: 53
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesDocstring: double
|
||||
location:
|
||||
row: 6
|
||||
column: 8
|
||||
end_location:
|
||||
row: 6
|
||||
column: 57
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesDocstring: double
|
||||
location:
|
||||
row: 9
|
||||
column: 28
|
||||
end_location:
|
||||
row: 9
|
||||
column: 52
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,18 +6,18 @@ expression: checks
|
||||
BadQuotesDocstring: double
|
||||
location:
|
||||
row: 2
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 2
|
||||
column: 57
|
||||
column: 56
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesDocstring: double
|
||||
location:
|
||||
row: 8
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 10
|
||||
column: 8
|
||||
column: 7
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,9 +6,9 @@ expression: checks
|
||||
BadQuotesDocstring: double
|
||||
location:
|
||||
row: 1
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 3
|
||||
column: 4
|
||||
column: 3
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,9 +6,9 @@ expression: checks
|
||||
BadQuotesDocstring: double
|
||||
location:
|
||||
row: 1
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 1
|
||||
column: 50
|
||||
column: 49
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,18 +6,18 @@ expression: checks
|
||||
BadQuotesInlineString: single
|
||||
location:
|
||||
row: 1
|
||||
column: 25
|
||||
column: 24
|
||||
end_location:
|
||||
row: 1
|
||||
column: 46
|
||||
column: 45
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesInlineString: single
|
||||
location:
|
||||
row: 2
|
||||
column: 25
|
||||
column: 24
|
||||
end_location:
|
||||
row: 2
|
||||
column: 47
|
||||
column: 46
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -5,9 +5,9 @@ expression: checks
|
||||
- kind: AvoidQuoteEscape
|
||||
location:
|
||||
row: 1
|
||||
column: 26
|
||||
column: 25
|
||||
end_location:
|
||||
row: 1
|
||||
column: 48
|
||||
column: 47
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,9 +6,9 @@ expression: checks
|
||||
BadQuotesMultilineString: single
|
||||
location:
|
||||
row: 1
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 3
|
||||
column: 13
|
||||
column: 12
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,27 +6,27 @@ expression: checks
|
||||
BadQuotesDocstring: single
|
||||
location:
|
||||
row: 1
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 3
|
||||
column: 4
|
||||
column: 3
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesDocstring: single
|
||||
location:
|
||||
row: 12
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 14
|
||||
column: 8
|
||||
column: 7
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesDocstring: single
|
||||
location:
|
||||
row: 24
|
||||
column: 9
|
||||
column: 8
|
||||
end_location:
|
||||
row: 26
|
||||
column: 12
|
||||
column: 11
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,27 +6,27 @@ expression: checks
|
||||
BadQuotesDocstring: single
|
||||
location:
|
||||
row: 2
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 2
|
||||
column: 54
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesDocstring: single
|
||||
location:
|
||||
row: 6
|
||||
column: 9
|
||||
end_location:
|
||||
row: 6
|
||||
column: 58
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesDocstring: single
|
||||
location:
|
||||
row: 9
|
||||
column: 29
|
||||
end_location:
|
||||
row: 9
|
||||
column: 53
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesDocstring: single
|
||||
location:
|
||||
row: 6
|
||||
column: 8
|
||||
end_location:
|
||||
row: 6
|
||||
column: 57
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesDocstring: single
|
||||
location:
|
||||
row: 9
|
||||
column: 28
|
||||
end_location:
|
||||
row: 9
|
||||
column: 52
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,18 +6,18 @@ expression: checks
|
||||
BadQuotesDocstring: single
|
||||
location:
|
||||
row: 2
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 2
|
||||
column: 57
|
||||
column: 56
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesDocstring: single
|
||||
location:
|
||||
row: 8
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 10
|
||||
column: 8
|
||||
column: 7
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,9 +6,9 @@ expression: checks
|
||||
BadQuotesDocstring: single
|
||||
location:
|
||||
row: 1
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 3
|
||||
column: 4
|
||||
column: 3
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,9 +6,9 @@ expression: checks
|
||||
BadQuotesDocstring: single
|
||||
location:
|
||||
row: 1
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 1
|
||||
column: 50
|
||||
column: 49
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,54 +6,54 @@ expression: checks
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 5
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 7
|
||||
column: 4
|
||||
column: 3
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 11
|
||||
column: 21
|
||||
column: 20
|
||||
end_location:
|
||||
row: 13
|
||||
column: 4
|
||||
column: 3
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 18
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 20
|
||||
column: 8
|
||||
column: 7
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 23
|
||||
column: 21
|
||||
column: 20
|
||||
end_location:
|
||||
row: 24
|
||||
column: 38
|
||||
column: 37
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 32
|
||||
column: 9
|
||||
column: 8
|
||||
end_location:
|
||||
row: 34
|
||||
column: 12
|
||||
column: 11
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 37
|
||||
column: 13
|
||||
column: 12
|
||||
end_location:
|
||||
row: 39
|
||||
column: 16
|
||||
column: 15
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,18 +6,18 @@ expression: checks
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 3
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 3
|
||||
column: 28
|
||||
column: 27
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 5
|
||||
column: 23
|
||||
column: 22
|
||||
end_location:
|
||||
row: 5
|
||||
column: 44
|
||||
column: 43
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,45 +6,45 @@ expression: checks
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 3
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 3
|
||||
column: 27
|
||||
column: 26
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 11
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 11
|
||||
column: 27
|
||||
column: 26
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 15
|
||||
column: 39
|
||||
column: 38
|
||||
end_location:
|
||||
row: 17
|
||||
column: 3
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 17
|
||||
column: 4
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 17
|
||||
column: 5
|
||||
end_location:
|
||||
row: 17
|
||||
column: 20
|
||||
column: 19
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 21
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 21
|
||||
column: 28
|
||||
column: 27
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,18 +6,18 @@ expression: checks
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 4
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 6
|
||||
column: 4
|
||||
column: 3
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 9
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 11
|
||||
column: 4
|
||||
column: 3
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,18 +6,18 @@ expression: checks
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 2
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 2
|
||||
column: 32
|
||||
column: 31
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 6
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 6
|
||||
column: 32
|
||||
column: 31
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,18 +6,18 @@ expression: checks
|
||||
BadQuotesInlineString: double
|
||||
location:
|
||||
row: 1
|
||||
column: 25
|
||||
column: 24
|
||||
end_location:
|
||||
row: 1
|
||||
column: 46
|
||||
column: 45
|
||||
fix: ~
|
||||
- kind:
|
||||
BadQuotesInlineString: double
|
||||
location:
|
||||
row: 2
|
||||
column: 25
|
||||
column: 24
|
||||
end_location:
|
||||
row: 2
|
||||
column: 47
|
||||
column: 46
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -5,9 +5,9 @@ expression: checks
|
||||
- kind: AvoidQuoteEscape
|
||||
location:
|
||||
row: 1
|
||||
column: 26
|
||||
column: 25
|
||||
end_location:
|
||||
row: 1
|
||||
column: 48
|
||||
column: 47
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,9 +6,9 @@ expression: checks
|
||||
BadQuotesMultilineString: double
|
||||
location:
|
||||
row: 1
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 3
|
||||
column: 13
|
||||
column: 12
|
||||
fix: ~
|
||||
|
||||
|
||||
30
src/lib.rs
30
src/lib.rs
@@ -10,18 +10,18 @@ use settings::pyproject;
|
||||
use settings::Settings;
|
||||
|
||||
use crate::autofix::fixer::Mode;
|
||||
use crate::checks::Check;
|
||||
use crate::linter::{check_path, tokenize};
|
||||
use crate::message::Message;
|
||||
use crate::settings::configuration::Configuration;
|
||||
|
||||
mod ast;
|
||||
mod autofix;
|
||||
pub mod autofix;
|
||||
pub mod cache;
|
||||
pub mod check_ast;
|
||||
mod check_lines;
|
||||
mod check_tokens;
|
||||
pub mod checks;
|
||||
mod checks_gen;
|
||||
pub mod checks_gen;
|
||||
pub mod cli;
|
||||
pub mod code_gen;
|
||||
mod cst;
|
||||
@@ -44,10 +44,11 @@ mod pyflakes;
|
||||
mod python;
|
||||
mod pyupgrade;
|
||||
pub mod settings;
|
||||
pub mod source_code_locator;
|
||||
pub mod visibility;
|
||||
|
||||
/// Run ruff over Python source code directly.
|
||||
pub fn check(path: &Path, contents: &str, quiet: bool) -> Result<Vec<Message>> {
|
||||
pub fn check(path: &Path, contents: &str) -> Result<Vec<Check>> {
|
||||
// Find the project root and pyproject.toml.
|
||||
let project_root = pyproject::find_project_root(&[path.to_path_buf()]);
|
||||
match &project_root {
|
||||
@@ -60,11 +61,8 @@ pub fn check(path: &Path, contents: &str, quiet: bool) -> Result<Vec<Message>> {
|
||||
None => debug!("Unable to find pyproject.toml; using default settings..."),
|
||||
};
|
||||
|
||||
let settings = Settings::from_configuration(Configuration::from_pyproject(
|
||||
&pyproject,
|
||||
&project_root,
|
||||
quiet,
|
||||
)?);
|
||||
let settings =
|
||||
Settings::from_configuration(Configuration::from_pyproject(&pyproject, &project_root)?);
|
||||
|
||||
// Tokenize once.
|
||||
let tokens: Vec<LexResult> = tokenize(contents);
|
||||
@@ -82,17 +80,5 @@ pub fn check(path: &Path, contents: &str, quiet: bool) -> Result<Vec<Message>> {
|
||||
&Mode::None,
|
||||
)?;
|
||||
|
||||
// Convert to messages.
|
||||
let messages: Vec<Message> = checks
|
||||
.into_iter()
|
||||
.map(|check| Message {
|
||||
kind: check.kind,
|
||||
fixed: check.fix.map(|fix| fix.applied).unwrap_or_default(),
|
||||
location: check.location,
|
||||
end_location: check.end_location,
|
||||
filename: path.to_string_lossy().to_string(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(messages)
|
||||
Ok(checks)
|
||||
}
|
||||
|
||||
@@ -6,7 +6,10 @@ use std::path::Path;
|
||||
use anyhow::Result;
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use log::debug;
|
||||
use rustpython_ast::{Mod, Suite};
|
||||
use rustpython_parser::error::ParseError;
|
||||
use rustpython_parser::lexer::LexResult;
|
||||
use rustpython_parser::parser::Mode;
|
||||
use rustpython_parser::{lexer, parser};
|
||||
|
||||
use crate::ast::types::Range;
|
||||
@@ -20,6 +23,7 @@ use crate::code_gen::SourceGenerator;
|
||||
use crate::message::Message;
|
||||
use crate::noqa::add_noqa;
|
||||
use crate::settings::Settings;
|
||||
use crate::source_code_locator::SourceCodeLocator;
|
||||
use crate::{cache, fs, noqa};
|
||||
|
||||
/// Collect tokens up to and including the first error.
|
||||
@@ -35,6 +39,17 @@ pub(crate) fn tokenize(contents: &str) -> Vec<LexResult> {
|
||||
tokens
|
||||
}
|
||||
|
||||
/// Parse a full Python program from its tokens.
|
||||
pub(crate) fn parse_program_tokens(
|
||||
lxr: Vec<LexResult>,
|
||||
source_path: &str,
|
||||
) -> Result<Suite, ParseError> {
|
||||
parser::parse_tokens(lxr, Mode::Module, source_path).map(|top| match top {
|
||||
Mod::Module { body, .. } => body,
|
||||
_ => unreachable!(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn check_path(
|
||||
path: &Path,
|
||||
contents: &str,
|
||||
@@ -46,13 +61,16 @@ pub(crate) fn check_path(
|
||||
// Aggregate all checks.
|
||||
let mut checks: Vec<Check> = vec![];
|
||||
|
||||
// Initialize the SourceCodeLocator (which computes offsets lazily).
|
||||
let locator = SourceCodeLocator::new(contents);
|
||||
|
||||
// Run the token-based checks.
|
||||
if settings
|
||||
.enabled
|
||||
.iter()
|
||||
.any(|check_code| matches!(check_code.lint_source(), LintSource::Tokens))
|
||||
{
|
||||
check_tokens(&mut checks, contents, &tokens, settings);
|
||||
check_tokens(&mut checks, &locator, &tokens, settings);
|
||||
}
|
||||
|
||||
// Run the AST-based checks.
|
||||
@@ -61,9 +79,9 @@ pub(crate) fn check_path(
|
||||
.iter()
|
||||
.any(|check_code| matches!(check_code.lint_source(), LintSource::AST))
|
||||
{
|
||||
match parser::parse_program_tokens(tokens, "<filename>") {
|
||||
match parse_program_tokens(tokens, "<filename>") {
|
||||
Ok(python_ast) => {
|
||||
checks.extend(check_ast(&python_ast, contents, settings, autofix, path))
|
||||
checks.extend(check_ast(&python_ast, &locator, settings, autofix, path))
|
||||
}
|
||||
Err(parse_error) => {
|
||||
if settings.enabled.contains(&CheckCode::E999) {
|
||||
@@ -216,7 +234,7 @@ pub fn autoformat_path(path: &Path) -> Result<()> {
|
||||
let tokens: Vec<LexResult> = tokenize(&contents);
|
||||
|
||||
// Generate the AST.
|
||||
let python_ast = parser::parse_program_tokens(tokens, "<filename>")?;
|
||||
let python_ast = parse_program_tokens(tokens, "<filename>")?;
|
||||
let mut generator: SourceGenerator = Default::default();
|
||||
generator.unparse_suite(&python_ast)?;
|
||||
write(path, generator.generate()?)?;
|
||||
@@ -252,6 +270,7 @@ mod tests {
|
||||
#[test_case(CheckCode::A002, Path::new("A002.py"); "A002")]
|
||||
#[test_case(CheckCode::A003, Path::new("A003.py"); "A003")]
|
||||
#[test_case(CheckCode::B002, Path::new("B002.py"); "B002")]
|
||||
#[test_case(CheckCode::B006, Path::new("B006_B008.py"); "B006")]
|
||||
#[test_case(CheckCode::B007, Path::new("B007.py"); "B007")]
|
||||
#[test_case(CheckCode::B011, Path::new("B011.py"); "B011")]
|
||||
#[test_case(CheckCode::B013, Path::new("B013.py"); "B013")]
|
||||
@@ -358,7 +377,8 @@ mod tests {
|
||||
#[test_case(CheckCode::F706, Path::new("F706.py"); "F706")]
|
||||
#[test_case(CheckCode::F707, Path::new("F707.py"); "F707")]
|
||||
#[test_case(CheckCode::F722, Path::new("F722.py"); "F722")]
|
||||
#[test_case(CheckCode::F821, Path::new("F821.py"); "F821")]
|
||||
#[test_case(CheckCode::F821, Path::new("F821_0.py"); "F821_0")]
|
||||
#[test_case(CheckCode::F821, Path::new("F821_1.py"); "F821_1")]
|
||||
#[test_case(CheckCode::F822, Path::new("F822.py"); "F822")]
|
||||
#[test_case(CheckCode::F823, Path::new("F823.py"); "F823")]
|
||||
#[test_case(CheckCode::F831, Path::new("F831.py"); "F831")]
|
||||
|
||||
15
src/main.rs
15
src/main.rs
@@ -1,3 +1,4 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{self, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
@@ -17,7 +18,8 @@ use walkdir::DirEntry;
|
||||
use ruff::cache;
|
||||
use ruff::checks::CheckCode;
|
||||
use ruff::checks::CheckKind;
|
||||
use ruff::cli::{warn_on, Cli, Warnable};
|
||||
use ruff::checks_gen::CheckCodePrefix;
|
||||
use ruff::cli::{collect_per_file_ignores, warn_on, Cli, Warnable};
|
||||
use ruff::fs::iter_python_files;
|
||||
use ruff::linter::add_noqa_to_path;
|
||||
use ruff::linter::autoformat_path;
|
||||
@@ -27,7 +29,7 @@ use ruff::message::Message;
|
||||
use ruff::printer::{Printer, SerializationFormat};
|
||||
use ruff::settings::configuration::Configuration;
|
||||
use ruff::settings::pyproject;
|
||||
use ruff::settings::types::{FilePattern, PerFileIgnore};
|
||||
use ruff::settings::types::FilePattern;
|
||||
use ruff::settings::user::UserConfiguration;
|
||||
use ruff::settings::Settings;
|
||||
use ruff::tell_user;
|
||||
@@ -255,13 +257,10 @@ fn inner_main() -> Result<ExitCode> {
|
||||
.iter()
|
||||
.map(|path| FilePattern::from_user(path, &project_root))
|
||||
.collect();
|
||||
let per_file_ignores: Vec<PerFileIgnore> = cli
|
||||
.per_file_ignores
|
||||
.into_iter()
|
||||
.map(|pair| PerFileIgnore::new(pair, &project_root))
|
||||
.collect();
|
||||
let per_file_ignores: BTreeMap<String, Vec<CheckCodePrefix>> =
|
||||
collect_per_file_ignores(cli.per_file_ignores);
|
||||
|
||||
let mut configuration = Configuration::from_pyproject(&pyproject, &project_root, cli.quiet)?;
|
||||
let mut configuration = Configuration::from_pyproject(&pyproject, &project_root)?;
|
||||
if !exclude.is_empty() {
|
||||
configuration.exclude = exclude;
|
||||
}
|
||||
|
||||
20
src/noqa.rs
20
src/noqa.rs
@@ -246,8 +246,8 @@ ghi
|
||||
let checks = vec![Check::new(
|
||||
CheckKind::UnusedVariable("x".to_string()),
|
||||
Range {
|
||||
location: Location::new(1, 1),
|
||||
end_location: Location::new(1, 1),
|
||||
location: Location::new(1, 0),
|
||||
end_location: Location::new(1, 0),
|
||||
},
|
||||
)];
|
||||
let contents = "x = 1";
|
||||
@@ -260,15 +260,15 @@ ghi
|
||||
Check::new(
|
||||
CheckKind::AmbiguousVariableName("x".to_string()),
|
||||
Range {
|
||||
location: Location::new(1, 1),
|
||||
end_location: Location::new(1, 1),
|
||||
location: Location::new(1, 0),
|
||||
end_location: Location::new(1, 0),
|
||||
},
|
||||
),
|
||||
Check::new(
|
||||
CheckKind::UnusedVariable("x".to_string()),
|
||||
Range {
|
||||
location: Location::new(1, 1),
|
||||
end_location: Location::new(1, 1),
|
||||
location: Location::new(1, 0),
|
||||
end_location: Location::new(1, 0),
|
||||
},
|
||||
),
|
||||
];
|
||||
@@ -282,15 +282,15 @@ ghi
|
||||
Check::new(
|
||||
CheckKind::AmbiguousVariableName("x".to_string()),
|
||||
Range {
|
||||
location: Location::new(1, 1),
|
||||
end_location: Location::new(1, 1),
|
||||
location: Location::new(1, 0),
|
||||
end_location: Location::new(1, 0),
|
||||
},
|
||||
),
|
||||
Check::new(
|
||||
CheckKind::UnusedVariable("x".to_string()),
|
||||
Range {
|
||||
location: Location::new(1, 1),
|
||||
end_location: Location::new(1, 1),
|
||||
location: Location::new(1, 0),
|
||||
end_location: Location::new(1, 0),
|
||||
},
|
||||
),
|
||||
];
|
||||
|
||||
@@ -3,7 +3,9 @@ use rustpython_ast::{Arguments, Expr, ExprKind, Stmt};
|
||||
|
||||
use crate::ast::types::{FunctionScope, Range, Scope, ScopeKind};
|
||||
use crate::checks::{Check, CheckKind};
|
||||
use crate::pep8_naming::settings::Settings;
|
||||
|
||||
/// N801
|
||||
pub fn invalid_class_name(class_def: &Stmt, name: &str) -> Option<Check> {
|
||||
let stripped = name.strip_prefix('_').unwrap_or(name);
|
||||
if !stripped
|
||||
@@ -21,23 +23,14 @@ pub fn invalid_class_name(class_def: &Stmt, name: &str) -> Option<Check> {
|
||||
None
|
||||
}
|
||||
|
||||
const IGNORE_NAMES: &[&str] = &[
|
||||
"setUp",
|
||||
"tearDown",
|
||||
"setUpClass",
|
||||
"tearDownClass",
|
||||
"setUpModule",
|
||||
"tearDownModule",
|
||||
"asyncSetUp",
|
||||
"asyncTearDown",
|
||||
"setUpTestData",
|
||||
"failureException",
|
||||
"longMessage",
|
||||
"maxDiff",
|
||||
];
|
||||
|
||||
pub fn invalid_function_name(func_def: &Stmt, name: &str) -> Option<Check> {
|
||||
if !is_lower(name) && !IGNORE_NAMES.contains(&name) {
|
||||
/// N802
|
||||
pub fn invalid_function_name(func_def: &Stmt, name: &str, settings: &Settings) -> Option<Check> {
|
||||
if !is_lower(name)
|
||||
&& !settings
|
||||
.ignore_names
|
||||
.iter()
|
||||
.any(|ignore_name| ignore_name == name)
|
||||
{
|
||||
return Some(Check::new(
|
||||
CheckKind::InvalidFunctionName(name.to_string()),
|
||||
Range::from_located(func_def),
|
||||
@@ -46,6 +39,7 @@ pub fn invalid_function_name(func_def: &Stmt, name: &str) -> Option<Check> {
|
||||
None
|
||||
}
|
||||
|
||||
/// N803
|
||||
pub fn invalid_argument_name(location: Range, name: &str) -> Option<Check> {
|
||||
if !is_lower(name) {
|
||||
return Some(Check::new(
|
||||
@@ -56,10 +50,12 @@ pub fn invalid_argument_name(location: Range, name: &str) -> Option<Check> {
|
||||
None
|
||||
}
|
||||
|
||||
/// N804
|
||||
pub fn invalid_first_argument_name_for_class_method(
|
||||
scope: &Scope,
|
||||
decorator_list: &[Expr],
|
||||
args: &Arguments,
|
||||
settings: &Settings,
|
||||
) -> Option<Check> {
|
||||
if !matches!(scope.kind, ScopeKind::Class) {
|
||||
return None;
|
||||
@@ -67,7 +63,7 @@ pub fn invalid_first_argument_name_for_class_method(
|
||||
|
||||
if decorator_list.iter().any(|decorator| {
|
||||
if let ExprKind::Name { id, .. } = &decorator.node {
|
||||
id == "classmethod"
|
||||
settings.classmethod_decorators.contains(id)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
@@ -84,10 +80,12 @@ pub fn invalid_first_argument_name_for_class_method(
|
||||
None
|
||||
}
|
||||
|
||||
/// N805
|
||||
pub fn invalid_first_argument_name_for_method(
|
||||
scope: &Scope,
|
||||
decorator_list: &[Expr],
|
||||
args: &Arguments,
|
||||
settings: &Settings,
|
||||
) -> Option<Check> {
|
||||
if !matches!(scope.kind, ScopeKind::Class) {
|
||||
return None;
|
||||
@@ -95,7 +93,8 @@ pub fn invalid_first_argument_name_for_method(
|
||||
|
||||
if decorator_list.iter().any(|decorator| {
|
||||
if let ExprKind::Name { id, .. } = &decorator.node {
|
||||
id == "classmethod" || id == "staticmethod"
|
||||
settings.classmethod_decorators.contains(id)
|
||||
|| settings.staticmethod_decorators.contains(id)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
@@ -114,6 +113,7 @@ pub fn invalid_first_argument_name_for_method(
|
||||
None
|
||||
}
|
||||
|
||||
/// N806
|
||||
pub fn non_lowercase_variable_in_function(scope: &Scope, expr: &Expr, name: &str) -> Option<Check> {
|
||||
if !matches!(scope.kind, ScopeKind::Function(FunctionScope { .. })) {
|
||||
return None;
|
||||
@@ -127,6 +127,83 @@ pub fn non_lowercase_variable_in_function(scope: &Scope, expr: &Expr, name: &str
|
||||
None
|
||||
}
|
||||
|
||||
/// N807
|
||||
pub fn dunder_function_name(func_def: &Stmt, scope: &Scope, name: &str) -> Option<Check> {
|
||||
if matches!(scope.kind, ScopeKind::Class) {
|
||||
return None;
|
||||
}
|
||||
|
||||
if name.starts_with("__") && name.ends_with("__") {
|
||||
return Some(Check::new(
|
||||
CheckKind::DunderFunctionName,
|
||||
Range::from_located(func_def),
|
||||
));
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// N811
|
||||
pub fn constant_imported_as_non_constant(
|
||||
import_from: &Stmt,
|
||||
name: &str,
|
||||
asname: &str,
|
||||
) -> Option<Check> {
|
||||
if is_upper(name) && !is_upper(asname) {
|
||||
return Some(Check::new(
|
||||
CheckKind::ConstantImportedAsNonConstant(name.to_string(), asname.to_string()),
|
||||
Range::from_located(import_from),
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// N812
|
||||
pub fn lowercase_imported_as_non_lowercase(
|
||||
import_from: &Stmt,
|
||||
name: &str,
|
||||
asname: &str,
|
||||
) -> Option<Check> {
|
||||
if is_lower(name) && asname.to_lowercase() != asname {
|
||||
return Some(Check::new(
|
||||
CheckKind::LowercaseImportedAsNonLowercase(name.to_string(), asname.to_string()),
|
||||
Range::from_located(import_from),
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// N813
|
||||
pub fn camelcase_imported_as_lowercase(
|
||||
import_from: &Stmt,
|
||||
name: &str,
|
||||
asname: &str,
|
||||
) -> Option<Check> {
|
||||
if is_camelcase(name) && is_lower(asname) {
|
||||
return Some(Check::new(
|
||||
CheckKind::CamelcaseImportedAsLowercase(name.to_string(), asname.to_string()),
|
||||
Range::from_located(import_from),
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// N814
|
||||
pub fn camelcase_imported_as_constant(
|
||||
import_from: &Stmt,
|
||||
name: &str,
|
||||
asname: &str,
|
||||
) -> Option<Check> {
|
||||
if is_camelcase(name) && is_upper(asname) && !is_acronym(name, asname) {
|
||||
return Some(Check::new(
|
||||
CheckKind::CamelcaseImportedAsConstant(name.to_string(), asname.to_string()),
|
||||
Range::from_located(import_from),
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// N815
|
||||
pub fn mixed_case_variable_in_class_scope(scope: &Scope, expr: &Expr, name: &str) -> Option<Check> {
|
||||
if !matches!(scope.kind, ScopeKind::Class) {
|
||||
return None;
|
||||
@@ -140,6 +217,7 @@ pub fn mixed_case_variable_in_class_scope(scope: &Scope, expr: &Expr, name: &str
|
||||
None
|
||||
}
|
||||
|
||||
/// N816
|
||||
pub fn mixed_case_variable_in_global_scope(
|
||||
scope: &Scope,
|
||||
expr: &Expr,
|
||||
@@ -157,18 +235,41 @@ pub fn mixed_case_variable_in_global_scope(
|
||||
None
|
||||
}
|
||||
|
||||
pub fn dunder_function_name(func_def: &Stmt, scope: &Scope, name: &str) -> Option<Check> {
|
||||
if matches!(scope.kind, ScopeKind::Class) {
|
||||
return None;
|
||||
}
|
||||
|
||||
if name.starts_with("__") && name.ends_with("__") {
|
||||
/// N817
|
||||
pub fn camelcase_imported_as_acronym(
|
||||
import_from: &Stmt,
|
||||
name: &str,
|
||||
asname: &str,
|
||||
) -> Option<Check> {
|
||||
if is_camelcase(name) && is_upper(asname) && is_acronym(name, asname) {
|
||||
return Some(Check::new(
|
||||
CheckKind::DunderFunctionName,
|
||||
Range::from_located(func_def),
|
||||
CheckKind::CamelcaseImportedAsAcronym(name.to_string(), asname.to_string()),
|
||||
Range::from_located(import_from),
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// N818
|
||||
pub fn error_suffix_on_exception_name(
|
||||
class_def: &Stmt,
|
||||
bases: &[Expr],
|
||||
name: &str,
|
||||
) -> Option<Check> {
|
||||
if bases.iter().any(|base| {
|
||||
if let ExprKind::Name { id, .. } = &base.node {
|
||||
id == "Exception"
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}) {
|
||||
if !name.ends_with("Error") {
|
||||
return Some(Check::new(
|
||||
CheckKind::ErrorSuffixOnExceptionName(name.to_string()),
|
||||
Range::from_located(class_def),
|
||||
));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
@@ -196,34 +297,6 @@ fn is_upper(s: &str) -> bool {
|
||||
cased
|
||||
}
|
||||
|
||||
pub fn constant_imported_as_non_constant(
|
||||
import_from: &Stmt,
|
||||
name: &str,
|
||||
asname: &str,
|
||||
) -> Option<Check> {
|
||||
if is_upper(name) && !is_upper(asname) {
|
||||
return Some(Check::new(
|
||||
CheckKind::ConstantImportedAsNonConstant(name.to_string(), asname.to_string()),
|
||||
Range::from_located(import_from),
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn lowercase_imported_as_non_lowercase(
|
||||
import_from: &Stmt,
|
||||
name: &str,
|
||||
asname: &str,
|
||||
) -> Option<Check> {
|
||||
if is_lower(name) && asname.to_lowercase() != asname {
|
||||
return Some(Check::new(
|
||||
CheckKind::LowercaseImportedAsNonLowercase(name.to_string(), asname.to_string()),
|
||||
Range::from_located(import_from),
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn is_camelcase(name: &str) -> bool {
|
||||
!is_lower(name) && !is_upper(name) && !name.contains('_')
|
||||
}
|
||||
@@ -242,70 +315,6 @@ fn is_acronym(name: &str, asname: &str) -> bool {
|
||||
name.chars().filter(|c| c.is_uppercase()).join("") == asname
|
||||
}
|
||||
|
||||
pub fn camelcase_imported_as_lowercase(
|
||||
import_from: &Stmt,
|
||||
name: &str,
|
||||
asname: &str,
|
||||
) -> Option<Check> {
|
||||
if is_camelcase(name) && is_lower(asname) {
|
||||
return Some(Check::new(
|
||||
CheckKind::CamelcaseImportedAsLowercase(name.to_string(), asname.to_string()),
|
||||
Range::from_located(import_from),
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn camelcase_imported_as_constant(
|
||||
import_from: &Stmt,
|
||||
name: &str,
|
||||
asname: &str,
|
||||
) -> Option<Check> {
|
||||
if is_camelcase(name) && is_upper(asname) && !is_acronym(name, asname) {
|
||||
return Some(Check::new(
|
||||
CheckKind::CamelcaseImportedAsConstant(name.to_string(), asname.to_string()),
|
||||
Range::from_located(import_from),
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn camelcase_imported_as_acronym(
|
||||
import_from: &Stmt,
|
||||
name: &str,
|
||||
asname: &str,
|
||||
) -> Option<Check> {
|
||||
if is_camelcase(name) && is_upper(asname) && is_acronym(name, asname) {
|
||||
return Some(Check::new(
|
||||
CheckKind::CamelcaseImportedAsAcronym(name.to_string(), asname.to_string()),
|
||||
Range::from_located(import_from),
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn error_suffix_on_exception_name(
|
||||
class_def: &Stmt,
|
||||
bases: &[Expr],
|
||||
name: &str,
|
||||
) -> Option<Check> {
|
||||
if bases.iter().any(|base| {
|
||||
if let ExprKind::Name { id, .. } = &base.node {
|
||||
id == "Exception"
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}) {
|
||||
if !name.ends_with("Error") {
|
||||
return Some(Check::new(
|
||||
CheckKind::ErrorSuffixOnExceptionName(name.to_string()),
|
||||
Range::from_located(class_def),
|
||||
));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{is_acronym, is_camelcase, is_lower, is_mixed_case, is_upper};
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
pub mod checks;
|
||||
pub mod settings;
|
||||
|
||||
63
src/pep8_naming/settings.rs
Normal file
63
src/pep8_naming/settings.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
//! Settings for the `pep8-naming` plugin.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const IGNORE_NAMES: [&str; 12] = [
|
||||
"setUp",
|
||||
"tearDown",
|
||||
"setUpClass",
|
||||
"tearDownClass",
|
||||
"setUpModule",
|
||||
"tearDownModule",
|
||||
"asyncSetUp",
|
||||
"asyncTearDown",
|
||||
"setUpTestData",
|
||||
"failureException",
|
||||
"longMessage",
|
||||
"maxDiff",
|
||||
];
|
||||
|
||||
const CLASSMETHOD_DECORATORS: [&str; 1] = ["classmethod"];
|
||||
|
||||
const STATICMETHOD_DECORATORS: [&str; 1] = ["staticmethod"];
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct Options {
|
||||
pub ignore_names: Option<Vec<String>>,
|
||||
pub classmethod_decorators: Option<Vec<String>>,
|
||||
pub staticmethod_decorators: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Settings {
|
||||
pub ignore_names: Vec<String>,
|
||||
pub classmethod_decorators: Vec<String>,
|
||||
pub staticmethod_decorators: Vec<String>,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
pub fn from_options(options: Options) -> Self {
|
||||
Self {
|
||||
ignore_names: options
|
||||
.ignore_names
|
||||
.unwrap_or_else(|| IGNORE_NAMES.map(String::from).to_vec()),
|
||||
classmethod_decorators: options
|
||||
.classmethod_decorators
|
||||
.unwrap_or_else(|| CLASSMETHOD_DECORATORS.map(String::from).to_vec()),
|
||||
staticmethod_decorators: options
|
||||
.staticmethod_decorators
|
||||
.unwrap_or_else(|| STATICMETHOD_DECORATORS.map(String::from).to_vec()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
ignore_names: IGNORE_NAMES.map(String::from).to_vec(),
|
||||
classmethod_decorators: CLASSMETHOD_DECORATORS.map(String::from).to_vec(),
|
||||
staticmethod_decorators: STATICMETHOD_DECORATORS.map(String::from).to_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,9 @@ use itertools::izip;
|
||||
use rustpython_ast::Location;
|
||||
use rustpython_parser::ast::{Cmpop, Constant, Expr, ExprKind, Unaryop};
|
||||
|
||||
use crate::ast::operations::SourceCodeLocator;
|
||||
use crate::ast::types::{CheckLocator, Range};
|
||||
use crate::checks::{Check, CheckKind, RejectedCmpop};
|
||||
use crate::source_code_locator::SourceCodeLocator;
|
||||
|
||||
fn is_ambiguous_name(name: &str) -> bool {
|
||||
name == "l" || name == "I" || name == "O"
|
||||
|
||||
@@ -35,8 +35,8 @@ pub fn not_missing(
|
||||
checker.add_check(Check::new(
|
||||
CheckKind::PublicModule,
|
||||
Range {
|
||||
location: Location::new(1, 1),
|
||||
end_location: Location::new(1, 1),
|
||||
location: Location::new(1, 0),
|
||||
end_location: Location::new(1, 0),
|
||||
},
|
||||
));
|
||||
}
|
||||
@@ -47,8 +47,8 @@ pub fn not_missing(
|
||||
checker.add_check(Check::new(
|
||||
CheckKind::PublicPackage,
|
||||
Range {
|
||||
location: Location::new(1, 1),
|
||||
end_location: Location::new(1, 1),
|
||||
location: Location::new(1, 0),
|
||||
end_location: Location::new(1, 0),
|
||||
},
|
||||
));
|
||||
}
|
||||
@@ -162,7 +162,7 @@ pub fn blank_before_after_function(checker: &mut Checker, definition: &Definitio
|
||||
} = &docstring.node
|
||||
{
|
||||
if checker.settings.enabled.contains(&CheckCode::D201) {
|
||||
let (before, _, _) = checker.get_locator().partition_source_code_at(
|
||||
let (before, _, _) = checker.locator.partition_source_code_at(
|
||||
&Range::from_located(parent),
|
||||
&Range::from_located(docstring),
|
||||
);
|
||||
@@ -181,8 +181,8 @@ pub fn blank_before_after_function(checker: &mut Checker, definition: &Definitio
|
||||
if checker.patch() {
|
||||
// Delete the blank line before the docstring.
|
||||
check.amend(Fix::deletion(
|
||||
Location::new(docstring.location.row() - blank_lines_before, 1),
|
||||
Location::new(docstring.location.row(), 1),
|
||||
Location::new(docstring.location.row() - blank_lines_before, 0),
|
||||
Location::new(docstring.location.row(), 0),
|
||||
));
|
||||
}
|
||||
checker.add_check(check);
|
||||
@@ -190,7 +190,7 @@ pub fn blank_before_after_function(checker: &mut Checker, definition: &Definitio
|
||||
}
|
||||
|
||||
if checker.settings.enabled.contains(&CheckCode::D202) {
|
||||
let (_, _, after) = checker.get_locator().partition_source_code_at(
|
||||
let (_, _, after) = checker.locator.partition_source_code_at(
|
||||
&Range::from_located(parent),
|
||||
&Range::from_located(docstring),
|
||||
);
|
||||
@@ -208,15 +208,13 @@ pub fn blank_before_after_function(checker: &mut Checker, definition: &Definitio
|
||||
.skip(1)
|
||||
.take_while(|line| line.trim().is_empty())
|
||||
.count();
|
||||
// Report a D202 violation if the docstring is followed by a blank line and the
|
||||
// blank line is not itself followed by an inner function or class.
|
||||
let expected_blank_lines_after =
|
||||
if INNER_FUNCTION_OR_CLASS_REGEX.is_match(after) {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if blank_lines_after != expected_blank_lines_after {
|
||||
|
||||
// Avoid D202 violations for blank lines followed by inner functions or classes.
|
||||
if blank_lines_after == 1 && INNER_FUNCTION_OR_CLASS_REGEX.is_match(after) {
|
||||
return;
|
||||
}
|
||||
|
||||
if blank_lines_after != 0 {
|
||||
let mut check = Check::new(
|
||||
CheckKind::NoBlankLineAfterFunction(blank_lines_after),
|
||||
Range::from_located(docstring),
|
||||
@@ -224,11 +222,8 @@ pub fn blank_before_after_function(checker: &mut Checker, definition: &Definitio
|
||||
if checker.patch() {
|
||||
// Delete the blank line after the docstring.
|
||||
check.amend(Fix::deletion(
|
||||
Location::new(
|
||||
docstring.location.row() + 1 + expected_blank_lines_after,
|
||||
1,
|
||||
),
|
||||
Location::new(docstring.location.row() + 1 + blank_lines_after, 1),
|
||||
Location::new(docstring.location.row() + 1, 0),
|
||||
Location::new(docstring.location.row() + 1 + blank_lines_after, 0),
|
||||
));
|
||||
}
|
||||
checker.add_check(check);
|
||||
@@ -253,7 +248,7 @@ pub fn blank_before_after_class(checker: &mut Checker, definition: &Definition)
|
||||
if checker.settings.enabled.contains(&CheckCode::D203)
|
||||
|| checker.settings.enabled.contains(&CheckCode::D211)
|
||||
{
|
||||
let (before, _, _) = checker.get_locator().partition_source_code_at(
|
||||
let (before, _, _) = checker.locator.partition_source_code_at(
|
||||
&Range::from_located(parent),
|
||||
&Range::from_located(docstring),
|
||||
);
|
||||
@@ -273,8 +268,8 @@ pub fn blank_before_after_class(checker: &mut Checker, definition: &Definition)
|
||||
if checker.patch() {
|
||||
// Delete the blank line before the class.
|
||||
check.amend(Fix::deletion(
|
||||
Location::new(docstring.location.row() - blank_lines_before, 1),
|
||||
Location::new(docstring.location.row(), 1),
|
||||
Location::new(docstring.location.row() - blank_lines_before, 0),
|
||||
Location::new(docstring.location.row(), 0),
|
||||
));
|
||||
}
|
||||
checker.add_check(check);
|
||||
@@ -290,8 +285,8 @@ pub fn blank_before_after_class(checker: &mut Checker, definition: &Definition)
|
||||
// Insert one blank line before the class.
|
||||
check.amend(Fix::replacement(
|
||||
"\n".to_string(),
|
||||
Location::new(docstring.location.row() - blank_lines_before, 1),
|
||||
Location::new(docstring.location.row(), 1),
|
||||
Location::new(docstring.location.row() - blank_lines_before, 0),
|
||||
Location::new(docstring.location.row(), 0),
|
||||
));
|
||||
}
|
||||
checker.add_check(check);
|
||||
@@ -300,7 +295,7 @@ pub fn blank_before_after_class(checker: &mut Checker, definition: &Definition)
|
||||
}
|
||||
|
||||
if checker.settings.enabled.contains(&CheckCode::D204) {
|
||||
let (_, _, after) = checker.get_locator().partition_source_code_at(
|
||||
let (_, _, after) = checker.locator.partition_source_code_at(
|
||||
&Range::from_located(parent),
|
||||
&Range::from_located(docstring),
|
||||
);
|
||||
@@ -327,10 +322,10 @@ pub fn blank_before_after_class(checker: &mut Checker, definition: &Definition)
|
||||
// Insert a blank line before the class (replacing any existing lines).
|
||||
check.amend(Fix::replacement(
|
||||
"\n".to_string(),
|
||||
Location::new(docstring.end_location.unwrap().row() + 1, 1),
|
||||
Location::new(docstring.end_location.unwrap().row() + 1, 0),
|
||||
Location::new(
|
||||
docstring.end_location.unwrap().row() + 1 + blank_lines_after,
|
||||
1,
|
||||
0,
|
||||
),
|
||||
));
|
||||
}
|
||||
@@ -369,8 +364,8 @@ pub fn blank_after_summary(checker: &mut Checker, definition: &Definition) {
|
||||
// Insert one blank line after the summary (replacing any existing lines).
|
||||
check.amend(Fix::replacement(
|
||||
"\n".to_string(),
|
||||
Location::new(docstring.location.row() + 1, 1),
|
||||
Location::new(docstring.location.row() + 1 + blanks_count, 1),
|
||||
Location::new(docstring.location.row() + 1, 0),
|
||||
Location::new(docstring.location.row() + 1 + blanks_count, 0),
|
||||
));
|
||||
}
|
||||
checker.add_check(check);
|
||||
@@ -404,7 +399,8 @@ pub fn indent(checker: &mut Checker, definition: &Definition) {
|
||||
|
||||
// Omit empty lines, except for the last line, which is non-empty by way of
|
||||
// containing the closing quotation marks.
|
||||
if i < lines.len() - 1 && lines[i].trim().is_empty() {
|
||||
let is_blank = lines[i].trim().is_empty();
|
||||
if i < lines.len() - 1 && is_blank {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -416,19 +412,19 @@ pub fn indent(checker: &mut Checker, definition: &Definition) {
|
||||
if checker.settings.enabled.contains(&CheckCode::D207) {
|
||||
// We report under-indentation on every line. This isn't great, but enables
|
||||
// autofix.
|
||||
if line_indent.len() < docstring_indent.len() {
|
||||
if !is_blank && line_indent.len() < docstring_indent.len() {
|
||||
let mut check = Check::new(
|
||||
CheckKind::NoUnderIndentation,
|
||||
Range {
|
||||
location: Location::new(docstring.location.row() + i, 1),
|
||||
end_location: Location::new(docstring.location.row() + i, 1),
|
||||
location: Location::new(docstring.location.row() + i, 0),
|
||||
end_location: Location::new(docstring.location.row() + i, 0),
|
||||
},
|
||||
);
|
||||
if checker.patch() {
|
||||
check.amend(Fix::replacement(
|
||||
helpers::clean(&docstring_indent),
|
||||
Location::new(docstring.location.row() + i, 1),
|
||||
Location::new(docstring.location.row() + i, 1 + line_indent.len()),
|
||||
Location::new(docstring.location.row() + i, 0),
|
||||
Location::new(docstring.location.row() + i, line_indent.len()),
|
||||
));
|
||||
}
|
||||
checker.add_check(check);
|
||||
@@ -469,18 +465,15 @@ pub fn indent(checker: &mut Checker, definition: &Definition) {
|
||||
let mut check = Check::new(
|
||||
CheckKind::NoOverIndentation,
|
||||
Range {
|
||||
location: Location::new(docstring.location.row() + i, 1),
|
||||
end_location: Location::new(docstring.location.row() + i, 1),
|
||||
location: Location::new(docstring.location.row() + i, 0),
|
||||
end_location: Location::new(docstring.location.row() + i, 0),
|
||||
},
|
||||
);
|
||||
if checker.patch() {
|
||||
check.amend(Fix::replacement(
|
||||
helpers::clean(&docstring_indent),
|
||||
Location::new(docstring.location.row() + i, 1),
|
||||
Location::new(
|
||||
docstring.location.row() + i,
|
||||
1 + line_indent.len(),
|
||||
),
|
||||
Location::new(docstring.location.row() + i, 0),
|
||||
Location::new(docstring.location.row() + i, line_indent.len()),
|
||||
));
|
||||
}
|
||||
checker.add_check(check);
|
||||
@@ -496,15 +489,15 @@ pub fn indent(checker: &mut Checker, definition: &Definition) {
|
||||
let mut check = Check::new(
|
||||
CheckKind::NoOverIndentation,
|
||||
Range {
|
||||
location: Location::new(docstring.location.row() + i, 1),
|
||||
end_location: Location::new(docstring.location.row() + i, 1),
|
||||
location: Location::new(docstring.location.row() + i, 0),
|
||||
end_location: Location::new(docstring.location.row() + i, 0),
|
||||
},
|
||||
);
|
||||
if checker.patch() {
|
||||
check.amend(Fix::replacement(
|
||||
helpers::clean(&docstring_indent),
|
||||
Location::new(docstring.location.row() + i, 1),
|
||||
Location::new(docstring.location.row() + i, 1 + line_indent.len()),
|
||||
Location::new(docstring.location.row() + i, 0),
|
||||
Location::new(docstring.location.row() + i, line_indent.len()),
|
||||
));
|
||||
}
|
||||
checker.add_check(check);
|
||||
@@ -530,7 +523,7 @@ pub fn newline_after_last_paragraph(checker: &mut Checker, definition: &Definiti
|
||||
}
|
||||
if line_count > 1 {
|
||||
let content = checker
|
||||
.get_locator()
|
||||
.locator
|
||||
.slice_source_code_range(&Range::from_located(docstring));
|
||||
if let Some(last_line) = content.lines().last().map(|line| line.trim()) {
|
||||
if last_line != "\"\"\"" && last_line != "'''" {
|
||||
@@ -583,7 +576,7 @@ pub fn no_surrounding_whitespace(checker: &mut Checker, definition: &Definition)
|
||||
);
|
||||
if checker.patch() {
|
||||
if let Some(first_line) = checker
|
||||
.get_locator()
|
||||
.locator
|
||||
.slice_source_code_range(&Range::from_located(docstring))
|
||||
.lines()
|
||||
.next()
|
||||
@@ -629,7 +622,7 @@ pub fn multi_line_summary_start(checker: &mut Checker, definition: &Definition)
|
||||
{
|
||||
if string.lines().nth(1).is_some() {
|
||||
if let Some(first_line) = checker
|
||||
.get_locator()
|
||||
.locator
|
||||
.slice_source_code_range(&Range::from_located(docstring))
|
||||
.lines()
|
||||
.next()
|
||||
@@ -665,7 +658,7 @@ pub fn triple_quotes(checker: &mut Checker, definition: &Definition) {
|
||||
} = &docstring.node
|
||||
{
|
||||
if let Some(first_line) = checker
|
||||
.get_locator()
|
||||
.locator
|
||||
.slice_source_code_range(&Range::from_located(docstring))
|
||||
.lines()
|
||||
.next()
|
||||
@@ -925,7 +918,7 @@ fn blanks_and_section_underline(
|
||||
);
|
||||
check.amend(Fix::insertion(
|
||||
content,
|
||||
Location::new(docstring.location.row() + context.original_index + 1, 1),
|
||||
Location::new(docstring.location.row() + context.original_index + 1, 0),
|
||||
));
|
||||
}
|
||||
checker.add_check(check);
|
||||
@@ -959,7 +952,7 @@ fn blanks_and_section_underline(
|
||||
);
|
||||
check.amend(Fix::insertion(
|
||||
content,
|
||||
Location::new(docstring.location.row() + context.original_index + 1, 1),
|
||||
Location::new(docstring.location.row() + context.original_index + 1, 0),
|
||||
));
|
||||
}
|
||||
checker.add_check(check);
|
||||
@@ -975,13 +968,13 @@ fn blanks_and_section_underline(
|
||||
if checker.patch() {
|
||||
// Delete any blank lines between the header and content.
|
||||
check.amend(Fix::deletion(
|
||||
Location::new(docstring.location.row() + context.original_index + 1, 1),
|
||||
Location::new(docstring.location.row() + context.original_index + 1, 0),
|
||||
Location::new(
|
||||
docstring.location.row()
|
||||
+ context.original_index
|
||||
+ 1
|
||||
+ blank_lines_after_header,
|
||||
1,
|
||||
0,
|
||||
),
|
||||
));
|
||||
}
|
||||
@@ -998,13 +991,13 @@ fn blanks_and_section_underline(
|
||||
if checker.patch() {
|
||||
// Delete any blank lines between the header and the underline.
|
||||
check.amend(Fix::deletion(
|
||||
Location::new(docstring.location.row() + context.original_index + 1, 1),
|
||||
Location::new(docstring.location.row() + context.original_index + 1, 0),
|
||||
Location::new(
|
||||
docstring.location.row()
|
||||
+ context.original_index
|
||||
+ 1
|
||||
+ blank_lines_after_header,
|
||||
1,
|
||||
0,
|
||||
),
|
||||
));
|
||||
}
|
||||
@@ -1040,7 +1033,7 @@ fn blanks_and_section_underline(
|
||||
+ context.original_index
|
||||
+ 1
|
||||
+ blank_lines_after_header,
|
||||
1,
|
||||
0,
|
||||
),
|
||||
Location::new(
|
||||
docstring.location.row()
|
||||
@@ -1048,7 +1041,7 @@ fn blanks_and_section_underline(
|
||||
+ 1
|
||||
+ blank_lines_after_header
|
||||
+ 1,
|
||||
1,
|
||||
0,
|
||||
),
|
||||
));
|
||||
};
|
||||
@@ -1073,7 +1066,7 @@ fn blanks_and_section_underline(
|
||||
+ context.original_index
|
||||
+ 1
|
||||
+ blank_lines_after_header,
|
||||
1,
|
||||
0,
|
||||
),
|
||||
Location::new(
|
||||
docstring.location.row()
|
||||
@@ -1121,7 +1114,7 @@ fn blanks_and_section_underline(
|
||||
+ context.original_index
|
||||
+ 1
|
||||
+ line_after_dashes_index,
|
||||
1,
|
||||
0,
|
||||
),
|
||||
Location::new(
|
||||
docstring.location.row()
|
||||
@@ -1129,7 +1122,7 @@ fn blanks_and_section_underline(
|
||||
+ 1
|
||||
+ line_after_dashes_index
|
||||
+ blank_lines_after_dashes,
|
||||
1,
|
||||
0,
|
||||
),
|
||||
));
|
||||
}
|
||||
@@ -1183,11 +1176,11 @@ fn common_section(
|
||||
capitalized_section_name,
|
||||
Location::new(
|
||||
docstring.location.row() + context.original_index,
|
||||
1 + section_name_start,
|
||||
*section_name_start,
|
||||
),
|
||||
Location::new(
|
||||
docstring.location.row() + context.original_index,
|
||||
1 + section_name_start + section_name_length,
|
||||
section_name_start + section_name_length,
|
||||
),
|
||||
))
|
||||
}
|
||||
@@ -1209,10 +1202,10 @@ fn common_section(
|
||||
// Replace the existing indentation with whitespace of the appropriate length.
|
||||
check.amend(Fix::replacement(
|
||||
helpers::clean(&indentation),
|
||||
Location::new(docstring.location.row() + context.original_index, 1),
|
||||
Location::new(docstring.location.row() + context.original_index, 0),
|
||||
Location::new(
|
||||
docstring.location.row() + context.original_index,
|
||||
1 + leading_space.len(),
|
||||
leading_space.len(),
|
||||
),
|
||||
));
|
||||
};
|
||||
@@ -1241,7 +1234,7 @@ fn common_section(
|
||||
+ context.original_index
|
||||
+ 1
|
||||
+ context.following_lines.len(),
|
||||
1,
|
||||
0,
|
||||
),
|
||||
));
|
||||
}
|
||||
@@ -1262,7 +1255,7 @@ fn common_section(
|
||||
+ context.original_index
|
||||
+ 1
|
||||
+ context.following_lines.len(),
|
||||
1,
|
||||
0,
|
||||
),
|
||||
));
|
||||
}
|
||||
@@ -1281,7 +1274,7 @@ fn common_section(
|
||||
// Add a blank line before the section.
|
||||
check.amend(Fix::insertion(
|
||||
"\n".to_string(),
|
||||
Location::new(docstring.location.row() + context.original_index, 1),
|
||||
Location::new(docstring.location.row() + context.original_index, 0),
|
||||
));
|
||||
}
|
||||
checker.add_check(check)
|
||||
@@ -1448,11 +1441,11 @@ fn numpy_section(checker: &mut Checker, definition: &Definition, context: &Secti
|
||||
check.amend(Fix::deletion(
|
||||
Location::new(
|
||||
docstring.location.row() + context.original_index,
|
||||
1 + suffix_start,
|
||||
*suffix_start,
|
||||
),
|
||||
Location::new(
|
||||
docstring.location.row() + context.original_index,
|
||||
1 + suffix_start + suffix_length,
|
||||
suffix_start + suffix_length,
|
||||
),
|
||||
));
|
||||
}
|
||||
@@ -1498,11 +1491,11 @@ fn google_section(checker: &mut Checker, definition: &Definition, context: &Sect
|
||||
":".to_string(),
|
||||
Location::new(
|
||||
docstring.location.row() + context.original_index,
|
||||
1 + suffix_start,
|
||||
*suffix_start,
|
||||
),
|
||||
Location::new(
|
||||
docstring.location.row() + context.original_index,
|
||||
1 + suffix_start + suffix_length,
|
||||
suffix_start + suffix_length,
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
@@ -2,10 +2,10 @@ use anyhow::Result;
|
||||
use libcst_native::{Codegen, ImportNames, NameOrAttribute, SmallStatement, Statement};
|
||||
use rustpython_ast::Stmt;
|
||||
|
||||
use crate::ast::operations::SourceCodeLocator;
|
||||
use crate::ast::types::Range;
|
||||
use crate::autofix::{helpers, Fix};
|
||||
use crate::cst::helpers::compose_module_path;
|
||||
use crate::source_code_locator::SourceCodeLocator;
|
||||
|
||||
/// Generate a Fix to remove any unused imports from an `import` statement.
|
||||
pub fn remove_unused_imports(
|
||||
|
||||
@@ -1,101 +1,207 @@
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use rustpython_ast::{Expr, ExprKind};
|
||||
|
||||
static ANNOTATED_SUBSCRIPTS: Lazy<BTreeSet<&'static str>> = Lazy::new(|| {
|
||||
BTreeSet::from([
|
||||
"AbstractAsyncContextManager",
|
||||
"AbstractContextManager",
|
||||
"AbstractSet",
|
||||
// "Annotated",
|
||||
"AsyncContextManager",
|
||||
"AsyncGenerator",
|
||||
"AsyncIterable",
|
||||
"AsyncIterator",
|
||||
"Awaitable",
|
||||
"BinaryIO",
|
||||
"BsdDbShelf",
|
||||
"ByteString",
|
||||
"Callable",
|
||||
"ChainMap",
|
||||
"ClassVar",
|
||||
"Collection",
|
||||
"Concatenate",
|
||||
"Container",
|
||||
"ContextManager",
|
||||
"Coroutine",
|
||||
"Counter",
|
||||
"Counter",
|
||||
"DbfilenameShelf",
|
||||
"DefaultDict",
|
||||
"Deque",
|
||||
"Dict",
|
||||
"Field",
|
||||
"Final",
|
||||
"FrozenSet",
|
||||
"Generator",
|
||||
"Iterator",
|
||||
"Generic",
|
||||
"IO",
|
||||
"ItemsView",
|
||||
"Iterable",
|
||||
"Iterator",
|
||||
"KeysView",
|
||||
"LifoQueue",
|
||||
"List",
|
||||
"Mapping",
|
||||
"MappingProxyType",
|
||||
"MappingView",
|
||||
"Match",
|
||||
"MutableMapping",
|
||||
"MutableSequence",
|
||||
"MutableSet",
|
||||
"Optional",
|
||||
"OrderedDict",
|
||||
"PathLike",
|
||||
"Pattern",
|
||||
"PriorityQueue",
|
||||
"Protocol",
|
||||
"Queue",
|
||||
"Reversible",
|
||||
"Sequence",
|
||||
"Set",
|
||||
"Shelf",
|
||||
"SimpleQueue",
|
||||
"TextIO",
|
||||
"Tuple",
|
||||
"Type",
|
||||
"TypeGuard",
|
||||
"Union",
|
||||
"ValuesView",
|
||||
"WeakKeyDictionary",
|
||||
"WeakMethod",
|
||||
"WeakSet",
|
||||
"WeakValueDictionary",
|
||||
"cached_property",
|
||||
"defaultdict",
|
||||
"deque",
|
||||
"dict",
|
||||
"frozenset",
|
||||
"list",
|
||||
"partialmethod",
|
||||
"set",
|
||||
"tuple",
|
||||
"type",
|
||||
])
|
||||
});
|
||||
// See: https://docs.python.org/3/library/typing.html
|
||||
static IMPORTED_SUBSCRIPTS: Lazy<BTreeMap<&'static str, BTreeSet<&'static str>>> =
|
||||
Lazy::new(|| {
|
||||
let mut import_map = BTreeMap::new();
|
||||
for (name, module) in [
|
||||
// `collections`
|
||||
("ChainMap", "collections"),
|
||||
("Counter", "collections"),
|
||||
("OrderedDict", "collections"),
|
||||
("defaultdict", "collections"),
|
||||
("deque", "collections"),
|
||||
// `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", "collections.abc"),
|
||||
// `contextlib`
|
||||
("AbstractAsyncContextManager", "contextlib"),
|
||||
("AbstractContextManager", "contextlib"),
|
||||
// `re`
|
||||
("Match", "re"),
|
||||
("Pattern", "re"),
|
||||
// `typing`
|
||||
("AbstractSet", "typing"),
|
||||
("Annotated", "typing"),
|
||||
("AsyncContextManager", "typing"),
|
||||
("AsyncContextManager", "typing"),
|
||||
("AsyncGenerator", "typing"),
|
||||
("AsyncIterable", "typing"),
|
||||
("AsyncIterator", "typing"),
|
||||
("Awaitable", "typing"),
|
||||
("BinaryIO", "typing"),
|
||||
("ByteString", "typing"),
|
||||
("Callable", "typing"),
|
||||
("ChainMap", "typing"),
|
||||
("ClassVar", "typing"),
|
||||
("Collection", "typing"),
|
||||
("Concatenate", "typing"),
|
||||
("Container", "typing"),
|
||||
("ContextManager", "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"),
|
||||
("Type", "typing"),
|
||||
("TypeGuard", "typing"),
|
||||
("Union", "typing"),
|
||||
("Unpack", "typing"),
|
||||
("ValuesView", "typing"),
|
||||
// `typing.io`
|
||||
("BinaryIO", "typing.io"),
|
||||
("IO", "typing.io"),
|
||||
("TextIO", "typing.io"),
|
||||
// `typing.re`
|
||||
("Match", "typing.re"),
|
||||
("Pattern", "typing.re"),
|
||||
// `weakref`
|
||||
("WeakKeyDictionary", "weakref"),
|
||||
("WeakSet", "weakref"),
|
||||
("WeakValueDictionary", "weakref"),
|
||||
] {
|
||||
import_map
|
||||
.entry(name)
|
||||
.or_insert_with(BTreeSet::new)
|
||||
.insert(module);
|
||||
}
|
||||
import_map
|
||||
});
|
||||
|
||||
pub fn is_annotated_subscript(name: &str) -> bool {
|
||||
ANNOTATED_SUBSCRIPTS.contains(name)
|
||||
}
|
||||
// These are all assumed to come from the `typing` module.
|
||||
// See: https://peps.python.org/pep-0585/
|
||||
static PEP_585_BUILTINS_ELIGIBLE: Lazy<BTreeSet<&'static str>> =
|
||||
Lazy::new(|| BTreeSet::from(["Dict", "FrozenSet", "List", "Set", "Tuple", "Type"]));
|
||||
|
||||
pub fn is_pep593_annotated_subscript(name: &str) -> bool {
|
||||
// These are all assumed to come from the `typing` module.
|
||||
// See: https://peps.python.org/pep-0585/
|
||||
static PEP_585_BUILTINS: Lazy<BTreeSet<&'static str>> =
|
||||
Lazy::new(|| BTreeSet::from(["dict", "frozenset", "list", "set", "tuple", "type"]));
|
||||
|
||||
fn is_pep593_annotated_subscript(name: &str) -> bool {
|
||||
name == "Annotated"
|
||||
}
|
||||
|
||||
static PEP_585_BUILTINS: Lazy<BTreeSet<&'static str>> =
|
||||
Lazy::new(|| BTreeSet::from(["Dict", "FrozenSet", "List", "Set", "Tuple", "Type"]));
|
||||
|
||||
pub fn is_pep585_builtin(name: &str) -> bool {
|
||||
PEP_585_BUILTINS.contains(name)
|
||||
pub enum SubscriptKind {
|
||||
AnnotatedSubscript,
|
||||
PEP593AnnotatedSubscript,
|
||||
}
|
||||
|
||||
pub fn match_annotated_subscript(
|
||||
expr: &Expr,
|
||||
imports: &BTreeMap<&str, BTreeSet<&str>>,
|
||||
) -> Option<SubscriptKind> {
|
||||
match &expr.node {
|
||||
ExprKind::Attribute { attr, value, .. } => {
|
||||
if let ExprKind::Name { id, .. } = &value.node {
|
||||
// If `id` is `typing` and `attr` is `Union`, verify that `typing.Union` is an
|
||||
// annotated subscript.
|
||||
if IMPORTED_SUBSCRIPTS
|
||||
.get(&attr.as_str())
|
||||
.map(|imports| imports.contains(&id.as_str()))
|
||||
.unwrap_or_default()
|
||||
{
|
||||
return if is_pep593_annotated_subscript(attr) {
|
||||
Some(SubscriptKind::PEP593AnnotatedSubscript)
|
||||
} else {
|
||||
Some(SubscriptKind::AnnotatedSubscript)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
ExprKind::Name { id, .. } => {
|
||||
// Built-ins (no import necessary).
|
||||
if PEP_585_BUILTINS.contains(&id.as_str()) {
|
||||
return Some(SubscriptKind::AnnotatedSubscript);
|
||||
}
|
||||
|
||||
// Verify that, e.g., `Union` is a reference to `typing.Union`.
|
||||
if let Some(modules) = IMPORTED_SUBSCRIPTS.get(&id.as_str()) {
|
||||
for module in modules {
|
||||
if imports
|
||||
.get(module)
|
||||
.map(|imports| imports.contains(&id.as_str()))
|
||||
.unwrap_or_default()
|
||||
{
|
||||
return if is_pep593_annotated_subscript(id) {
|
||||
Some(SubscriptKind::PEP593AnnotatedSubscript)
|
||||
} else {
|
||||
Some(SubscriptKind::AnnotatedSubscript)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns `true` if `Expr` represents a reference to a typing object with a PEP 585 built-in.
|
||||
pub fn is_pep585_builtin(expr: &Expr, typing_imports: Option<&BTreeSet<&str>>) -> bool {
|
||||
match &expr.node {
|
||||
ExprKind::Attribute { attr, value, .. } => {
|
||||
if let ExprKind::Name { id, .. } = &value.node {
|
||||
id == "typing" && PEP_585_BUILTINS_ELIGIBLE.contains(&attr.as_str())
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
ExprKind::Name { id, .. } => {
|
||||
typing_imports
|
||||
.map(|imports| imports.contains(&id.as_str()))
|
||||
.unwrap_or_default()
|
||||
&& PEP_585_BUILTINS_ELIGIBLE.contains(&id.as_str())
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@ use rustpython_parser::lexer;
|
||||
use rustpython_parser::lexer::Tok;
|
||||
|
||||
use crate::ast::helpers;
|
||||
use crate::ast::operations::SourceCodeLocator;
|
||||
use crate::ast::types::Range;
|
||||
use crate::autofix::Fix;
|
||||
use crate::source_code_locator::SourceCodeLocator;
|
||||
|
||||
/// Generate a fix to remove a base from a ClassDef statement.
|
||||
pub fn remove_class_def_base(
|
||||
|
||||
@@ -17,9 +17,7 @@ pub fn super_call_with_parameters(checker: &mut Checker, expr: &Expr, func: &Exp
|
||||
.collect();
|
||||
if let Some(mut check) = checks::super_args(scope, &parents, expr, func, args) {
|
||||
if checker.patch() {
|
||||
if let Some(fix) =
|
||||
pyupgrade::fixes::remove_super_arguments(checker.get_locator(), expr)
|
||||
{
|
||||
if let Some(fix) = pyupgrade::fixes::remove_super_arguments(checker.locator, expr) {
|
||||
check.amend(fix);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,22 +4,18 @@ use crate::ast::types::Range;
|
||||
use crate::autofix::Fix;
|
||||
use crate::check_ast::Checker;
|
||||
use crate::checks::{Check, CheckKind};
|
||||
use crate::python::typing;
|
||||
|
||||
pub fn use_pep585_annotation(checker: &mut Checker, expr: &Expr, id: &str) {
|
||||
// TODO(charlie): Verify that the builtin is imported from the `typing` module.
|
||||
if typing::is_pep585_builtin(id) {
|
||||
let mut check = Check::new(
|
||||
CheckKind::UsePEP585Annotation(id.to_string()),
|
||||
Range::from_located(expr),
|
||||
);
|
||||
if checker.patch() {
|
||||
check.amend(Fix::replacement(
|
||||
id.to_lowercase(),
|
||||
expr.location,
|
||||
expr.end_location.unwrap(),
|
||||
));
|
||||
}
|
||||
checker.add_check(check);
|
||||
let mut check = Check::new(
|
||||
CheckKind::UsePEP585Annotation(id.to_string()),
|
||||
Range::from_located(expr),
|
||||
);
|
||||
if checker.patch() {
|
||||
check.amend(Fix::replacement(
|
||||
id.to_lowercase(),
|
||||
expr.location,
|
||||
expr.end_location.unwrap(),
|
||||
));
|
||||
}
|
||||
checker.add_check(check);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use rustpython_ast::{Constant, Expr, ExprKind, Operator};
|
||||
|
||||
use crate::ast::helpers::match_name_or_attr;
|
||||
use crate::ast::types::Range;
|
||||
use crate::autofix::Fix;
|
||||
use crate::check_ast::Checker;
|
||||
@@ -43,7 +42,7 @@ fn union(elts: &[Expr]) -> Expr {
|
||||
}
|
||||
|
||||
pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, slice: &Expr) {
|
||||
if match_name_or_attr(value, "Optional") {
|
||||
if checker.match_typing_module(value, "Optional") {
|
||||
let mut check = Check::new(CheckKind::UsePEP604Annotation, Range::from_located(expr));
|
||||
if checker.patch() {
|
||||
let mut generator = SourceGenerator::new();
|
||||
@@ -58,7 +57,7 @@ pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, s
|
||||
}
|
||||
}
|
||||
checker.add_check(check);
|
||||
} else if match_name_or_attr(value, "Union") {
|
||||
} else if checker.match_typing_module(value, "Union") {
|
||||
let mut check = Check::new(CheckKind::UsePEP604Annotation, Range::from_located(expr));
|
||||
if checker.patch() {
|
||||
match &slice.node {
|
||||
|
||||
@@ -15,7 +15,7 @@ pub fn useless_object_inheritance(
|
||||
if let Some(mut check) = checks::useless_object_inheritance(name, bases, scope) {
|
||||
if checker.patch() {
|
||||
if let Some(fix) = pyupgrade::fixes::remove_class_def_base(
|
||||
checker.get_locator(),
|
||||
checker.locator,
|
||||
&stmt.location,
|
||||
check.location,
|
||||
bases,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! User-provided program settings, taking into account pyproject.toml and command-line options.
|
||||
//! Structure mirrors the user-facing representation of the various parameters.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
@@ -8,9 +9,9 @@ use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
|
||||
use crate::checks_gen::CheckCodePrefix;
|
||||
use crate::flake8_quotes;
|
||||
use crate::settings::pyproject::load_options;
|
||||
use crate::settings::types::{FilePattern, PerFileIgnore, PythonVersion};
|
||||
use crate::settings::types::{FilePattern, PythonVersion};
|
||||
use crate::{flake8_quotes, pep8_naming};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Configuration {
|
||||
@@ -21,11 +22,12 @@ pub struct Configuration {
|
||||
pub extend_select: Vec<CheckCodePrefix>,
|
||||
pub ignore: Vec<CheckCodePrefix>,
|
||||
pub line_length: usize,
|
||||
pub per_file_ignores: Vec<PerFileIgnore>,
|
||||
pub per_file_ignores: BTreeMap<String, Vec<CheckCodePrefix>>,
|
||||
pub select: Vec<CheckCodePrefix>,
|
||||
pub target_version: PythonVersion,
|
||||
// Plugins
|
||||
pub flake8_quotes: flake8_quotes::settings::Settings,
|
||||
pub pep8_naming: pep8_naming::settings::Settings,
|
||||
}
|
||||
|
||||
static DEFAULT_EXCLUDE: Lazy<Vec<FilePattern>> = Lazy::new(|| {
|
||||
@@ -59,9 +61,8 @@ impl Configuration {
|
||||
pub fn from_pyproject(
|
||||
pyproject: &Option<PathBuf>,
|
||||
project_root: &Option<PathBuf>,
|
||||
quiet: bool,
|
||||
) -> Result<Self> {
|
||||
let options = load_options(pyproject, quiet)?;
|
||||
let options = load_options(pyproject)?;
|
||||
Ok(Configuration {
|
||||
dummy_variable_rgx: match options.dummy_variable_rgx {
|
||||
Some(pattern) => Regex::new(&pattern)
|
||||
@@ -80,25 +81,26 @@ impl Configuration {
|
||||
.unwrap_or_else(|| DEFAULT_EXCLUDE.clone()),
|
||||
extend_exclude: options
|
||||
.extend_exclude
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|path| FilePattern::from_user(path, project_root))
|
||||
.collect(),
|
||||
extend_ignore: options.extend_ignore,
|
||||
extend_ignore: options.extend_ignore.unwrap_or_default(),
|
||||
select: options
|
||||
.select
|
||||
.unwrap_or_else(|| vec![CheckCodePrefix::E, CheckCodePrefix::F]),
|
||||
extend_select: options.extend_select,
|
||||
ignore: options.ignore,
|
||||
extend_select: options.extend_select.unwrap_or_default(),
|
||||
ignore: options.ignore.unwrap_or_default(),
|
||||
line_length: options.line_length.unwrap_or(88),
|
||||
per_file_ignores: options
|
||||
.per_file_ignores
|
||||
.into_iter()
|
||||
.map(|pair| PerFileIgnore::new(pair, project_root))
|
||||
.collect(),
|
||||
per_file_ignores: options.per_file_ignores.unwrap_or_default(),
|
||||
// Plugins
|
||||
flake8_quotes: options
|
||||
.flake8_quotes
|
||||
.map(flake8_quotes::settings::Settings::from_config)
|
||||
.map(flake8_quotes::settings::Settings::from_options)
|
||||
.unwrap_or_default(),
|
||||
pep8_naming: options
|
||||
.pep8_naming
|
||||
.map(pep8_naming::settings::Settings::from_options)
|
||||
.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
//! Effective program settings, taking into account pyproject.toml and command-line options.
|
||||
//! Structure is optimized for internal usage, as opposed to external visibility or parsing.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use regex::Regex;
|
||||
|
||||
use crate::checks::CheckCode;
|
||||
use crate::checks_gen::{CheckCodePrefix, PrefixSpecificity};
|
||||
use crate::flake8_quotes;
|
||||
use crate::settings::configuration::Configuration;
|
||||
use crate::settings::types::{FilePattern, PerFileIgnore, PythonVersion};
|
||||
use crate::{flake8_quotes, pep8_naming};
|
||||
|
||||
pub mod configuration;
|
||||
pub mod options;
|
||||
@@ -29,6 +29,7 @@ pub struct Settings {
|
||||
pub target_version: PythonVersion,
|
||||
// Plugins
|
||||
pub flake8_quotes: flake8_quotes::settings::Settings,
|
||||
pub pep8_naming: pep8_naming::settings::Settings,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
@@ -45,7 +46,8 @@ impl Settings {
|
||||
extend_exclude: config.extend_exclude,
|
||||
flake8_quotes: config.flake8_quotes,
|
||||
line_length: config.line_length,
|
||||
per_file_ignores: config.per_file_ignores,
|
||||
pep8_naming: config.pep8_naming,
|
||||
per_file_ignores: resolve_per_file_ignores(&config.per_file_ignores),
|
||||
target_version: config.target_version,
|
||||
}
|
||||
}
|
||||
@@ -54,12 +56,13 @@ impl Settings {
|
||||
Self {
|
||||
dummy_variable_rgx: Regex::new("^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$").unwrap(),
|
||||
enabled: BTreeSet::from([check_code]),
|
||||
exclude: vec![],
|
||||
extend_exclude: vec![],
|
||||
exclude: Default::default(),
|
||||
extend_exclude: Default::default(),
|
||||
line_length: 88,
|
||||
per_file_ignores: vec![],
|
||||
per_file_ignores: Default::default(),
|
||||
target_version: PythonVersion::Py310,
|
||||
flake8_quotes: Default::default(),
|
||||
pep8_naming: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,12 +70,13 @@ impl Settings {
|
||||
Self {
|
||||
dummy_variable_rgx: Regex::new("^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$").unwrap(),
|
||||
enabled: BTreeSet::from_iter(check_codes),
|
||||
exclude: vec![],
|
||||
extend_exclude: vec![],
|
||||
exclude: Default::default(),
|
||||
extend_exclude: Default::default(),
|
||||
line_length: 88,
|
||||
per_file_ignores: vec![],
|
||||
per_file_ignores: Default::default(),
|
||||
target_version: PythonVersion::Py310,
|
||||
flake8_quotes: Default::default(),
|
||||
pep8_naming: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -132,6 +136,15 @@ fn resolve_codes(
|
||||
codes
|
||||
}
|
||||
|
||||
fn resolve_per_file_ignores(
|
||||
per_file_ignores: &BTreeMap<String, Vec<CheckCodePrefix>>,
|
||||
) -> Vec<PerFileIgnore> {
|
||||
per_file_ignores
|
||||
.iter()
|
||||
.map(|(pattern, prefixes)| PerFileIgnore::new(pattern, prefixes, &None))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
@@ -1,28 +1,27 @@
|
||||
//! Options that the user can provide via pyproject.toml.
|
||||
|
||||
use serde::Deserialize;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::checks_gen::CheckCodePrefix;
|
||||
use crate::flake8_quotes;
|
||||
use crate::settings::types::{PythonVersion, StrCheckCodePair};
|
||||
use crate::settings::types::PythonVersion;
|
||||
use crate::{flake8_quotes, pep8_naming};
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Deserialize, Default)]
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct Options {
|
||||
pub line_length: Option<usize>,
|
||||
pub exclude: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
pub extend_exclude: Vec<String>,
|
||||
pub extend_exclude: Option<Vec<String>>,
|
||||
pub select: Option<Vec<CheckCodePrefix>>,
|
||||
#[serde(default)]
|
||||
pub extend_select: Vec<CheckCodePrefix>,
|
||||
#[serde(default)]
|
||||
pub ignore: Vec<CheckCodePrefix>,
|
||||
#[serde(default)]
|
||||
pub extend_ignore: Vec<CheckCodePrefix>,
|
||||
#[serde(default)]
|
||||
pub per_file_ignores: Vec<StrCheckCodePair>,
|
||||
pub extend_select: Option<Vec<CheckCodePrefix>>,
|
||||
pub ignore: Option<Vec<CheckCodePrefix>>,
|
||||
pub extend_ignore: Option<Vec<CheckCodePrefix>>,
|
||||
pub per_file_ignores: Option<BTreeMap<String, Vec<CheckCodePrefix>>>,
|
||||
pub dummy_variable_rgx: Option<String>,
|
||||
pub target_version: Option<PythonVersion>,
|
||||
// Plugins
|
||||
pub flake8_quotes: Option<flake8_quotes::settings::Options>,
|
||||
pub pep8_naming: Option<pep8_naming::settings::Options>,
|
||||
}
|
||||
|
||||
@@ -4,22 +4,33 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::Result;
|
||||
use common_path::common_path_all;
|
||||
use log::debug;
|
||||
use path_absolutize::Absolutize;
|
||||
use serde::Deserialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::fs;
|
||||
use crate::settings::options::Options;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Deserialize)]
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct Tools {
|
||||
ruff: Option<Options>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Deserialize)]
|
||||
struct Pyproject {
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Pyproject {
|
||||
tool: Option<Tools>,
|
||||
}
|
||||
|
||||
impl Pyproject {
|
||||
pub fn new(options: Options) -> Self {
|
||||
Self {
|
||||
tool: Some(Tools {
|
||||
ruff: Some(options),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_pyproject_toml(path: &Path) -> Result<Pyproject> {
|
||||
let contents = fs::read_file(path)?;
|
||||
toml::from_str(&contents).map_err(|e| e.into())
|
||||
@@ -69,17 +80,15 @@ pub fn find_project_root(sources: &[PathBuf]) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn load_options(pyproject: &Option<PathBuf>, quiet: bool) -> Result<Options> {
|
||||
pub fn load_options(pyproject: &Option<PathBuf>) -> Result<Options> {
|
||||
match pyproject {
|
||||
Some(pyproject) => Ok(parse_pyproject_toml(pyproject)?
|
||||
.tool
|
||||
.and_then(|tool| tool.ruff)
|
||||
.unwrap_or_default()),
|
||||
None => {
|
||||
if !quiet {
|
||||
eprintln!("No pyproject.toml found.");
|
||||
eprintln!("Falling back to default configuration...");
|
||||
}
|
||||
debug!("No pyproject.toml found.");
|
||||
debug!("Falling back to default configuration...");
|
||||
Ok(Default::default())
|
||||
}
|
||||
}
|
||||
@@ -87,6 +96,7 @@ pub fn load_options(pyproject: &Option<PathBuf>, quiet: bool) -> Result<Options>
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeMap;
|
||||
use std::env::current_dir;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
@@ -94,12 +104,12 @@ mod tests {
|
||||
use anyhow::Result;
|
||||
|
||||
use crate::checks_gen::CheckCodePrefix;
|
||||
use crate::flake8_quotes;
|
||||
use crate::flake8_quotes::settings::Quote;
|
||||
use crate::settings::pyproject::{
|
||||
find_project_root, find_pyproject_toml, parse_pyproject_toml, Options, Pyproject, Tools,
|
||||
};
|
||||
use crate::settings::types::StrCheckCodePair;
|
||||
use crate::settings::types::PatternPrefixPair;
|
||||
use crate::{flake8_quotes, pep8_naming};
|
||||
|
||||
#[test]
|
||||
fn deserialize() -> Result<()> {
|
||||
@@ -125,15 +135,16 @@ mod tests {
|
||||
ruff: Some(Options {
|
||||
line_length: None,
|
||||
exclude: None,
|
||||
extend_exclude: vec![],
|
||||
extend_exclude: None,
|
||||
select: None,
|
||||
extend_select: vec![],
|
||||
ignore: vec![],
|
||||
extend_ignore: vec![],
|
||||
per_file_ignores: vec![],
|
||||
extend_select: None,
|
||||
ignore: None,
|
||||
extend_ignore: None,
|
||||
per_file_ignores: None,
|
||||
dummy_variable_rgx: None,
|
||||
target_version: None,
|
||||
flake8_quotes: None
|
||||
flake8_quotes: None,
|
||||
pep8_naming: None,
|
||||
})
|
||||
})
|
||||
);
|
||||
@@ -151,15 +162,16 @@ line-length = 79
|
||||
ruff: Some(Options {
|
||||
line_length: Some(79),
|
||||
exclude: None,
|
||||
extend_exclude: vec![],
|
||||
extend_exclude: None,
|
||||
select: None,
|
||||
extend_select: vec![],
|
||||
ignore: vec![],
|
||||
extend_ignore: vec![],
|
||||
per_file_ignores: vec![],
|
||||
extend_select: None,
|
||||
ignore: None,
|
||||
extend_ignore: None,
|
||||
per_file_ignores: None,
|
||||
dummy_variable_rgx: None,
|
||||
target_version: None,
|
||||
flake8_quotes: None
|
||||
flake8_quotes: None,
|
||||
pep8_naming: None,
|
||||
})
|
||||
})
|
||||
);
|
||||
@@ -177,15 +189,16 @@ exclude = ["foo.py"]
|
||||
ruff: Some(Options {
|
||||
line_length: None,
|
||||
exclude: Some(vec!["foo.py".to_string()]),
|
||||
extend_exclude: vec![],
|
||||
extend_exclude: None,
|
||||
select: None,
|
||||
extend_select: vec![],
|
||||
ignore: vec![],
|
||||
extend_ignore: vec![],
|
||||
per_file_ignores: vec![],
|
||||
extend_select: None,
|
||||
ignore: None,
|
||||
extend_ignore: None,
|
||||
per_file_ignores: None,
|
||||
dummy_variable_rgx: None,
|
||||
target_version: None,
|
||||
flake8_quotes: None
|
||||
flake8_quotes: None,
|
||||
pep8_naming: None,
|
||||
})
|
||||
})
|
||||
);
|
||||
@@ -203,15 +216,16 @@ select = ["E501"]
|
||||
ruff: Some(Options {
|
||||
line_length: None,
|
||||
exclude: None,
|
||||
extend_exclude: vec![],
|
||||
extend_exclude: None,
|
||||
select: Some(vec![CheckCodePrefix::E501]),
|
||||
extend_select: vec![],
|
||||
ignore: vec![],
|
||||
extend_ignore: vec![],
|
||||
per_file_ignores: vec![],
|
||||
extend_select: None,
|
||||
ignore: None,
|
||||
extend_ignore: None,
|
||||
per_file_ignores: None,
|
||||
dummy_variable_rgx: None,
|
||||
target_version: None,
|
||||
flake8_quotes: None
|
||||
flake8_quotes: None,
|
||||
pep8_naming: None,
|
||||
})
|
||||
})
|
||||
);
|
||||
@@ -230,15 +244,16 @@ ignore = ["E501"]
|
||||
ruff: Some(Options {
|
||||
line_length: None,
|
||||
exclude: None,
|
||||
extend_exclude: vec![],
|
||||
extend_exclude: None,
|
||||
select: None,
|
||||
extend_select: vec![CheckCodePrefix::M001],
|
||||
ignore: vec![CheckCodePrefix::E501],
|
||||
extend_ignore: vec![],
|
||||
per_file_ignores: vec![],
|
||||
extend_select: Some(vec![CheckCodePrefix::M001]),
|
||||
ignore: Some(vec![CheckCodePrefix::E501]),
|
||||
extend_ignore: None,
|
||||
per_file_ignores: None,
|
||||
dummy_variable_rgx: None,
|
||||
target_version: None,
|
||||
flake8_quotes: None
|
||||
flake8_quotes: None,
|
||||
pep8_naming: None,
|
||||
})
|
||||
})
|
||||
);
|
||||
@@ -296,19 +311,19 @@ other-attribute = 1
|
||||
Options {
|
||||
line_length: Some(88),
|
||||
exclude: None,
|
||||
extend_exclude: vec![
|
||||
extend_exclude: Some(vec![
|
||||
"excluded.py".to_string(),
|
||||
"migrations".to_string(),
|
||||
"directory/also_excluded.py".to_string(),
|
||||
],
|
||||
]),
|
||||
select: None,
|
||||
extend_select: vec![],
|
||||
ignore: vec![],
|
||||
extend_ignore: vec![],
|
||||
per_file_ignores: vec![StrCheckCodePair {
|
||||
pattern: "__init__.py".to_string(),
|
||||
code: CheckCodePrefix::F401
|
||||
}],
|
||||
extend_select: None,
|
||||
ignore: None,
|
||||
extend_ignore: None,
|
||||
per_file_ignores: Some(BTreeMap::from([(
|
||||
"__init__.py".to_string(),
|
||||
vec![CheckCodePrefix::F401]
|
||||
),])),
|
||||
dummy_variable_rgx: None,
|
||||
target_version: None,
|
||||
flake8_quotes: Some(flake8_quotes::settings::Options {
|
||||
@@ -316,7 +331,25 @@ other-attribute = 1
|
||||
multiline_quotes: Some(Quote::Double),
|
||||
docstring_quotes: Some(Quote::Double),
|
||||
avoid_escape: Some(true),
|
||||
})
|
||||
}),
|
||||
pep8_naming: Some(pep8_naming::settings::Options {
|
||||
ignore_names: Some(vec![
|
||||
"setUp".to_string(),
|
||||
"tearDown".to_string(),
|
||||
"setUpClass".to_string(),
|
||||
"tearDownClass".to_string(),
|
||||
"setUpModule".to_string(),
|
||||
"tearDownModule".to_string(),
|
||||
"asyncSetUp".to_string(),
|
||||
"asyncTearDown".to_string(),
|
||||
"setUpTestData".to_string(),
|
||||
"failureException".to_string(),
|
||||
"longMessage".to_string(),
|
||||
"maxDiff".to_string(),
|
||||
]),
|
||||
classmethod_decorators: Some(vec!["classmethod".to_string()]),
|
||||
staticmethod_decorators: Some(vec!["staticmethod".to_string()]),
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
@@ -325,21 +358,21 @@ other-attribute = 1
|
||||
|
||||
#[test]
|
||||
fn str_check_code_pair_strings() {
|
||||
let result = StrCheckCodePair::from_str("foo:E501");
|
||||
let result = PatternPrefixPair::from_str("foo:E501");
|
||||
assert!(result.is_ok());
|
||||
let result = StrCheckCodePair::from_str("foo: E501");
|
||||
let result = PatternPrefixPair::from_str("foo: E501");
|
||||
assert!(result.is_ok());
|
||||
let result = StrCheckCodePair::from_str("E501:foo");
|
||||
let result = PatternPrefixPair::from_str("E501:foo");
|
||||
assert!(result.is_err());
|
||||
let result = StrCheckCodePair::from_str("E501");
|
||||
let result = PatternPrefixPair::from_str("E501");
|
||||
assert!(result.is_err());
|
||||
let result = StrCheckCodePair::from_str("foo");
|
||||
let result = PatternPrefixPair::from_str("foo");
|
||||
assert!(result.is_err());
|
||||
let result = StrCheckCodePair::from_str("foo:E501:E402");
|
||||
let result = PatternPrefixPair::from_str("foo:E501:E402");
|
||||
assert!(result.is_err());
|
||||
let result = StrCheckCodePair::from_str("**/bar:E501");
|
||||
let result = PatternPrefixPair::from_str("**/bar:E501");
|
||||
assert!(result.is_ok());
|
||||
let result = StrCheckCodePair::from_str("bar:E502");
|
||||
let result = PatternPrefixPair::from_str("bar:E502");
|
||||
assert!(result.is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,24 +75,28 @@ pub struct PerFileIgnore {
|
||||
}
|
||||
|
||||
impl PerFileIgnore {
|
||||
pub fn new(user_in: StrCheckCodePair, project_root: &Option<PathBuf>) -> Self {
|
||||
let pattern = FilePattern::from_user(user_in.pattern.as_str(), project_root);
|
||||
let codes = BTreeSet::from_iter(user_in.code.codes());
|
||||
pub fn new(
|
||||
pattern: &str,
|
||||
prefixes: &[CheckCodePrefix],
|
||||
project_root: &Option<PathBuf>,
|
||||
) -> Self {
|
||||
let pattern = FilePattern::from_user(pattern, project_root);
|
||||
let codes = BTreeSet::from_iter(prefixes.iter().flat_map(|prefix| prefix.codes()));
|
||||
Self { pattern, codes }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StrCheckCodePair {
|
||||
pub struct PatternPrefixPair {
|
||||
pub pattern: String,
|
||||
pub code: CheckCodePrefix,
|
||||
pub prefix: CheckCodePrefix,
|
||||
}
|
||||
|
||||
impl StrCheckCodePair {
|
||||
impl PatternPrefixPair {
|
||||
const EXPECTED_PATTERN: &'static str = "<FilePattern>:<CheckCode> pattern";
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for StrCheckCodePair {
|
||||
impl<'de> Deserialize<'de> for PatternPrefixPair {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
@@ -107,7 +111,7 @@ impl<'de> Deserialize<'de> for StrCheckCodePair {
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for StrCheckCodePair {
|
||||
impl FromStr for PatternPrefixPair {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(string: &str) -> Result<Self, Self::Err> {
|
||||
@@ -118,8 +122,8 @@ impl FromStr for StrCheckCodePair {
|
||||
}
|
||||
(tokens[0].trim(), tokens[1].trim())
|
||||
};
|
||||
let code = CheckCodePrefix::from_str(code_string)?;
|
||||
let pattern = pattern_str.into();
|
||||
Ok(Self { pattern, code })
|
||||
let prefix = CheckCodePrefix::from_str(code_string)?;
|
||||
Ok(Self { pattern, prefix })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
//! Structs to render user-facing settings.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use regex::Regex;
|
||||
|
||||
use crate::checks_gen::CheckCodePrefix;
|
||||
use crate::settings::types::{FilePattern, PerFileIgnore, PythonVersion};
|
||||
use crate::{flake8_quotes, Configuration};
|
||||
use crate::settings::types::{FilePattern, PythonVersion};
|
||||
use crate::{flake8_quotes, pep8_naming, Configuration};
|
||||
|
||||
/// Struct to render user-facing exclusion patterns.
|
||||
#[derive(Debug)]
|
||||
@@ -41,11 +42,12 @@ pub struct UserConfiguration {
|
||||
pub extend_select: Vec<CheckCodePrefix>,
|
||||
pub ignore: Vec<CheckCodePrefix>,
|
||||
pub line_length: usize,
|
||||
pub per_file_ignores: Vec<PerFileIgnore>,
|
||||
pub per_file_ignores: BTreeMap<String, Vec<CheckCodePrefix>>,
|
||||
pub select: Vec<CheckCodePrefix>,
|
||||
pub target_version: PythonVersion,
|
||||
// Plugins
|
||||
pub flake8_quotes: flake8_quotes::settings::Settings,
|
||||
pub pep8_naming: pep8_naming::settings::Settings,
|
||||
// Non-settings exposed to the user
|
||||
pub project_root: Option<PathBuf>,
|
||||
pub pyproject: Option<PathBuf>,
|
||||
@@ -53,30 +55,31 @@ pub struct UserConfiguration {
|
||||
|
||||
impl UserConfiguration {
|
||||
pub fn from_configuration(
|
||||
settings: Configuration,
|
||||
configuration: Configuration,
|
||||
project_root: Option<PathBuf>,
|
||||
pyproject: Option<PathBuf>,
|
||||
) -> Self {
|
||||
Self {
|
||||
dummy_variable_rgx: settings.dummy_variable_rgx,
|
||||
exclude: settings
|
||||
dummy_variable_rgx: configuration.dummy_variable_rgx,
|
||||
exclude: configuration
|
||||
.exclude
|
||||
.into_iter()
|
||||
.map(Exclusion::from_file_pattern)
|
||||
.collect(),
|
||||
extend_exclude: settings
|
||||
extend_exclude: configuration
|
||||
.extend_exclude
|
||||
.into_iter()
|
||||
.map(Exclusion::from_file_pattern)
|
||||
.collect(),
|
||||
extend_ignore: settings.extend_ignore,
|
||||
extend_select: settings.extend_select,
|
||||
ignore: settings.ignore,
|
||||
line_length: settings.line_length,
|
||||
per_file_ignores: settings.per_file_ignores,
|
||||
select: settings.select,
|
||||
target_version: settings.target_version,
|
||||
flake8_quotes: settings.flake8_quotes,
|
||||
extend_ignore: configuration.extend_ignore,
|
||||
extend_select: configuration.extend_select,
|
||||
ignore: configuration.ignore,
|
||||
line_length: configuration.line_length,
|
||||
per_file_ignores: configuration.per_file_ignores,
|
||||
select: configuration.select,
|
||||
target_version: configuration.target_version,
|
||||
flake8_quotes: configuration.flake8_quotes,
|
||||
pep8_naming: configuration.pep8_naming,
|
||||
project_root,
|
||||
pyproject,
|
||||
}
|
||||
|
||||
@@ -6,162 +6,162 @@ expression: checks
|
||||
BuiltinVariableShadowing: sum
|
||||
location:
|
||||
row: 1
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 1
|
||||
column: 19
|
||||
column: 18
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: int
|
||||
location:
|
||||
row: 2
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 2
|
||||
column: 30
|
||||
column: 29
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: print
|
||||
location:
|
||||
row: 4
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 4
|
||||
column: 6
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: copyright
|
||||
location:
|
||||
row: 5
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 5
|
||||
column: 10
|
||||
column: 9
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: complex
|
||||
location:
|
||||
row: 6
|
||||
column: 2
|
||||
column: 1
|
||||
end_location:
|
||||
row: 6
|
||||
column: 14
|
||||
column: 13
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: float
|
||||
location:
|
||||
row: 7
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 7
|
||||
column: 6
|
||||
column: 5
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: object
|
||||
location:
|
||||
row: 7
|
||||
column: 9
|
||||
column: 8
|
||||
end_location:
|
||||
row: 7
|
||||
column: 15
|
||||
column: 14
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: min
|
||||
location:
|
||||
row: 8
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 8
|
||||
column: 4
|
||||
column: 3
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: max
|
||||
location:
|
||||
row: 8
|
||||
column: 6
|
||||
column: 5
|
||||
end_location:
|
||||
row: 8
|
||||
column: 9
|
||||
column: 8
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: bytes
|
||||
location:
|
||||
row: 10
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 13
|
||||
column: 1
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: slice
|
||||
location:
|
||||
row: 13
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 16
|
||||
column: 1
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: ValueError
|
||||
location:
|
||||
row: 18
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 21
|
||||
column: 1
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: memoryview
|
||||
location:
|
||||
row: 21
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 21
|
||||
column: 15
|
||||
column: 14
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: bytearray
|
||||
location:
|
||||
row: 21
|
||||
column: 18
|
||||
column: 17
|
||||
end_location:
|
||||
row: 21
|
||||
column: 27
|
||||
column: 26
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: str
|
||||
location:
|
||||
row: 24
|
||||
column: 22
|
||||
column: 21
|
||||
end_location:
|
||||
row: 24
|
||||
column: 25
|
||||
column: 24
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: all
|
||||
location:
|
||||
row: 24
|
||||
column: 45
|
||||
column: 44
|
||||
end_location:
|
||||
row: 24
|
||||
column: 48
|
||||
column: 47
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: any
|
||||
location:
|
||||
row: 24
|
||||
column: 50
|
||||
column: 49
|
||||
end_location:
|
||||
row: 24
|
||||
column: 53
|
||||
column: 52
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinVariableShadowing: sum
|
||||
location:
|
||||
row: 27
|
||||
column: 8
|
||||
column: 7
|
||||
end_location:
|
||||
row: 27
|
||||
column: 11
|
||||
column: 10
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,63 +6,63 @@ expression: checks
|
||||
BuiltinArgumentShadowing: str
|
||||
location:
|
||||
row: 1
|
||||
column: 11
|
||||
column: 10
|
||||
end_location:
|
||||
row: 1
|
||||
column: 14
|
||||
column: 13
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinArgumentShadowing: type
|
||||
location:
|
||||
row: 1
|
||||
column: 19
|
||||
column: 18
|
||||
end_location:
|
||||
row: 1
|
||||
column: 23
|
||||
column: 22
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinArgumentShadowing: complex
|
||||
location:
|
||||
row: 1
|
||||
column: 26
|
||||
column: 25
|
||||
end_location:
|
||||
row: 1
|
||||
column: 33
|
||||
column: 32
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinArgumentShadowing: Exception
|
||||
location:
|
||||
row: 1
|
||||
column: 35
|
||||
column: 34
|
||||
end_location:
|
||||
row: 1
|
||||
column: 44
|
||||
column: 43
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinArgumentShadowing: getattr
|
||||
location:
|
||||
row: 1
|
||||
column: 48
|
||||
column: 47
|
||||
end_location:
|
||||
row: 1
|
||||
column: 55
|
||||
column: 54
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinArgumentShadowing: bytes
|
||||
location:
|
||||
row: 5
|
||||
column: 17
|
||||
column: 16
|
||||
end_location:
|
||||
row: 5
|
||||
column: 22
|
||||
column: 21
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinArgumentShadowing: float
|
||||
location:
|
||||
row: 9
|
||||
column: 16
|
||||
column: 15
|
||||
end_location:
|
||||
row: 9
|
||||
column: 21
|
||||
column: 20
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,18 +6,18 @@ expression: checks
|
||||
BuiltinAttributeShadowing: ImportError
|
||||
location:
|
||||
row: 2
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 2
|
||||
column: 16
|
||||
column: 15
|
||||
fix: ~
|
||||
- kind:
|
||||
BuiltinAttributeShadowing: str
|
||||
location:
|
||||
row: 7
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 9
|
||||
column: 1
|
||||
column: 0
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -5,17 +5,17 @@ expression: checks
|
||||
- kind: UnaryPrefixIncrement
|
||||
location:
|
||||
row: 15
|
||||
column: 9
|
||||
column: 8
|
||||
end_location:
|
||||
row: 15
|
||||
column: 12
|
||||
column: 11
|
||||
fix: ~
|
||||
- kind: UnaryPrefixIncrement
|
||||
location:
|
||||
row: 20
|
||||
column: 12
|
||||
column: 11
|
||||
end_location:
|
||||
row: 20
|
||||
column: 15
|
||||
column: 14
|
||||
fix: ~
|
||||
|
||||
|
||||
93
src/snapshots/ruff__linter__tests__B006_B006_B008.py.snap
Normal file
93
src/snapshots/ruff__linter__tests__B006_B006_B008.py.snap
Normal file
@@ -0,0 +1,93 @@
|
||||
---
|
||||
source: src/linter.rs
|
||||
expression: checks
|
||||
---
|
||||
- kind: MutableArgumentDefault
|
||||
location:
|
||||
row: 60
|
||||
column: 24
|
||||
end_location:
|
||||
row: 60
|
||||
column: 33
|
||||
fix: ~
|
||||
- kind: MutableArgumentDefault
|
||||
location:
|
||||
row: 64
|
||||
column: 29
|
||||
end_location:
|
||||
row: 64
|
||||
column: 31
|
||||
fix: ~
|
||||
- kind: MutableArgumentDefault
|
||||
location:
|
||||
row: 68
|
||||
column: 19
|
||||
end_location:
|
||||
row: 68
|
||||
column: 24
|
||||
fix: ~
|
||||
- kind: MutableArgumentDefault
|
||||
location:
|
||||
row: 72
|
||||
column: 19
|
||||
end_location:
|
||||
row: 72
|
||||
column: 44
|
||||
fix: ~
|
||||
- kind: MutableArgumentDefault
|
||||
location:
|
||||
row: 76
|
||||
column: 31
|
||||
end_location:
|
||||
row: 76
|
||||
column: 56
|
||||
fix: ~
|
||||
- kind: MutableArgumentDefault
|
||||
location:
|
||||
row: 80
|
||||
column: 25
|
||||
end_location:
|
||||
row: 80
|
||||
column: 44
|
||||
fix: ~
|
||||
- kind: MutableArgumentDefault
|
||||
location:
|
||||
row: 85
|
||||
column: 45
|
||||
end_location:
|
||||
row: 85
|
||||
column: 69
|
||||
fix: ~
|
||||
- kind: MutableArgumentDefault
|
||||
location:
|
||||
row: 89
|
||||
column: 45
|
||||
end_location:
|
||||
row: 89
|
||||
column: 72
|
||||
fix: ~
|
||||
- kind: MutableArgumentDefault
|
||||
location:
|
||||
row: 93
|
||||
column: 44
|
||||
end_location:
|
||||
row: 93
|
||||
column: 68
|
||||
fix: ~
|
||||
- kind: MutableArgumentDefault
|
||||
location:
|
||||
row: 97
|
||||
column: 32
|
||||
end_location:
|
||||
row: 97
|
||||
column: 34
|
||||
fix: ~
|
||||
- kind: MutableArgumentDefault
|
||||
location:
|
||||
row: 170
|
||||
column: 19
|
||||
end_location:
|
||||
row: 170
|
||||
column: 48
|
||||
fix: ~
|
||||
|
||||
@@ -6,72 +6,72 @@ expression: checks
|
||||
UnusedLoopControlVariable: i
|
||||
location:
|
||||
row: 6
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 6
|
||||
column: 6
|
||||
column: 5
|
||||
fix:
|
||||
patch:
|
||||
content: _i
|
||||
location:
|
||||
row: 6
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 6
|
||||
column: 6
|
||||
column: 5
|
||||
applied: false
|
||||
- kind:
|
||||
UnusedLoopControlVariable: k
|
||||
location:
|
||||
row: 18
|
||||
column: 13
|
||||
column: 12
|
||||
end_location:
|
||||
row: 18
|
||||
column: 14
|
||||
column: 13
|
||||
fix:
|
||||
patch:
|
||||
content: _k
|
||||
location:
|
||||
row: 18
|
||||
column: 13
|
||||
column: 12
|
||||
end_location:
|
||||
row: 18
|
||||
column: 14
|
||||
column: 13
|
||||
applied: false
|
||||
- kind:
|
||||
UnusedLoopControlVariable: i
|
||||
location:
|
||||
row: 30
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 30
|
||||
column: 6
|
||||
column: 5
|
||||
fix:
|
||||
patch:
|
||||
content: _i
|
||||
location:
|
||||
row: 30
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 30
|
||||
column: 6
|
||||
column: 5
|
||||
applied: false
|
||||
- kind:
|
||||
UnusedLoopControlVariable: k
|
||||
location:
|
||||
row: 30
|
||||
column: 13
|
||||
column: 12
|
||||
end_location:
|
||||
row: 30
|
||||
column: 14
|
||||
column: 13
|
||||
fix:
|
||||
patch:
|
||||
content: _k
|
||||
location:
|
||||
row: 30
|
||||
column: 13
|
||||
column: 12
|
||||
end_location:
|
||||
row: 30
|
||||
column: 14
|
||||
column: 13
|
||||
applied: false
|
||||
|
||||
|
||||
@@ -5,35 +5,35 @@ expression: checks
|
||||
- kind: DoNotAssertFalse
|
||||
location:
|
||||
row: 8
|
||||
column: 8
|
||||
column: 7
|
||||
end_location:
|
||||
row: 8
|
||||
column: 13
|
||||
column: 12
|
||||
fix:
|
||||
patch:
|
||||
content: raise AssertionError()
|
||||
location:
|
||||
row: 8
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 8
|
||||
column: 13
|
||||
column: 12
|
||||
applied: false
|
||||
- kind: DoNotAssertFalse
|
||||
location:
|
||||
row: 10
|
||||
column: 8
|
||||
column: 7
|
||||
end_location:
|
||||
row: 10
|
||||
column: 13
|
||||
column: 12
|
||||
fix:
|
||||
patch:
|
||||
content: "raise AssertionError('message')"
|
||||
location:
|
||||
row: 10
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 10
|
||||
column: 24
|
||||
column: 23
|
||||
applied: false
|
||||
|
||||
|
||||
@@ -6,9 +6,9 @@ expression: checks
|
||||
RedundantTupleInExceptionHandler: ValueError
|
||||
location:
|
||||
row: 3
|
||||
column: 9
|
||||
column: 8
|
||||
end_location:
|
||||
row: 3
|
||||
column: 20
|
||||
column: 19
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -7,56 +7,56 @@ expression: checks
|
||||
- OSError
|
||||
location:
|
||||
row: 17
|
||||
column: 9
|
||||
column: 8
|
||||
end_location:
|
||||
row: 17
|
||||
column: 25
|
||||
column: 24
|
||||
fix:
|
||||
patch:
|
||||
content: "OSError,"
|
||||
location:
|
||||
row: 17
|
||||
column: 9
|
||||
column: 8
|
||||
end_location:
|
||||
row: 17
|
||||
column: 25
|
||||
column: 24
|
||||
applied: false
|
||||
- kind:
|
||||
DuplicateHandlerException:
|
||||
- MyError
|
||||
location:
|
||||
row: 28
|
||||
column: 9
|
||||
column: 8
|
||||
end_location:
|
||||
row: 28
|
||||
column: 25
|
||||
column: 24
|
||||
fix:
|
||||
patch:
|
||||
content: "MyError,"
|
||||
location:
|
||||
row: 28
|
||||
column: 9
|
||||
column: 8
|
||||
end_location:
|
||||
row: 28
|
||||
column: 25
|
||||
column: 24
|
||||
applied: false
|
||||
- kind:
|
||||
DuplicateHandlerException:
|
||||
- re.error
|
||||
location:
|
||||
row: 49
|
||||
column: 9
|
||||
column: 8
|
||||
end_location:
|
||||
row: 49
|
||||
column: 27
|
||||
column: 26
|
||||
fix:
|
||||
patch:
|
||||
content: "re.error,"
|
||||
location:
|
||||
row: 49
|
||||
column: 9
|
||||
column: 8
|
||||
end_location:
|
||||
row: 49
|
||||
column: 27
|
||||
column: 26
|
||||
applied: false
|
||||
|
||||
|
||||
@@ -5,9 +5,9 @@ expression: checks
|
||||
- kind: NoAssertRaisesException
|
||||
location:
|
||||
row: 22
|
||||
column: 9
|
||||
column: 8
|
||||
end_location:
|
||||
row: 25
|
||||
column: 5
|
||||
column: 4
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -6,36 +6,36 @@ expression: checks
|
||||
DuplicateTryBlockException: ValueError
|
||||
location:
|
||||
row: 15
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 22
|
||||
column: 1
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind:
|
||||
DuplicateTryBlockException: pickle.PickleError
|
||||
location:
|
||||
row: 22
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 31
|
||||
column: 1
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind:
|
||||
DuplicateTryBlockException: TypeError
|
||||
location:
|
||||
row: 31
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 39
|
||||
column: 1
|
||||
column: 0
|
||||
fix: ~
|
||||
- kind:
|
||||
DuplicateTryBlockException: ValueError
|
||||
location:
|
||||
row: 31
|
||||
column: 1
|
||||
column: 0
|
||||
end_location:
|
||||
row: 39
|
||||
column: 1
|
||||
column: 0
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -5,9 +5,9 @@ expression: checks
|
||||
- kind: UnnecessaryGeneratorList
|
||||
location:
|
||||
row: 1
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 1
|
||||
column: 30
|
||||
column: 29
|
||||
fix: ~
|
||||
|
||||
|
||||
@@ -5,9 +5,9 @@ expression: checks
|
||||
- kind: UnnecessaryGeneratorSet
|
||||
location:
|
||||
row: 1
|
||||
column: 5
|
||||
column: 4
|
||||
end_location:
|
||||
row: 1
|
||||
column: 29
|
||||
column: 28
|
||||
fix: ~
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user