Compare commits
209 Commits
micha/fixp
...
david/type
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9220598fc8 | ||
|
|
f9ca6eb63e | ||
|
|
8729cb208f | ||
|
|
a2c87c2bc1 | ||
|
|
b302d89da3 | ||
|
|
ce43dbab58 | ||
|
|
fb589730ef | ||
|
|
4fad15805b | ||
|
|
0ede831a3f | ||
|
|
d6009eb942 | ||
|
|
236633cd42 | ||
|
|
99cb89f90f | ||
|
|
ac5df56aa3 | ||
|
|
6985de4c40 | ||
|
|
55a410a885 | ||
|
|
97058e8093 | ||
|
|
569c94b71b | ||
|
|
59d80aff9f | ||
|
|
b913f568c4 | ||
|
|
4c889d5251 | ||
|
|
220137ca7b | ||
|
|
34337fb8ba | ||
|
|
38c332fe23 | ||
|
|
9f743d1b9f | ||
|
|
405544cc8f | ||
|
|
ab96adbcd1 | ||
|
|
a761b8cfa2 | ||
|
|
8c020cc2e9 | ||
|
|
c67aa0cce2 | ||
|
|
b00e390f3a | ||
|
|
1f9df0c8f0 | ||
|
|
9dd9227bca | ||
|
|
181a380ee0 | ||
|
|
12f5e99389 | ||
|
|
d9cd6399e6 | ||
|
|
c40a801002 | ||
|
|
04168cf1ce | ||
|
|
6d0703ae78 | ||
|
|
f7691a79a0 | ||
|
|
6e7340c68b | ||
|
|
5095248b7e | ||
|
|
b1e6c6edce | ||
|
|
8ee92c6c77 | ||
|
|
d6709abd94 | ||
|
|
660375d429 | ||
|
|
dd04ca7f58 | ||
|
|
b86960f18c | ||
|
|
2abcd86c57 | ||
|
|
c6e55f673c | ||
|
|
3d55a16c91 | ||
|
|
e21972a79b | ||
|
|
0adbb3d600 | ||
|
|
28fb802467 | ||
|
|
a1d007c37c | ||
|
|
1ba56b4bc6 | ||
|
|
e677cabd69 | ||
|
|
9910ec700c | ||
|
|
9ae698fe30 | ||
|
|
e67b35743a | ||
|
|
8644c9da43 | ||
|
|
196e4befba | ||
|
|
6e39250015 | ||
|
|
7dc4fefb47 | ||
|
|
e5435eb106 | ||
|
|
f53c580c53 | ||
|
|
2ceba6ae67 | ||
|
|
d3a7cb3fe4 | ||
|
|
69393b2e6e | ||
|
|
c066bf0127 | ||
|
|
a5ee1a3bb1 | ||
|
|
e2c5b83fe1 | ||
|
|
b35bf8ae07 | ||
|
|
279dac1c0e | ||
|
|
57617031de | ||
|
|
28b5a868d3 | ||
|
|
b6b7caa023 | ||
|
|
46be305ad2 | ||
|
|
c3a4992ae9 | ||
|
|
9aa6330bb1 | ||
|
|
b600ff106a | ||
|
|
466021d5e1 | ||
|
|
33e14c5963 | ||
|
|
6800a9f6f3 | ||
|
|
68559fc17d | ||
|
|
2a217e80ca | ||
|
|
030a16cb5f | ||
|
|
0590b38214 | ||
|
|
8104b1e83b | ||
|
|
cf70c7863c | ||
|
|
faf54c0181 | ||
|
|
451c5db7a3 | ||
|
|
bd5b7f415f | ||
|
|
0230cbac2c | ||
|
|
2e94d37275 | ||
|
|
1e4377c9c6 | ||
|
|
1b4f7de840 | ||
|
|
9b52ae8991 | ||
|
|
97d7b46936 | ||
|
|
1eab59e681 | ||
|
|
e7f97a3e4b | ||
|
|
d17557f0ae | ||
|
|
8cbd433a31 | ||
|
|
65e48cb439 | ||
|
|
301d9985d8 | ||
|
|
cfbb914100 | ||
|
|
fe653de3dd | ||
|
|
a9f7521944 | ||
|
|
f8890b70c3 | ||
|
|
142c1bc760 | ||
|
|
c0f22928bd | ||
|
|
5bf5f3682a | ||
|
|
5913997c72 | ||
|
|
00f672a83b | ||
|
|
68b0386007 | ||
|
|
0ae07cdd1f | ||
|
|
0fb94c052e | ||
|
|
55df9271ba | ||
|
|
f301931159 | ||
|
|
7e9b0df18a | ||
|
|
41fa082414 | ||
|
|
c7b6108cb8 | ||
|
|
a97e72fb5e | ||
|
|
0d6fafd0f9 | ||
|
|
2eb2d5359b | ||
|
|
f549dfe39d | ||
|
|
6b64630635 | ||
|
|
d545b5bfd2 | ||
|
|
b2d9f59937 | ||
|
|
d7ef01401c | ||
|
|
c9031ce59f | ||
|
|
138ab91def | ||
|
|
550b8be552 | ||
|
|
bdccb37b4a | ||
|
|
3ccc0edfe4 | ||
|
|
6b3ff6f5b8 | ||
|
|
6f8f7506b4 | ||
|
|
797eb70904 | ||
|
|
be6ec613db | ||
|
|
fcd858e0c8 | ||
|
|
d944a1397e | ||
|
|
d3f3d92df3 | ||
|
|
38c00dfad5 | ||
|
|
d6280c5aea | ||
|
|
a34240a3f0 | ||
|
|
b86c7bbf7c | ||
|
|
d7c54ba8c4 | ||
|
|
c38d6e8045 | ||
|
|
2bfd7b1816 | ||
|
|
c1cfb43bf0 | ||
|
|
99555b775c | ||
|
|
b398b83631 | ||
|
|
bc7b30364d | ||
|
|
5792ed15da | ||
|
|
8845a13efb | ||
|
|
669855d2b5 | ||
|
|
ff7ebecf89 | ||
|
|
7e8ba2b68e | ||
|
|
0bb8cbdf07 | ||
|
|
2923c55698 | ||
|
|
316e406ca4 | ||
|
|
5ecd560c6f | ||
|
|
b765dc48e9 | ||
|
|
cd1d906ffa | ||
|
|
235b74a310 | ||
|
|
40fd52dde0 | ||
|
|
fd1eb3d801 | ||
|
|
882a1a702e | ||
|
|
b4a1ebdfe3 | ||
|
|
7a48477c67 | ||
|
|
346e82b572 | ||
|
|
5ea3a52c8a | ||
|
|
90272ad85a | ||
|
|
e9da1750a1 | ||
|
|
25e13debc0 | ||
|
|
249a852a6e | ||
|
|
861ef2504e | ||
|
|
b71ef8a26e | ||
|
|
50c780fc8b | ||
|
|
244ea27d5f | ||
|
|
2c4cbb6e29 | ||
|
|
d1bb10a66b | ||
|
|
2370297cde | ||
|
|
a137cb18d4 | ||
|
|
03a4d56624 | ||
|
|
642eac452d | ||
|
|
c1b875799b | ||
|
|
6cd8a49638 | ||
|
|
12ce445ff7 | ||
|
|
f46ed8d410 | ||
|
|
6c177e2bbe | ||
|
|
3d2485eb1b | ||
|
|
f78367979e | ||
|
|
b705664d49 | ||
|
|
f51f1f7153 | ||
|
|
9b694ada82 | ||
|
|
4d81a41107 | ||
|
|
981bd70d39 | ||
|
|
0763331f7f | ||
|
|
da8540862d | ||
|
|
6a5533c44c | ||
|
|
d608eae126 | ||
|
|
067a8ac574 | ||
|
|
5eb215e8e5 | ||
|
|
91aa853b9c | ||
|
|
57bf7dfbd9 | ||
|
|
67cd94ed64 | ||
|
|
aac862822f | ||
|
|
3755ac9fac | ||
|
|
4f890b2867 |
1
.gitattributes
vendored
1
.gitattributes
vendored
@@ -21,6 +21,7 @@ crates/ruff_linter/resources/test/fixtures/pyupgrade/UP018_LF.py text eol=lf
|
||||
crates/ruff_python_parser/resources/inline linguist-generated=true
|
||||
|
||||
ruff.schema.json -diff linguist-generated=true text=auto eol=lf
|
||||
ty.schema.json -diff linguist-generated=true text=auto eol=lf
|
||||
crates/ruff_python_ast/src/generated.rs -diff linguist-generated=true text=auto eol=lf
|
||||
crates/ruff_python_formatter/src/generated.rs -diff linguist-generated=true text=auto eol=lf
|
||||
*.md.snap linguist-language=Markdown
|
||||
|
||||
5
.github/PULL_REQUEST_TEMPLATE.md
vendored
5
.github/PULL_REQUEST_TEMPLATE.md
vendored
@@ -1,8 +1,9 @@
|
||||
<!--
|
||||
Thank you for contributing to Ruff! To help us out with reviewing, please consider the following:
|
||||
Thank you for contributing to Ruff/ty! To help us out with reviewing, please consider the following:
|
||||
|
||||
- Does this pull request include a summary of the change? (See below.)
|
||||
- Does this pull request include a descriptive title?
|
||||
- Does this pull request include a descriptive title? (Please prefix with `[ty]` for ty pull
|
||||
requests.)
|
||||
- Does this pull request include references to any relevant issues?
|
||||
-->
|
||||
|
||||
|
||||
7
.github/mypy-primer-ty.toml
vendored
Normal file
7
.github/mypy-primer-ty.toml
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
#:schema ../ty.schema.json
|
||||
# Configuration overrides for the mypy primer run
|
||||
|
||||
# Enable off-by-default rules.
|
||||
[rules]
|
||||
possibly-unresolved-reference = "warn"
|
||||
unused-ignore-comment = "warn"
|
||||
4
.github/workflows/build-binaries.yml
vendored
4
.github/workflows/build-binaries.yml
vendored
@@ -310,7 +310,7 @@ jobs:
|
||||
manylinux: auto
|
||||
docker-options: ${{ matrix.platform.maturin_docker_options }}
|
||||
args: --release --locked --out dist
|
||||
- uses: uraimo/run-on-arch-action@ac33288c3728ca72563c97b8b88dda5a65a84448 # v2
|
||||
- uses: uraimo/run-on-arch-action@d94c13912ea685de38fccc1109385b83fd79427d # v3.0.1
|
||||
if: ${{ matrix.platform.arch != 'ppc64' && matrix.platform.arch != 'ppc64le'}}
|
||||
name: Test wheel
|
||||
with:
|
||||
@@ -441,7 +441,7 @@ jobs:
|
||||
manylinux: musllinux_1_2
|
||||
args: --release --locked --out dist
|
||||
docker-options: ${{ matrix.platform.maturin_docker_options }}
|
||||
- uses: uraimo/run-on-arch-action@ac33288c3728ca72563c97b8b88dda5a65a84448 # v2
|
||||
- uses: uraimo/run-on-arch-action@d94c13912ea685de38fccc1109385b83fd79427d # v3.0.1
|
||||
name: Test wheel
|
||||
with:
|
||||
arch: ${{ matrix.platform.arch }}
|
||||
|
||||
28
.github/workflows/build-docker.yml
vendored
28
.github/workflows/build-docker.yml
vendored
@@ -38,9 +38,9 @@ jobs:
|
||||
submodules: recursive
|
||||
persist-credentials: false
|
||||
|
||||
- uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3
|
||||
- uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
|
||||
|
||||
- uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3
|
||||
- uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -63,7 +63,7 @@ jobs:
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # v5
|
||||
uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # v5.7.0
|
||||
with:
|
||||
images: ${{ env.RUFF_BASE_IMG }}
|
||||
# Defining this makes sure the org.opencontainers.image.version OCI label becomes the actual release version and not the branch name
|
||||
@@ -79,7 +79,7 @@ jobs:
|
||||
# Adapted from https://docs.docker.com/build/ci/github-actions/multi-platform/
|
||||
- name: Build and push by digest
|
||||
id: build
|
||||
uses: docker/build-push-action@14487ce63c7a62a4a324b0bfb37086795e31c6c1 # v6
|
||||
uses: docker/build-push-action@1dc73863535b631f98b2378be8619f83b136f4a0 # v6.17.0
|
||||
with:
|
||||
context: .
|
||||
platforms: ${{ matrix.platform }}
|
||||
@@ -119,11 +119,11 @@ jobs:
|
||||
pattern: digests-*
|
||||
merge-multiple: true
|
||||
|
||||
- uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3
|
||||
- uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # v5
|
||||
uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # v5.7.0
|
||||
with:
|
||||
images: ${{ env.RUFF_BASE_IMG }}
|
||||
# Order is on purpose such that the label org.opencontainers.image.version has the first pattern with the full version
|
||||
@@ -131,7 +131,7 @@ jobs:
|
||||
type=pep440,pattern={{ version }},value=${{ fromJson(inputs.plan).announcement_tag }}
|
||||
type=pep440,pattern={{ major }}.{{ minor }},value=${{ fromJson(inputs.plan).announcement_tag }}
|
||||
|
||||
- uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3
|
||||
- uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -167,9 +167,9 @@ jobs:
|
||||
- debian:bookworm-slim,bookworm-slim,debian-slim
|
||||
- buildpack-deps:bookworm,bookworm,debian
|
||||
steps:
|
||||
- uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3
|
||||
- uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
|
||||
|
||||
- uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3
|
||||
- uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -219,7 +219,7 @@ jobs:
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # v5
|
||||
uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # v5.7.0
|
||||
# ghcr.io prefers index level annotations
|
||||
env:
|
||||
DOCKER_METADATA_ANNOTATIONS_LEVELS: index
|
||||
@@ -231,7 +231,7 @@ jobs:
|
||||
${{ env.TAG_PATTERNS }}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@14487ce63c7a62a4a324b0bfb37086795e31c6c1 # v6
|
||||
uses: docker/build-push-action@1dc73863535b631f98b2378be8619f83b136f4a0 # v6.17.0
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
@@ -262,11 +262,11 @@ jobs:
|
||||
pattern: digests-*
|
||||
merge-multiple: true
|
||||
|
||||
- uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3
|
||||
- uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # v5
|
||||
uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # v5.7.0
|
||||
env:
|
||||
DOCKER_METADATA_ANNOTATIONS_LEVELS: index
|
||||
with:
|
||||
@@ -276,7 +276,7 @@ jobs:
|
||||
type=pep440,pattern={{ version }},value=${{ fromJson(inputs.plan).announcement_tag }}
|
||||
type=pep440,pattern={{ major }}.{{ minor }},value=${{ fromJson(inputs.plan).announcement_tag }}
|
||||
|
||||
- uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3
|
||||
- uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
|
||||
36
.github/workflows/ci.yaml
vendored
36
.github/workflows/ci.yaml
vendored
@@ -239,11 +239,11 @@ jobs:
|
||||
- name: "Install mold"
|
||||
uses: rui314/setup-mold@e16410e7f8d9e167b74ad5697a9089a35126eb50 # v1
|
||||
- name: "Install cargo nextest"
|
||||
uses: taiki-e/install-action@86c23eed46c17b80677df6d8151545ce3e236c61 # v2
|
||||
uses: taiki-e/install-action@941e8a4d9d7cdb696bd4f017cf54aca281f8ffff # v2.51.2
|
||||
with:
|
||||
tool: cargo-nextest
|
||||
- name: "Install cargo insta"
|
||||
uses: taiki-e/install-action@86c23eed46c17b80677df6d8151545ce3e236c61 # v2
|
||||
uses: taiki-e/install-action@941e8a4d9d7cdb696bd4f017cf54aca281f8ffff # v2.51.2
|
||||
with:
|
||||
tool: cargo-insta
|
||||
- name: ty mdtests (GitHub annotations)
|
||||
@@ -297,11 +297,11 @@ jobs:
|
||||
- name: "Install mold"
|
||||
uses: rui314/setup-mold@e16410e7f8d9e167b74ad5697a9089a35126eb50 # v1
|
||||
- name: "Install cargo nextest"
|
||||
uses: taiki-e/install-action@86c23eed46c17b80677df6d8151545ce3e236c61 # v2
|
||||
uses: taiki-e/install-action@941e8a4d9d7cdb696bd4f017cf54aca281f8ffff # v2.51.2
|
||||
with:
|
||||
tool: cargo-nextest
|
||||
- name: "Install cargo insta"
|
||||
uses: taiki-e/install-action@86c23eed46c17b80677df6d8151545ce3e236c61 # v2
|
||||
uses: taiki-e/install-action@941e8a4d9d7cdb696bd4f017cf54aca281f8ffff # v2.51.2
|
||||
with:
|
||||
tool: cargo-insta
|
||||
- name: "Run tests"
|
||||
@@ -324,7 +324,7 @@ jobs:
|
||||
- name: "Install Rust toolchain"
|
||||
run: rustup show
|
||||
- name: "Install cargo nextest"
|
||||
uses: taiki-e/install-action@86c23eed46c17b80677df6d8151545ce3e236c61 # v2
|
||||
uses: taiki-e/install-action@941e8a4d9d7cdb696bd4f017cf54aca281f8ffff # v2.51.2
|
||||
with:
|
||||
tool: cargo-nextest
|
||||
- name: "Run tests"
|
||||
@@ -407,11 +407,11 @@ jobs:
|
||||
- name: "Install mold"
|
||||
uses: rui314/setup-mold@e16410e7f8d9e167b74ad5697a9089a35126eb50 # v1
|
||||
- name: "Install cargo nextest"
|
||||
uses: taiki-e/install-action@86c23eed46c17b80677df6d8151545ce3e236c61 # v2
|
||||
uses: taiki-e/install-action@941e8a4d9d7cdb696bd4f017cf54aca281f8ffff # v2.51.2
|
||||
with:
|
||||
tool: cargo-nextest
|
||||
- name: "Install cargo insta"
|
||||
uses: taiki-e/install-action@86c23eed46c17b80677df6d8151545ce3e236c61 # v2
|
||||
uses: taiki-e/install-action@941e8a4d9d7cdb696bd4f017cf54aca281f8ffff # v2.51.2
|
||||
with:
|
||||
tool: cargo-insta
|
||||
- name: "Run tests"
|
||||
@@ -437,7 +437,7 @@ jobs:
|
||||
- name: "Install Rust toolchain"
|
||||
run: rustup show
|
||||
- name: "Install cargo-binstall"
|
||||
uses: cargo-bins/cargo-binstall@63aaa5c1932cebabc34eceda9d92a70215dcead6 # v1.12.3
|
||||
uses: cargo-bins/cargo-binstall@5cbf019d8cb9b9d5b086218c41458ea35d817691 # v1.12.5
|
||||
with:
|
||||
tool: cargo-fuzz@0.11.2
|
||||
- name: "Install cargo-fuzz"
|
||||
@@ -459,7 +459,7 @@ jobs:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2
|
||||
- uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca # v6.0.1
|
||||
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
name: Download Ruff binary to test
|
||||
id: download-cached-binary
|
||||
@@ -504,12 +504,10 @@ jobs:
|
||||
# Verify that adding a plugin or rule produces clean code.
|
||||
- run: ./scripts/add_rule.py --name DoTheThing --prefix F --code 999 --linter pyflakes
|
||||
- run: cargo check
|
||||
- run: cargo fmt --all --check
|
||||
- run: |
|
||||
./scripts/add_plugin.py test --url https://pypi.org/project/-test/0.1.0/ --prefix TST
|
||||
./scripts/add_rule.py --name FirstRule --prefix TST --code 001 --linter test
|
||||
- run: cargo check
|
||||
- run: cargo fmt --all --check
|
||||
|
||||
ecosystem:
|
||||
name: "ecosystem"
|
||||
@@ -662,7 +660,7 @@ jobs:
|
||||
branch: ${{ github.event.pull_request.base.ref }}
|
||||
workflow: "ci.yaml"
|
||||
check_artifacts: true
|
||||
- uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2
|
||||
- uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca # v6.0.1
|
||||
- name: Fuzz
|
||||
env:
|
||||
FORCE_COLOR: 1
|
||||
@@ -692,7 +690,7 @@ jobs:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: cargo-bins/cargo-binstall@63aaa5c1932cebabc34eceda9d92a70215dcead6 # v1.12.3
|
||||
- uses: cargo-bins/cargo-binstall@5cbf019d8cb9b9d5b086218c41458ea35d817691 # v1.12.5
|
||||
- run: cargo binstall --no-confirm cargo-shear
|
||||
- run: cargo shear
|
||||
|
||||
@@ -732,7 +730,11 @@ jobs:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2
|
||||
- uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca # v6.0.1
|
||||
- uses: Swatinem/rust-cache@9d47c6ad4b02e050fd481d890b2ea34778fd09d6 # v2.7.8
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: 22
|
||||
- name: "Cache pre-commit"
|
||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
||||
with:
|
||||
@@ -771,7 +773,7 @@ jobs:
|
||||
- name: "Install Rust toolchain"
|
||||
run: rustup show
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2
|
||||
uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca # v6.0.1
|
||||
- name: "Install Insiders dependencies"
|
||||
if: ${{ env.MKDOCS_INSIDERS_SSH_KEY_EXISTS == 'true' }}
|
||||
run: uv pip install -r docs/requirements-insiders.txt --system
|
||||
@@ -820,7 +822,7 @@ jobs:
|
||||
- determine_changes
|
||||
if: ${{ !contains(github.event.pull_request.labels.*.name, 'no-test') && (needs.determine_changes.outputs.code == 'true' || github.ref == 'refs/heads/main') }}
|
||||
steps:
|
||||
- uses: extractions/setup-just@dd310ad5a97d8e7b41793f8ef055398d51ad4de6 # v2
|
||||
- uses: extractions/setup-just@e33e0265a09d6d736e2ee1e0eb685ef1de4669ff # v3.0.0
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -908,7 +910,7 @@ jobs:
|
||||
run: rustup show
|
||||
|
||||
- name: "Install codspeed"
|
||||
uses: taiki-e/install-action@86c23eed46c17b80677df6d8151545ce3e236c61 # v2
|
||||
uses: taiki-e/install-action@941e8a4d9d7cdb696bd4f017cf54aca281f8ffff # v2.51.2
|
||||
with:
|
||||
tool: cargo-codspeed
|
||||
|
||||
|
||||
2
.github/workflows/daily_fuzz.yaml
vendored
2
.github/workflows/daily_fuzz.yaml
vendored
@@ -34,7 +34,7 @@ jobs:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2
|
||||
- uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca # v6.0.1
|
||||
- name: "Install Rust toolchain"
|
||||
run: rustup show
|
||||
- name: "Install mold"
|
||||
|
||||
72
.github/workflows/daily_property_tests.yaml
vendored
72
.github/workflows/daily_property_tests.yaml
vendored
@@ -1,72 +0,0 @@
|
||||
name: Daily property test run
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "0 12 * * *"
|
||||
pull_request:
|
||||
paths:
|
||||
- ".github/workflows/daily_property_tests.yaml"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
CARGO_INCREMENTAL: 0
|
||||
CARGO_NET_RETRY: 10
|
||||
CARGO_TERM_COLOR: always
|
||||
RUSTUP_MAX_RETRIES: 10
|
||||
FORCE_COLOR: 1
|
||||
|
||||
jobs:
|
||||
property_tests:
|
||||
name: Property tests
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
# Don't run the cron job on forks:
|
||||
if: ${{ github.repository == 'astral-sh/ruff' || github.event_name != 'schedule' }}
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: "Install Rust toolchain"
|
||||
run: rustup show
|
||||
- name: "Install mold"
|
||||
uses: rui314/setup-mold@e16410e7f8d9e167b74ad5697a9089a35126eb50 # v1
|
||||
- uses: Swatinem/rust-cache@9d47c6ad4b02e050fd481d890b2ea34778fd09d6 # v2.7.8
|
||||
- name: Build ty
|
||||
# A release build takes longer (2 min vs 1 min), but the property tests run much faster in release
|
||||
# mode (1.5 min vs 14 min), so the overall time is shorter with a release build.
|
||||
run: cargo build --locked --release --package ty_python_semantic --tests
|
||||
- name: Run property tests
|
||||
shell: bash
|
||||
run: |
|
||||
export QUICKCHECK_TESTS=100000
|
||||
for _ in {1..5}; do
|
||||
cargo test --locked --release --package ty_python_semantic -- --ignored list::property_tests
|
||||
cargo test --locked --release --package ty_python_semantic -- --ignored types::property_tests::stable
|
||||
done
|
||||
|
||||
create-issue-on-failure:
|
||||
name: Create an issue if the daily property test run surfaced any bugs
|
||||
runs-on: ubuntu-latest
|
||||
needs: property_tests
|
||||
if: ${{ github.repository == 'astral-sh/ruff' && always() && github.event_name == 'schedule' && needs.property_tests.result == 'failure' }}
|
||||
permissions:
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
await github.rest.issues.create({
|
||||
owner: "astral-sh",
|
||||
repo: "ruff",
|
||||
title: `Daily property test run failed on ${new Date().toDateString()}`,
|
||||
body: "Run listed here: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}",
|
||||
labels: ["bug", "ty", "testing"],
|
||||
})
|
||||
8
.github/workflows/mypy_primer.yaml
vendored
8
.github/workflows/mypy_primer.yaml
vendored
@@ -36,7 +36,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install the latest version of uv
|
||||
uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2
|
||||
uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca # v6.0.1
|
||||
|
||||
- uses: Swatinem/rust-cache@9d47c6ad4b02e050fd481d890b2ea34778fd09d6 # v2.7.8
|
||||
with:
|
||||
@@ -50,6 +50,10 @@ jobs:
|
||||
run: |
|
||||
cd ruff
|
||||
|
||||
echo "Enabling mypy primer specific configuration overloads (see .github/mypy-primer-ty.toml)"
|
||||
mkdir -p ~/.config/ty
|
||||
cp .github/mypy-primer-ty.toml ~/.config/ty/ty.toml
|
||||
|
||||
PRIMER_SELECTOR="$(paste -s -d'|' crates/ty_python_semantic/resources/primer/good.txt)"
|
||||
|
||||
echo "new commit"
|
||||
@@ -65,7 +69,7 @@ jobs:
|
||||
echo "Project selector: $PRIMER_SELECTOR"
|
||||
# Allow the exit code to be 0 or 1, only fail for actual mypy_primer crashes/bugs
|
||||
uvx \
|
||||
--from="git+https://github.com/hauntsaninja/mypy_primer@4b15cf3b07db69db67bbfaebfffb2a8a28040933" \
|
||||
--from="git+https://github.com/hauntsaninja/mypy_primer@01a7ca325f674433c58e02416a867178d1571128" \
|
||||
mypy_primer \
|
||||
--repo ruff \
|
||||
--type-checker ty \
|
||||
|
||||
2
.github/workflows/mypy_primer_comment.yaml
vendored
2
.github/workflows/mypy_primer_comment.yaml
vendored
@@ -79,7 +79,7 @@ jobs:
|
||||
echo 'EOF' >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Find existing comment
|
||||
uses: peter-evans/find-comment@3eae4d37986fb5a8592848f6a574fdf654e61f9e # v3
|
||||
uses: peter-evans/find-comment@3eae4d37986fb5a8592848f6a574fdf654e61f9e # v3.1.0
|
||||
if: steps.generate-comment.outcome == 'success'
|
||||
id: find-comment
|
||||
with:
|
||||
|
||||
2
.github/workflows/pr-comment.yaml
vendored
2
.github/workflows/pr-comment.yaml
vendored
@@ -70,7 +70,7 @@ jobs:
|
||||
echo 'EOF' >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Find existing comment
|
||||
uses: peter-evans/find-comment@3eae4d37986fb5a8592848f6a574fdf654e61f9e # v3
|
||||
uses: peter-evans/find-comment@3eae4d37986fb5a8592848f6a574fdf654e61f9e # v3.1.0
|
||||
if: steps.generate-comment.outcome == 'success'
|
||||
id: find-comment
|
||||
with:
|
||||
|
||||
2
.github/workflows/publish-pypi.yml
vendored
2
.github/workflows/publish-pypi.yml
vendored
@@ -22,7 +22,7 @@ jobs:
|
||||
id-token: write
|
||||
steps:
|
||||
- name: "Install uv"
|
||||
uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2
|
||||
uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca # v6.0.1
|
||||
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
pattern: wheels-*
|
||||
|
||||
@@ -29,3 +29,7 @@ MD024:
|
||||
#
|
||||
# Ref: https://github.com/astral-sh/ruff/pull/15011#issuecomment-2544790854
|
||||
MD046: false
|
||||
|
||||
# Link text should be descriptive
|
||||
# Disallows link text like *here* which is annoying.
|
||||
MD059: false
|
||||
|
||||
@@ -5,6 +5,7 @@ exclude: |
|
||||
.github/workflows/release.yml|
|
||||
crates/ty_vendored/vendor/.*|
|
||||
crates/ty_project/resources/.*|
|
||||
crates/ty/docs/(configuration|rules|cli).md|
|
||||
crates/ruff_benchmark/resources/.*|
|
||||
crates/ruff_linter/resources/.*|
|
||||
crates/ruff_linter/src/rules/.*/snapshots/.*|
|
||||
@@ -42,7 +43,7 @@ repos:
|
||||
)$
|
||||
|
||||
- repo: https://github.com/igorshubovych/markdownlint-cli
|
||||
rev: v0.44.0
|
||||
rev: v0.45.0
|
||||
hooks:
|
||||
- id: markdownlint-fix
|
||||
exclude: |
|
||||
@@ -79,7 +80,7 @@ repos:
|
||||
pass_filenames: false # This makes it a lot faster
|
||||
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.11.8
|
||||
rev: v0.11.10
|
||||
hooks:
|
||||
- id: ruff-format
|
||||
- id: ruff
|
||||
@@ -97,7 +98,7 @@ repos:
|
||||
# zizmor detects security vulnerabilities in GitHub Actions workflows.
|
||||
# Additional configuration for the tool is found in `.github/zizmor.yml`
|
||||
- repo: https://github.com/woodruffw/zizmor-pre-commit
|
||||
rev: v1.6.0
|
||||
rev: v1.7.0
|
||||
hooks:
|
||||
- id: zizmor
|
||||
|
||||
|
||||
72
CHANGELOG.md
72
CHANGELOG.md
@@ -1,5 +1,77 @@
|
||||
# Changelog
|
||||
|
||||
## 0.11.10
|
||||
|
||||
### Preview features
|
||||
|
||||
- \[`ruff`\] Implement a recursive check for `RUF060` ([#17976](https://github.com/astral-sh/ruff/pull/17976))
|
||||
- \[`airflow`\] Enable autofixes for `AIR301` and `AIR311` ([#17941](https://github.com/astral-sh/ruff/pull/17941))
|
||||
- \[`airflow`\] Apply try catch guard to all `AIR3` rules ([#17887](https://github.com/astral-sh/ruff/pull/17887))
|
||||
- \[`airflow`\] Extend `AIR311` rules ([#17913](https://github.com/astral-sh/ruff/pull/17913))
|
||||
|
||||
### Bug fixes
|
||||
|
||||
- \[`flake8-bugbear`\] Ignore `B028` if `skip_file_prefixes` is present ([#18047](https://github.com/astral-sh/ruff/pull/18047))
|
||||
- \[`flake8-pie`\] Mark autofix for `PIE804` as unsafe if the dictionary contains comments ([#18046](https://github.com/astral-sh/ruff/pull/18046))
|
||||
- \[`flake8-simplify`\] Correct behavior for `str.split`/`rsplit` with `maxsplit=0` (`SIM905`) ([#18075](https://github.com/astral-sh/ruff/pull/18075))
|
||||
- \[`flake8-simplify`\] Fix `SIM905` autofix for `rsplit` creating a reversed list literal ([#18045](https://github.com/astral-sh/ruff/pull/18045))
|
||||
- \[`flake8-use-pathlib`\] Suppress diagnostics for all `os.*` functions that have the `dir_fd` parameter (`PTH`) ([#17968](https://github.com/astral-sh/ruff/pull/17968))
|
||||
- \[`refurb`\] Mark autofix as safe only for number literals (`FURB116`) ([#17692](https://github.com/astral-sh/ruff/pull/17692))
|
||||
|
||||
### Rule changes
|
||||
|
||||
- \[`flake8-bandit`\] Skip `S608` for expressionless f-strings ([#17999](https://github.com/astral-sh/ruff/pull/17999))
|
||||
- \[`flake8-pytest-style`\] Don't recommend `usefixtures` for `parametrize` values (`PT019`) ([#17650](https://github.com/astral-sh/ruff/pull/17650))
|
||||
- \[`pyupgrade`\] Add `resource.error` as deprecated alias of `OSError` (`UP024`) ([#17933](https://github.com/astral-sh/ruff/pull/17933))
|
||||
|
||||
### CLI
|
||||
|
||||
- Disable jemalloc on Android ([#18033](https://github.com/astral-sh/ruff/pull/18033))
|
||||
|
||||
### Documentation
|
||||
|
||||
- Update Neovim setup docs ([#18108](https://github.com/astral-sh/ruff/pull/18108))
|
||||
- \[`flake8-simplify`\] Add fix safety section (`SIM103`) ([#18086](https://github.com/astral-sh/ruff/pull/18086))
|
||||
- \[`flake8-simplify`\] Add fix safety section (`SIM112`) ([#18099](https://github.com/astral-sh/ruff/pull/18099))
|
||||
- \[`pylint`\] Add fix safety section (`PLC0414`) ([#17802](https://github.com/astral-sh/ruff/pull/17802))
|
||||
- \[`pylint`\] Add fix safety section (`PLE4703`) ([#17824](https://github.com/astral-sh/ruff/pull/17824))
|
||||
- \[`pylint`\] Add fix safety section (`PLW1514`) ([#17932](https://github.com/astral-sh/ruff/pull/17932))
|
||||
- \[`pylint`\] Add fix safety section (`PLW3301`) ([#17878](https://github.com/astral-sh/ruff/pull/17878))
|
||||
- \[`ruff`\] Add fix safety section (`RUF007`) ([#17755](https://github.com/astral-sh/ruff/pull/17755))
|
||||
- \[`ruff`\] Add fix safety section (`RUF033`) ([#17760](https://github.com/astral-sh/ruff/pull/17760))
|
||||
|
||||
## 0.11.9
|
||||
|
||||
### Preview features
|
||||
|
||||
- Default to latest supported Python version for version-related syntax errors ([#17529](https://github.com/astral-sh/ruff/pull/17529))
|
||||
- Implement deferred annotations for Python 3.14 ([#17658](https://github.com/astral-sh/ruff/pull/17658))
|
||||
- \[`airflow`\] Fix `SQLTableCheckOperator` typo (`AIR302`) ([#17946](https://github.com/astral-sh/ruff/pull/17946))
|
||||
- \[`airflow`\] Remove `airflow.utils.dag_parsing_context.get_parsing_context` (`AIR301`) ([#17852](https://github.com/astral-sh/ruff/pull/17852))
|
||||
- \[`airflow`\] Skip attribute check in try catch block (`AIR301`) ([#17790](https://github.com/astral-sh/ruff/pull/17790))
|
||||
- \[`flake8-bandit`\] Mark tuples of string literals as trusted input in `S603` ([#17801](https://github.com/astral-sh/ruff/pull/17801))
|
||||
- \[`isort`\] Check full module path against project root(s) when categorizing first-party imports ([#16565](https://github.com/astral-sh/ruff/pull/16565))
|
||||
- \[`ruff`\] Add new rule `in-empty-collection` (`RUF060`) ([#16480](https://github.com/astral-sh/ruff/pull/16480))
|
||||
|
||||
### Bug fixes
|
||||
|
||||
- Fix missing `combine` call for `lint.typing-extensions` setting ([#17823](https://github.com/astral-sh/ruff/pull/17823))
|
||||
- \[`flake8-async`\] Fix module name in `ASYNC110`, `ASYNC115`, and `ASYNC116` fixes ([#17774](https://github.com/astral-sh/ruff/pull/17774))
|
||||
- \[`pyupgrade`\] Add spaces between tokens as necessary to avoid syntax errors in `UP018` autofix ([#17648](https://github.com/astral-sh/ruff/pull/17648))
|
||||
- \[`refurb`\] Fix false positive for float and complex numbers in `FURB116` ([#17661](https://github.com/astral-sh/ruff/pull/17661))
|
||||
- [parser] Flag single unparenthesized generator expr with trailing comma in arguments. ([#17893](https://github.com/astral-sh/ruff/pull/17893))
|
||||
|
||||
### Documentation
|
||||
|
||||
- Add instructions on how to upgrade to a newer Rust version ([#17928](https://github.com/astral-sh/ruff/pull/17928))
|
||||
- Update code of conduct email address ([#17875](https://github.com/astral-sh/ruff/pull/17875))
|
||||
- Add fix safety sections to `PLC2801`, `PLR1722`, and `RUF013` ([#17825](https://github.com/astral-sh/ruff/pull/17825), [#17826](https://github.com/astral-sh/ruff/pull/17826), [#17759](https://github.com/astral-sh/ruff/pull/17759))
|
||||
- Add link to `check-typed-exception` from `S110` and `S112` ([#17786](https://github.com/astral-sh/ruff/pull/17786))
|
||||
|
||||
### Other changes
|
||||
|
||||
- Allow passing a virtual environment to `ruff analyze graph` ([#17743](https://github.com/astral-sh/ruff/pull/17743))
|
||||
|
||||
## 0.11.8
|
||||
|
||||
### Preview features
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
|
||||
Welcome! We're happy to have you here. Thank you in advance for your contribution to Ruff.
|
||||
|
||||
> [!NOTE]
|
||||
>
|
||||
> This guide is for Ruff. If you're looking to contribute to ty, please see [the ty contributing
|
||||
> guide](https://github.com/astral-sh/ruff/blob/main/crates/ty/CONTRIBUTING.md).
|
||||
|
||||
## The Basics
|
||||
|
||||
Ruff welcomes contributions in the form of pull requests.
|
||||
@@ -406,7 +411,7 @@ cargo install hyperfine
|
||||
To benchmark the release build:
|
||||
|
||||
```shell
|
||||
cargo build --release && hyperfine --warmup 10 \
|
||||
cargo build --release --bin ruff && hyperfine --warmup 10 \
|
||||
"./target/release/ruff check ./crates/ruff_linter/resources/test/cpython/ --no-cache -e" \
|
||||
"./target/release/ruff check ./crates/ruff_linter/resources/test/cpython/ -e"
|
||||
|
||||
@@ -605,8 +610,7 @@ Then convert the recorded profile
|
||||
perf script -F +pid > /tmp/test.perf
|
||||
```
|
||||
|
||||
You can now view the converted file with [firefox profiler](https://profiler.firefox.com/), with a
|
||||
more in-depth guide [here](https://profiler.firefox.com/docs/#/./guide-perf-profiling)
|
||||
You can now view the converted file with [firefox profiler](https://profiler.firefox.com/). To learn more about Firefox profiler, read the [Firefox profiler profiling-guide](https://profiler.firefox.com/docs/#/./guide-perf-profiling).
|
||||
|
||||
An alternative is to convert the perf data to `flamegraph.svg` using
|
||||
[flamegraph](https://github.com/flamegraph-rs/flamegraph) (`cargo install flamegraph`):
|
||||
|
||||
833
Cargo.lock
generated
833
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
26
Cargo.toml
26
Cargo.toml
@@ -3,8 +3,9 @@ members = ["crates/*"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
edition = "2021"
|
||||
rust-version = "1.84"
|
||||
# Please update rustfmt.toml when bumping the Rust edition
|
||||
edition = "2024"
|
||||
rust-version = "1.85"
|
||||
homepage = "https://docs.astral.sh/ruff"
|
||||
documentation = "https://docs.astral.sh/ruff"
|
||||
repository = "https://github.com/astral-sh/ruff"
|
||||
@@ -23,6 +24,7 @@ ruff_index = { path = "crates/ruff_index" }
|
||||
ruff_linter = { path = "crates/ruff_linter" }
|
||||
ruff_macros = { path = "crates/ruff_macros" }
|
||||
ruff_notebook = { path = "crates/ruff_notebook" }
|
||||
ruff_options_metadata = { path = "crates/ruff_options_metadata" }
|
||||
ruff_python_ast = { path = "crates/ruff_python_ast" }
|
||||
ruff_python_codegen = { path = "crates/ruff_python_codegen" }
|
||||
ruff_python_formatter = { path = "crates/ruff_python_formatter" }
|
||||
@@ -37,6 +39,7 @@ ruff_source_file = { path = "crates/ruff_source_file" }
|
||||
ruff_text_size = { path = "crates/ruff_text_size" }
|
||||
ruff_workspace = { path = "crates/ruff_workspace" }
|
||||
|
||||
ty = { path = "crates/ty" }
|
||||
ty_ide = { path = "crates/ty_ide" }
|
||||
ty_project = { path = "crates/ty_project", default-features = false }
|
||||
ty_python_semantic = { path = "crates/ty_python_semantic" }
|
||||
@@ -50,7 +53,7 @@ anstyle = { version = "1.0.10" }
|
||||
anyhow = { version = "1.0.80" }
|
||||
assert_fs = { version = "1.1.0" }
|
||||
argfile = { version = "0.2.0" }
|
||||
bincode = { version = "1.3.3" }
|
||||
bincode = { version = "2.0.0" }
|
||||
bitflags = { version = "2.5.0" }
|
||||
bstr = { version = "1.9.1" }
|
||||
cachedir = { version = "0.3.1" }
|
||||
@@ -64,7 +67,7 @@ console_error_panic_hook = { version = "0.1.7" }
|
||||
console_log = { version = "1.0.0" }
|
||||
countme = { version = "3.0.1" }
|
||||
compact_str = "0.9.0"
|
||||
criterion = { version = "0.5.1", default-features = false }
|
||||
criterion = { version = "0.6.0", default-features = false }
|
||||
crossbeam = { version = "0.8.4" }
|
||||
dashmap = { version = "6.0.1" }
|
||||
dir-test = { version = "0.4.0" }
|
||||
@@ -83,6 +86,7 @@ hashbrown = { version = "0.15.0", default-features = false, features = [
|
||||
"equivalent",
|
||||
"inline-more",
|
||||
] }
|
||||
heck = "0.5.0"
|
||||
ignore = { version = "0.4.22" }
|
||||
imara-diff = { version = "0.1.5" }
|
||||
imperative = { version = "1.0.4" }
|
||||
@@ -96,7 +100,7 @@ is-wsl = { version = "0.4.0" }
|
||||
itertools = { version = "0.14.0" }
|
||||
jiff = { version = "0.2.0" }
|
||||
js-sys = { version = "0.3.69" }
|
||||
jod-thread = { version = "0.1.2" }
|
||||
jod-thread = { version = "1.0.0" }
|
||||
libc = { version = "0.2.153" }
|
||||
libcst = { version = "1.1.0", default-features = false }
|
||||
log = { version = "0.4.17" }
|
||||
@@ -123,8 +127,9 @@ rand = { version = "0.9.0" }
|
||||
rayon = { version = "1.10.0" }
|
||||
regex = { version = "1.10.2" }
|
||||
rustc-hash = { version = "2.0.0" }
|
||||
rustc-stable-hash = { version = "0.1.2" }
|
||||
# When updating salsa, make sure to also update the revision in `fuzz/Cargo.toml`
|
||||
salsa = { git = "https://github.com/salsa-rs/salsa.git", rev = "f78a641d2086695ac0ef96cbe915bf80b5a690f2" }
|
||||
salsa = { git = "https://github.com/salsa-rs/salsa.git", rev = "7edce6e248f35c8114b4b021cdb474a3fb2813b3" }
|
||||
schemars = { version = "0.8.16" }
|
||||
seahash = { version = "4.1.0" }
|
||||
serde = { version = "1.0.197", features = ["derive"] }
|
||||
@@ -159,8 +164,9 @@ tracing-log = { version = "0.2.0" }
|
||||
tracing-subscriber = { version = "0.3.18", default-features = false, features = [
|
||||
"env-filter",
|
||||
"fmt",
|
||||
"ansi",
|
||||
"smallvec"
|
||||
] }
|
||||
tracing-tree = { version = "0.4.0" }
|
||||
tryfn = { version = "0.2.1" }
|
||||
typed-arena = { version = "2.0.2" }
|
||||
unic-ucd-category = { version = "0.9" }
|
||||
@@ -182,7 +188,7 @@ wild = { version = "2" }
|
||||
zip = { version = "0.6.6", default-features = false }
|
||||
|
||||
[workspace.metadata.cargo-shear]
|
||||
ignored = ["getrandom"]
|
||||
ignored = ["getrandom", "ruff_options_metadata"]
|
||||
|
||||
|
||||
[workspace.lints.rust]
|
||||
@@ -210,6 +216,7 @@ similar_names = "allow"
|
||||
single_match_else = "allow"
|
||||
too_many_lines = "allow"
|
||||
needless_continue = "allow" # An explicit continue can be more readable, especially if the alternative is an empty block.
|
||||
unnecessary_debug_formatting = "allow" # too many instances, the display also doesn't quote the path which is often desired in logs where we use them the most often.
|
||||
# Without the hashes we run into a `rustfmt` bug in some snapshot tests, see #13250
|
||||
needless_raw_string_hashes = "allow"
|
||||
# Disallowed restriction lints
|
||||
@@ -254,6 +261,9 @@ opt-level = 3
|
||||
[profile.dev.package.similar]
|
||||
opt-level = 3
|
||||
|
||||
[profile.dev.package.salsa]
|
||||
opt-level = 3
|
||||
|
||||
# Reduce complexity of a parser function that would trigger a locals limit in a wasm tool.
|
||||
# https://github.com/bytecodealliance/wasm-tools/blob/b5c3d98e40590512a3b12470ef358d5c7b983b15/crates/wasmparser/src/limits.rs#L29
|
||||
[profile.dev.package.ruff_python_parser]
|
||||
|
||||
@@ -149,8 +149,8 @@ curl -LsSf https://astral.sh/ruff/install.sh | sh
|
||||
powershell -c "irm https://astral.sh/ruff/install.ps1 | iex"
|
||||
|
||||
# For a specific version.
|
||||
curl -LsSf https://astral.sh/ruff/0.11.8/install.sh | sh
|
||||
powershell -c "irm https://astral.sh/ruff/0.11.8/install.ps1 | iex"
|
||||
curl -LsSf https://astral.sh/ruff/0.11.10/install.sh | sh
|
||||
powershell -c "irm https://astral.sh/ruff/0.11.10/install.ps1 | iex"
|
||||
```
|
||||
|
||||
You can also install Ruff via [Homebrew](https://formulae.brew.sh/formula/ruff), [Conda](https://anaconda.org/conda-forge/ruff),
|
||||
@@ -183,7 +183,7 @@ Ruff can also be used as a [pre-commit](https://pre-commit.com/) hook via [`ruff
|
||||
```yaml
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
# Ruff version.
|
||||
rev: v0.11.8
|
||||
rev: v0.11.10
|
||||
hooks:
|
||||
# Run the linter.
|
||||
- id: ruff
|
||||
@@ -255,7 +255,7 @@ indent-width = 4
|
||||
target-version = "py39"
|
||||
|
||||
[lint]
|
||||
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
|
||||
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
|
||||
select = ["E4", "E7", "E9", "F"]
|
||||
ignore = []
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ruff"
|
||||
version = "0.11.8"
|
||||
version = "0.11.10"
|
||||
publish = true
|
||||
authors = { workspace = true }
|
||||
edition = { workspace = true }
|
||||
@@ -20,6 +20,7 @@ ruff_graph = { workspace = true, features = ["serde", "clap"] }
|
||||
ruff_linter = { workspace = true, features = ["clap"] }
|
||||
ruff_macros = { workspace = true }
|
||||
ruff_notebook = { workspace = true }
|
||||
ruff_options_metadata = { workspace = true, features = ["serde"] }
|
||||
ruff_python_ast = { workspace = true }
|
||||
ruff_python_formatter = { workspace = true }
|
||||
ruff_python_parser = { workspace = true }
|
||||
@@ -30,7 +31,7 @@ ruff_workspace = { workspace = true }
|
||||
|
||||
anyhow = { workspace = true }
|
||||
argfile = { workspace = true }
|
||||
bincode = { workspace = true }
|
||||
bincode = { workspace = true, features = ["serde"] }
|
||||
bitflags = { workspace = true }
|
||||
cachedir = { workspace = true }
|
||||
clap = { workspace = true, features = ["derive", "env", "wrap_help"] }
|
||||
@@ -83,7 +84,7 @@ dist = true
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
mimalloc = { workspace = true }
|
||||
|
||||
[target.'cfg(all(not(target_os = "windows"), not(target_os = "openbsd"), not(target_os = "aix"), any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "powerpc64")))'.dependencies]
|
||||
[target.'cfg(all(not(target_os = "windows"), not(target_os = "openbsd"), not(target_os = "aix"), not(target_os = "android"), any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "powerpc64")))'.dependencies]
|
||||
tikv-jemallocator = { workspace = true }
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::sync::Arc;
|
||||
use crate::commands::completions::config::{OptionString, OptionStringParser};
|
||||
use anyhow::bail;
|
||||
use clap::builder::{TypedValueParser, ValueParserFactory};
|
||||
use clap::{command, Parser, Subcommand};
|
||||
use clap::{Parser, Subcommand, command};
|
||||
use colored::Colorize;
|
||||
use itertools::Itertools;
|
||||
use path_absolutize::path_dedot;
|
||||
@@ -22,12 +22,12 @@ use ruff_linter::settings::types::{
|
||||
PythonVersion, UnsafeFixes,
|
||||
};
|
||||
use ruff_linter::{RuleParser, RuleSelector, RuleSelectorParser};
|
||||
use ruff_options_metadata::{OptionEntry, OptionsMetadata};
|
||||
use ruff_python_ast as ast;
|
||||
use ruff_source_file::{LineIndex, OneIndexed, PositionEncoding};
|
||||
use ruff_text_size::TextRange;
|
||||
use ruff_workspace::configuration::{Configuration, RuleSelection};
|
||||
use ruff_workspace::options::{Options, PycodestyleOptions};
|
||||
use ruff_workspace::options_base::{OptionEntry, OptionsMetadata};
|
||||
use ruff_workspace::resolver::ConfigurationTransformer;
|
||||
use rustc_hash::FxHashMap;
|
||||
use toml;
|
||||
@@ -1126,10 +1126,10 @@ impl std::fmt::Display for FormatRangeParseError {
|
||||
write!(
|
||||
f,
|
||||
"the start position '{start_invalid}' is greater than the end position '{end_invalid}'.\n {tip} Try switching start and end: '{end}-{start}'",
|
||||
start_invalid=start.to_string().bold().yellow(),
|
||||
end_invalid=end.to_string().bold().yellow(),
|
||||
start=start.to_string().green().bold(),
|
||||
end=end.to_string().green().bold()
|
||||
start_invalid = start.to_string().bold().yellow(),
|
||||
end_invalid = end.to_string().bold().yellow(),
|
||||
start = start.to_string().green().bold(),
|
||||
end = end.to_string().green().bold()
|
||||
)
|
||||
}
|
||||
FormatRangeParseError::InvalidStart(inner) => inner.write(f, true),
|
||||
@@ -1230,30 +1230,36 @@ impl LineColumnParseError {
|
||||
|
||||
match self {
|
||||
LineColumnParseError::ColumnParseError(inner) => {
|
||||
write!(f, "the {range}s column is not a valid number ({inner})'\n {tip} The format is 'line:column'.")
|
||||
write!(
|
||||
f,
|
||||
"the {range}s column is not a valid number ({inner})'\n {tip} The format is 'line:column'."
|
||||
)
|
||||
}
|
||||
LineColumnParseError::LineParseError(inner) => {
|
||||
write!(f, "the {range} line is not a valid number ({inner})\n {tip} The format is 'line:column'.")
|
||||
write!(
|
||||
f,
|
||||
"the {range} line is not a valid number ({inner})\n {tip} The format is 'line:column'."
|
||||
)
|
||||
}
|
||||
LineColumnParseError::ZeroColumnIndex { line } => {
|
||||
write!(
|
||||
f,
|
||||
"the {range} column is 0, but it should be 1 or greater.\n {tip} The column numbers start at 1.\n {tip} Try {suggestion} instead.",
|
||||
suggestion=format!("{line}:1").green().bold()
|
||||
suggestion = format!("{line}:1").green().bold()
|
||||
)
|
||||
}
|
||||
LineColumnParseError::ZeroLineIndex { column } => {
|
||||
write!(
|
||||
f,
|
||||
"the {range} line is 0, but it should be 1 or greater.\n {tip} The line numbers start at 1.\n {tip} Try {suggestion} instead.",
|
||||
suggestion=format!("1:{column}").green().bold()
|
||||
suggestion = format!("1:{column}").green().bold()
|
||||
)
|
||||
}
|
||||
LineColumnParseError::ZeroLineAndColumnIndex => {
|
||||
write!(
|
||||
f,
|
||||
"the {range} line and column are both 0, but they should be 1 or greater.\n {tip} The line and column numbers start at 1.\n {tip} Try {suggestion} instead.",
|
||||
suggestion="1:1".to_string().green().bold()
|
||||
suggestion = "1:1".to_string().green().bold()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@ use std::fs::{self, File};
|
||||
use std::hash::Hasher;
|
||||
use std::io::{self, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
@@ -13,21 +13,21 @@ use itertools::Itertools;
|
||||
use log::{debug, error};
|
||||
use rayon::iter::ParallelIterator;
|
||||
use rayon::iter::{IntoParallelIterator, ParallelBridge};
|
||||
use ruff_linter::codes::Rule;
|
||||
use rustc_hash::FxHashMap;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
use ruff_cache::{CacheKey, CacheKeyHasher};
|
||||
use ruff_diagnostics::{DiagnosticKind, Fix};
|
||||
use ruff_linter::message::{DiagnosticMessage, Message};
|
||||
use ruff_diagnostics::Fix;
|
||||
use ruff_linter::message::Message;
|
||||
use ruff_linter::package::PackageRoot;
|
||||
use ruff_linter::{warn_user, VERSION};
|
||||
use ruff_linter::{VERSION, warn_user};
|
||||
use ruff_macros::CacheKey;
|
||||
use ruff_notebook::NotebookIndex;
|
||||
use ruff_source_file::SourceFileBuilder;
|
||||
use ruff_text_size::{TextRange, TextSize};
|
||||
use ruff_workspace::resolver::Resolver;
|
||||
use ruff_text_size::{Ranged, TextRange, TextSize};
|
||||
use ruff_workspace::Settings;
|
||||
use ruff_workspace::resolver::Resolver;
|
||||
|
||||
use crate::diagnostics::Diagnostics;
|
||||
|
||||
@@ -117,13 +117,14 @@ impl Cache {
|
||||
}
|
||||
};
|
||||
|
||||
let mut package: PackageCache = match bincode::deserialize_from(BufReader::new(file)) {
|
||||
Ok(package) => package,
|
||||
Err(err) => {
|
||||
warn_user!("Failed parse cache file `{}`: {err}", path.display());
|
||||
return Cache::empty(path, package_root);
|
||||
}
|
||||
};
|
||||
let mut package: PackageCache =
|
||||
match bincode::decode_from_reader(BufReader::new(file), bincode::config::standard()) {
|
||||
Ok(package) => package,
|
||||
Err(err) => {
|
||||
warn_user!("Failed parse cache file `{}`: {err}", path.display());
|
||||
return Cache::empty(path, package_root);
|
||||
}
|
||||
};
|
||||
|
||||
// Sanity check.
|
||||
if package.package_root != package_root {
|
||||
@@ -175,8 +176,8 @@ impl Cache {
|
||||
|
||||
// Serialize to in-memory buffer because hyperfine benchmark showed that it's faster than
|
||||
// using a `BufWriter` and our cache files are small enough that streaming isn't necessary.
|
||||
let serialized =
|
||||
bincode::serialize(&self.package).context("Failed to serialize cache data")?;
|
||||
let serialized = bincode::encode_to_vec(&self.package, bincode::config::standard())
|
||||
.context("Failed to serialize cache data")?;
|
||||
temp_file
|
||||
.write_all(&serialized)
|
||||
.context("Failed to write serialized cache to temporary file.")?;
|
||||
@@ -311,7 +312,7 @@ impl Cache {
|
||||
}
|
||||
|
||||
/// On disk representation of a cache of a package.
|
||||
#[derive(Deserialize, Debug, Serialize)]
|
||||
#[derive(bincode::Encode, Debug, bincode::Decode)]
|
||||
struct PackageCache {
|
||||
/// Path to the root of the package.
|
||||
///
|
||||
@@ -323,7 +324,7 @@ struct PackageCache {
|
||||
}
|
||||
|
||||
/// On disk representation of the cache per source file.
|
||||
#[derive(Deserialize, Debug, Serialize)]
|
||||
#[derive(bincode::Decode, Debug, bincode::Encode)]
|
||||
pub(crate) struct FileCache {
|
||||
/// Key that determines if the cached item is still valid.
|
||||
key: u64,
|
||||
@@ -347,14 +348,16 @@ impl FileCache {
|
||||
lint.messages
|
||||
.iter()
|
||||
.map(|msg| {
|
||||
Message::Diagnostic(DiagnosticMessage {
|
||||
kind: msg.kind.clone(),
|
||||
range: msg.range,
|
||||
fix: msg.fix.clone(),
|
||||
file: file.clone(),
|
||||
noqa_offset: msg.noqa_offset,
|
||||
parent: msg.parent,
|
||||
})
|
||||
Message::diagnostic(
|
||||
msg.rule.into(),
|
||||
msg.body.clone(),
|
||||
msg.suggestion.clone(),
|
||||
msg.range,
|
||||
msg.fix.clone(),
|
||||
msg.parent,
|
||||
file.clone(),
|
||||
msg.noqa_offset,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
@@ -368,7 +371,7 @@ impl FileCache {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize)]
|
||||
#[derive(Debug, Default, bincode::Decode, bincode::Encode)]
|
||||
struct FileCacheData {
|
||||
lint: Option<LintCacheData>,
|
||||
formatted: bool,
|
||||
@@ -406,7 +409,7 @@ pub(crate) fn init(path: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Serialize, PartialEq)]
|
||||
#[derive(bincode::Decode, Debug, bincode::Encode, PartialEq)]
|
||||
pub(crate) struct LintCacheData {
|
||||
/// Imports made.
|
||||
// pub(super) imports: ImportMap,
|
||||
@@ -419,6 +422,7 @@ pub(crate) struct LintCacheData {
|
||||
/// This will be empty if `messages` is empty.
|
||||
pub(super) source: String,
|
||||
/// Notebook index if this file is a Jupyter Notebook.
|
||||
#[bincode(with_serde)]
|
||||
pub(super) notebook_index: Option<NotebookIndex>,
|
||||
}
|
||||
|
||||
@@ -435,20 +439,22 @@ impl LintCacheData {
|
||||
|
||||
let messages = messages
|
||||
.iter()
|
||||
.filter_map(|message| message.as_diagnostic_message())
|
||||
.map(|msg| {
|
||||
.filter_map(|msg| msg.to_rule().map(|rule| (rule, msg)))
|
||||
.map(|(rule, msg)| {
|
||||
// Make sure that all message use the same source file.
|
||||
assert_eq!(
|
||||
&msg.file,
|
||||
msg.source_file(),
|
||||
messages.first().unwrap().source_file(),
|
||||
"message uses a different source file"
|
||||
);
|
||||
CacheMessage {
|
||||
kind: msg.kind.clone(),
|
||||
range: msg.range,
|
||||
rule,
|
||||
body: msg.body().to_string(),
|
||||
suggestion: msg.suggestion().map(ToString::to_string),
|
||||
range: msg.range(),
|
||||
parent: msg.parent,
|
||||
fix: msg.fix.clone(),
|
||||
noqa_offset: msg.noqa_offset,
|
||||
fix: msg.fix().cloned(),
|
||||
noqa_offset: msg.noqa_offset(),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -462,14 +468,24 @@ impl LintCacheData {
|
||||
}
|
||||
|
||||
/// On disk representation of a diagnostic message.
|
||||
#[derive(Deserialize, Debug, Serialize, PartialEq)]
|
||||
#[derive(bincode::Decode, Debug, bincode::Encode, PartialEq)]
|
||||
pub(super) struct CacheMessage {
|
||||
kind: DiagnosticKind,
|
||||
/// The rule for the cached diagnostic.
|
||||
#[bincode(with_serde)]
|
||||
rule: Rule,
|
||||
/// The message body to display to the user, to explain the diagnostic.
|
||||
body: String,
|
||||
/// The message to display to the user, to explain the suggested fix.
|
||||
suggestion: Option<String>,
|
||||
/// Range into the message's [`FileCache::source`].
|
||||
#[bincode(with_serde)]
|
||||
range: TextRange,
|
||||
#[bincode(with_serde)]
|
||||
parent: Option<TextSize>,
|
||||
#[bincode(with_serde)]
|
||||
fix: Option<Fix>,
|
||||
noqa_offset: TextSize,
|
||||
#[bincode(with_serde)]
|
||||
noqa_offset: Option<TextSize>,
|
||||
}
|
||||
|
||||
pub(crate) trait PackageCaches {
|
||||
@@ -587,7 +603,7 @@ mod tests {
|
||||
use std::time::SystemTime;
|
||||
|
||||
use anyhow::Result;
|
||||
use filetime::{set_file_mtime, FileTime};
|
||||
use filetime::{FileTime, set_file_mtime};
|
||||
use itertools::Itertools;
|
||||
use ruff_linter::settings::LinterSettings;
|
||||
use test_case::test_case;
|
||||
@@ -602,8 +618,8 @@ mod tests {
|
||||
|
||||
use crate::cache::{self, FileCache, FileCacheData, FileCacheKey};
|
||||
use crate::cache::{Cache, RelativePathBuf};
|
||||
use crate::commands::format::{format_path, FormatCommandError, FormatMode, FormatResult};
|
||||
use crate::diagnostics::{lint_path, Diagnostics};
|
||||
use crate::commands::format::{FormatCommandError, FormatMode, FormatResult, format_path};
|
||||
use crate::diagnostics::{Diagnostics, lint_path};
|
||||
|
||||
#[test_case("../ruff_linter/resources/test/fixtures", "ruff_tests/cache_same_results_ruff_linter"; "ruff_linter_fixtures")]
|
||||
#[test_case("../ruff_notebook/resources/test/fixtures", "ruff_tests/cache_same_results_ruff_notebook"; "ruff_notebook_fixtures")]
|
||||
|
||||
@@ -11,7 +11,7 @@ use ruff_linter::source_kind::SourceKind;
|
||||
use ruff_linter::warn_user_once;
|
||||
use ruff_python_ast::{PySourceType, SourceType};
|
||||
use ruff_workspace::resolver::{
|
||||
match_exclusion, python_files_in_path, PyprojectConfig, ResolvedFile,
|
||||
PyprojectConfig, ResolvedFile, match_exclusion, python_files_in_path,
|
||||
};
|
||||
|
||||
use crate::args::ConfigArguments;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::args::{AnalyzeGraphArgs, ConfigArguments};
|
||||
use crate::resolve::resolve;
|
||||
use crate::{resolve_default_files, ExitStatus};
|
||||
use crate::{ExitStatus, resolve_default_files};
|
||||
use anyhow::Result;
|
||||
use log::{debug, warn};
|
||||
use path_absolutize::CWD;
|
||||
@@ -9,7 +9,7 @@ use ruff_graph::{Direction, ImportMap, ModuleDb, ModuleImports};
|
||||
use ruff_linter::package::PackageRoot;
|
||||
use ruff_linter::{warn_user, warn_user_once};
|
||||
use ruff_python_ast::{PySourceType, SourceType};
|
||||
use ruff_workspace::resolver::{match_exclusion, python_files_in_path, ResolvedFile};
|
||||
use ruff_workspace::resolver::{ResolvedFile, match_exclusion, python_files_in_path};
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -17,12 +17,12 @@ use ruff_linter::message::Message;
|
||||
use ruff_linter::package::PackageRoot;
|
||||
use ruff_linter::registry::Rule;
|
||||
use ruff_linter::settings::types::UnsafeFixes;
|
||||
use ruff_linter::settings::{flags, LinterSettings};
|
||||
use ruff_linter::{fs, warn_user_once, IOError};
|
||||
use ruff_linter::settings::{LinterSettings, flags};
|
||||
use ruff_linter::{IOError, fs, warn_user_once};
|
||||
use ruff_source_file::SourceFileBuilder;
|
||||
use ruff_text_size::{TextRange, TextSize};
|
||||
use ruff_text_size::TextRange;
|
||||
use ruff_workspace::resolver::{
|
||||
match_exclusion, python_files_in_path, PyprojectConfig, ResolvedFile,
|
||||
PyprojectConfig, ResolvedFile, match_exclusion, python_files_in_path,
|
||||
};
|
||||
|
||||
use crate::args::ConfigArguments;
|
||||
@@ -133,7 +133,7 @@ pub(crate) fn check(
|
||||
vec![Message::from_diagnostic(
|
||||
Diagnostic::new(IOError { message }, TextRange::default()),
|
||||
dummy,
|
||||
TextSize::default(),
|
||||
None,
|
||||
)],
|
||||
FxHashMap::default(),
|
||||
)
|
||||
@@ -228,9 +228,9 @@ mod test {
|
||||
use ruff_linter::message::{Emitter, EmitterContext, TextEmitter};
|
||||
use ruff_linter::registry::Rule;
|
||||
use ruff_linter::settings::types::UnsafeFixes;
|
||||
use ruff_linter::settings::{flags, LinterSettings};
|
||||
use ruff_workspace::resolver::{PyprojectConfig, PyprojectDiscoveryStrategy};
|
||||
use ruff_linter::settings::{LinterSettings, flags};
|
||||
use ruff_workspace::Settings;
|
||||
use ruff_workspace::resolver::{PyprojectConfig, PyprojectDiscoveryStrategy};
|
||||
|
||||
use crate::args::ConfigArguments;
|
||||
|
||||
|
||||
@@ -4,10 +4,10 @@ use anyhow::Result;
|
||||
use ruff_linter::package::PackageRoot;
|
||||
use ruff_linter::packaging;
|
||||
use ruff_linter::settings::flags;
|
||||
use ruff_workspace::resolver::{match_exclusion, python_file_at_path, PyprojectConfig, Resolver};
|
||||
use ruff_workspace::resolver::{PyprojectConfig, Resolver, match_exclusion, python_file_at_path};
|
||||
|
||||
use crate::args::ConfigArguments;
|
||||
use crate::diagnostics::{lint_stdin, Diagnostics};
|
||||
use crate::diagnostics::{Diagnostics, lint_stdin};
|
||||
use crate::stdin::{parrot_stdin, read_from_stdin};
|
||||
|
||||
/// Run the linter over a single file, read from `stdin`.
|
||||
|
||||
@@ -2,10 +2,8 @@ use clap::builder::{PossibleValue, TypedValueParser, ValueParserFactory};
|
||||
use itertools::Itertools;
|
||||
use std::str::FromStr;
|
||||
|
||||
use ruff_workspace::{
|
||||
options::Options,
|
||||
options_base::{OptionField, OptionSet, OptionsMetadata, Visit},
|
||||
};
|
||||
use ruff_options_metadata::{OptionField, OptionSet, OptionsMetadata, Visit};
|
||||
use ruff_workspace::options::Options;
|
||||
|
||||
#[derive(Default)]
|
||||
struct CollectOptionsVisitor {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use anyhow::{anyhow, Result};
|
||||
use anyhow::{Result, anyhow};
|
||||
|
||||
use crate::args::HelpFormat;
|
||||
|
||||
use ruff_options_metadata::OptionsMetadata;
|
||||
use ruff_workspace::options::Options;
|
||||
use ruff_workspace::options_base::OptionsMetadata;
|
||||
|
||||
#[expect(clippy::print_stdout)]
|
||||
pub(crate) fn config(key: Option<&str>, format: HelpFormat) -> Result<()> {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::io::{stderr, stdout, Write};
|
||||
use std::io::{Write, stderr, stdout};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
@@ -16,7 +16,7 @@ use rustc_hash::FxHashSet;
|
||||
use thiserror::Error;
|
||||
use tracing::debug;
|
||||
|
||||
use ruff_db::panic::{catch_unwind, PanicError};
|
||||
use ruff_db::panic::{PanicError, catch_unwind};
|
||||
use ruff_diagnostics::SourceMap;
|
||||
use ruff_linter::fs;
|
||||
use ruff_linter::logging::{DisplayParseError, LogLevel};
|
||||
@@ -26,16 +26,16 @@ use ruff_linter::rules::flake8_quotes::settings::Quote;
|
||||
use ruff_linter::source_kind::{SourceError, SourceKind};
|
||||
use ruff_linter::warn_user_once;
|
||||
use ruff_python_ast::{PySourceType, SourceType};
|
||||
use ruff_python_formatter::{format_module_source, format_range, FormatModuleError, QuoteStyle};
|
||||
use ruff_python_formatter::{FormatModuleError, QuoteStyle, format_module_source, format_range};
|
||||
use ruff_source_file::LineIndex;
|
||||
use ruff_text_size::{TextLen, TextRange, TextSize};
|
||||
use ruff_workspace::resolver::{match_exclusion, python_files_in_path, ResolvedFile, Resolver};
|
||||
use ruff_workspace::FormatterSettings;
|
||||
use ruff_workspace::resolver::{ResolvedFile, Resolver, match_exclusion, python_files_in_path};
|
||||
|
||||
use crate::args::{ConfigArguments, FormatArguments, FormatRange};
|
||||
use crate::cache::{Cache, FileCacheKey, PackageCacheMap, PackageCaches};
|
||||
use crate::resolve::resolve;
|
||||
use crate::{resolve_default_files, ExitStatus};
|
||||
use crate::{ExitStatus, resolve_default_files};
|
||||
|
||||
#[derive(Debug, Copy, Clone, is_macro::Is)]
|
||||
pub(crate) enum FormatMode {
|
||||
@@ -821,9 +821,14 @@ pub(super) fn warn_incompatible_formatter_settings(resolver: &Resolver) {
|
||||
.collect();
|
||||
rule_names.sort();
|
||||
if let [rule] = rule_names.as_slice() {
|
||||
warn_user_once!("The following rule may cause conflicts when used with the formatter: {rule}. To avoid unexpected behavior, we recommend disabling this rule, either by removing it from the `select` or `extend-select` configuration, or adding it to the `ignore` configuration.");
|
||||
warn_user_once!(
|
||||
"The following rule may cause conflicts when used with the formatter: {rule}. To avoid unexpected behavior, we recommend disabling this rule, either by removing it from the `select` or `extend-select` configuration, or adding it to the `ignore` configuration."
|
||||
);
|
||||
} else {
|
||||
warn_user_once!("The following rules may cause conflicts when used with the formatter: {}. To avoid unexpected behavior, we recommend disabling these rules, either by removing them from the `select` or `extend-select` configuration, or adding them to the `ignore` configuration.", rule_names.join(", "));
|
||||
warn_user_once!(
|
||||
"The following rules may cause conflicts when used with the formatter: {}. To avoid unexpected behavior, we recommend disabling these rules, either by removing them from the `select` or `extend-select` configuration, or adding them to the `ignore` configuration.",
|
||||
rule_names.join(", ")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -833,7 +838,9 @@ pub(super) fn warn_incompatible_formatter_settings(resolver: &Resolver) {
|
||||
if setting.linter.rules.enabled(Rule::TabIndentation)
|
||||
&& setting.formatter.indent_style.is_tab()
|
||||
{
|
||||
warn_user_once!("The `format.indent-style=\"tab\"` option is incompatible with `W191`, which lints against all uses of tabs. We recommend disabling these rules when using the formatter, which enforces a consistent indentation style. Alternatively, set the `format.indent-style` option to `\"space\"`.");
|
||||
warn_user_once!(
|
||||
"The `format.indent-style=\"tab\"` option is incompatible with `W191`, which lints against all uses of tabs. We recommend disabling these rules when using the formatter, which enforces a consistent indentation style. Alternatively, set the `format.indent-style` option to `\"space\"`."
|
||||
);
|
||||
}
|
||||
|
||||
if !setting
|
||||
@@ -846,14 +853,18 @@ pub(super) fn warn_incompatible_formatter_settings(resolver: &Resolver) {
|
||||
.enabled(Rule::MultiLineImplicitStringConcatenation)
|
||||
&& !setting.linter.flake8_implicit_str_concat.allow_multiline
|
||||
{
|
||||
warn_user_once!("The `lint.flake8-implicit-str-concat.allow-multiline = false` option is incompatible with the formatter unless `ISC001` is enabled. We recommend enabling `ISC001` or setting `allow-multiline=true`.");
|
||||
warn_user_once!(
|
||||
"The `lint.flake8-implicit-str-concat.allow-multiline = false` option is incompatible with the formatter unless `ISC001` is enabled. We recommend enabling `ISC001` or setting `allow-multiline=true`."
|
||||
);
|
||||
}
|
||||
|
||||
// Validate all rules that rely on tab styles.
|
||||
if setting.linter.rules.enabled(Rule::DocstringTabIndentation)
|
||||
&& setting.formatter.indent_style.is_tab()
|
||||
{
|
||||
warn_user_once!("The `format.indent-style=\"tab\"` option is incompatible with `D206`, with requires space-based indentation. We recommend disabling these rules when using the formatter, which enforces a consistent indentation style. Alternatively, set the `format.indent-style` option to `\"space\"`.");
|
||||
warn_user_once!(
|
||||
"The `format.indent-style=\"tab\"` option is incompatible with `D206`, with requires space-based indentation. We recommend disabling these rules when using the formatter, which enforces a consistent indentation style. Alternatively, set the `format.indent-style` option to `\"space\"`."
|
||||
);
|
||||
}
|
||||
|
||||
// Validate all rules that rely on custom indent widths.
|
||||
@@ -862,7 +873,9 @@ pub(super) fn warn_incompatible_formatter_settings(resolver: &Resolver) {
|
||||
Rule::IndentationWithInvalidMultipleComment,
|
||||
]) && setting.formatter.indent_width.value() != 4
|
||||
{
|
||||
warn_user_once!("The `format.indent-width` option with a value other than 4 is incompatible with `E111` and `E114`. We recommend disabling these rules when using the formatter, which enforces a consistent indentation width. Alternatively, set the `format.indent-width` option to `4`.");
|
||||
warn_user_once!(
|
||||
"The `format.indent-width` option with a value other than 4 is incompatible with `E111` and `E114`. We recommend disabling these rules when using the formatter, which enforces a consistent indentation width. Alternatively, set the `format.indent-width` option to `4`."
|
||||
);
|
||||
}
|
||||
|
||||
// Validate all rules that rely on quote styles.
|
||||
@@ -876,10 +889,14 @@ pub(super) fn warn_incompatible_formatter_settings(resolver: &Resolver) {
|
||||
setting.formatter.quote_style,
|
||||
) {
|
||||
(Quote::Double, QuoteStyle::Single) => {
|
||||
warn_user_once!("The `flake8-quotes.inline-quotes=\"double\"` option is incompatible with the formatter's `format.quote-style=\"single\"`. We recommend disabling `Q000` and `Q003` when using the formatter, which enforces a consistent quote style. Alternatively, set both options to either `\"single\"` or `\"double\"`.");
|
||||
warn_user_once!(
|
||||
"The `flake8-quotes.inline-quotes=\"double\"` option is incompatible with the formatter's `format.quote-style=\"single\"`. We recommend disabling `Q000` and `Q003` when using the formatter, which enforces a consistent quote style. Alternatively, set both options to either `\"single\"` or `\"double\"`."
|
||||
);
|
||||
}
|
||||
(Quote::Single, QuoteStyle::Double) => {
|
||||
warn_user_once!("The `flake8-quotes.inline-quotes=\"single\"` option is incompatible with the formatter's `format.quote-style=\"double\"`. We recommend disabling `Q000` and `Q003` when using the formatter, which enforces a consistent quote style. Alternatively, set both options to either `\"single\"` or `\"double\"`.");
|
||||
warn_user_once!(
|
||||
"The `flake8-quotes.inline-quotes=\"single\"` option is incompatible with the formatter's `format.quote-style=\"double\"`. We recommend disabling `Q000` and `Q003` when using the formatter, which enforces a consistent quote style. Alternatively, set both options to either `\"single\"` or `\"double\"`."
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -892,7 +909,9 @@ pub(super) fn warn_incompatible_formatter_settings(resolver: &Resolver) {
|
||||
QuoteStyle::Single | QuoteStyle::Double
|
||||
)
|
||||
{
|
||||
warn_user_once!("The `flake8-quotes.multiline-quotes=\"single\"` option is incompatible with the formatter. We recommend disabling `Q001` when using the formatter, which enforces double quotes for multiline strings. Alternatively, set the `flake8-quotes.multiline-quotes` option to `\"double\"`.`");
|
||||
warn_user_once!(
|
||||
"The `flake8-quotes.multiline-quotes=\"single\"` option is incompatible with the formatter. We recommend disabling `Q001` when using the formatter, which enforces double quotes for multiline strings. Alternatively, set the `flake8-quotes.multiline-quotes` option to `\"double\"`.`"
|
||||
);
|
||||
}
|
||||
|
||||
if setting.linter.rules.enabled(Rule::BadQuotesDocstring)
|
||||
@@ -902,7 +921,9 @@ pub(super) fn warn_incompatible_formatter_settings(resolver: &Resolver) {
|
||||
QuoteStyle::Single | QuoteStyle::Double
|
||||
)
|
||||
{
|
||||
warn_user_once!("The `flake8-quotes.docstring-quotes=\"single\"` option is incompatible with the formatter. We recommend disabling `Q002` when using the formatter, which enforces double quotes for docstrings. Alternatively, set the `flake8-quotes.docstring-quotes` option to `\"double\"`.`");
|
||||
warn_user_once!(
|
||||
"The `flake8-quotes.docstring-quotes=\"single\"` option is incompatible with the formatter. We recommend disabling `Q002` when using the formatter, which enforces double quotes for docstrings. Alternatively, set the `flake8-quotes.docstring-quotes` option to `\"double\"`.`"
|
||||
);
|
||||
}
|
||||
|
||||
// Validate all isort settings.
|
||||
@@ -910,12 +931,16 @@ pub(super) fn warn_incompatible_formatter_settings(resolver: &Resolver) {
|
||||
// The formatter removes empty lines if the value is larger than 2 but always inserts a empty line after imports.
|
||||
// Two empty lines are okay because `isort` only uses this setting for top-level imports (not in nested blocks).
|
||||
if !matches!(setting.linter.isort.lines_after_imports, 1 | 2 | -1) {
|
||||
warn_user_once!("The isort option `isort.lines-after-imports` with a value other than `-1`, `1` or `2` is incompatible with the formatter. To avoid unexpected behavior, we recommend setting the option to one of: `2`, `1`, or `-1` (default).");
|
||||
warn_user_once!(
|
||||
"The isort option `isort.lines-after-imports` with a value other than `-1`, `1` or `2` is incompatible with the formatter. To avoid unexpected behavior, we recommend setting the option to one of: `2`, `1`, or `-1` (default)."
|
||||
);
|
||||
}
|
||||
|
||||
// Values larger than two get reduced to one line by the formatter if the import is in a nested block.
|
||||
if setting.linter.isort.lines_between_types > 1 {
|
||||
warn_user_once!("The isort option `isort.lines-between-types` with a value greater than 1 is incompatible with the formatter. To avoid unexpected behavior, we recommend setting the option to one of: `1` or `0` (default).");
|
||||
warn_user_once!(
|
||||
"The isort option `isort.lines-between-types` with a value greater than 1 is incompatible with the formatter. To avoid unexpected behavior, we recommend setting the option to one of: `1` or `0` (default)."
|
||||
);
|
||||
}
|
||||
|
||||
// isort inserts a trailing comma which the formatter preserves, but only if `skip-magic-trailing-comma` isn't false.
|
||||
@@ -924,11 +949,15 @@ pub(super) fn warn_incompatible_formatter_settings(resolver: &Resolver) {
|
||||
&& !setting.linter.isort.force_single_line
|
||||
{
|
||||
if setting.linter.isort.force_wrap_aliases {
|
||||
warn_user_once!("The isort option `isort.force-wrap-aliases` is incompatible with the formatter `format.skip-magic-trailing-comma=true` option. To avoid unexpected behavior, we recommend either setting `isort.force-wrap-aliases=false` or `format.skip-magic-trailing-comma=false`.");
|
||||
warn_user_once!(
|
||||
"The isort option `isort.force-wrap-aliases` is incompatible with the formatter `format.skip-magic-trailing-comma=true` option. To avoid unexpected behavior, we recommend either setting `isort.force-wrap-aliases=false` or `format.skip-magic-trailing-comma=false`."
|
||||
);
|
||||
}
|
||||
|
||||
if setting.linter.isort.split_on_trailing_comma {
|
||||
warn_user_once!("The isort option `isort.split-on-trailing-comma` is incompatible with the formatter `format.skip-magic-trailing-comma=true` option. To avoid unexpected behavior, we recommend either setting `isort.split-on-trailing-comma=false` or `format.skip-magic-trailing-comma=false`.");
|
||||
warn_user_once!(
|
||||
"The isort option `isort.split-on-trailing-comma` is incompatible with the formatter `format.skip-magic-trailing-comma=true` option. To avoid unexpected behavior, we recommend either setting `isort.split-on-trailing-comma=false` or `format.skip-magic-trailing-comma=false`."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,17 +6,17 @@ use log::error;
|
||||
|
||||
use ruff_linter::source_kind::SourceKind;
|
||||
use ruff_python_ast::{PySourceType, SourceType};
|
||||
use ruff_workspace::resolver::{match_exclusion, python_file_at_path, Resolver};
|
||||
use ruff_workspace::FormatterSettings;
|
||||
use ruff_workspace::resolver::{Resolver, match_exclusion, python_file_at_path};
|
||||
|
||||
use crate::ExitStatus;
|
||||
use crate::args::{ConfigArguments, FormatArguments, FormatRange};
|
||||
use crate::commands::format::{
|
||||
format_source, warn_incompatible_formatter_settings, FormatCommandError, FormatMode,
|
||||
FormatResult, FormattedSource,
|
||||
FormatCommandError, FormatMode, FormatResult, FormattedSource, format_source,
|
||||
warn_incompatible_formatter_settings,
|
||||
};
|
||||
use crate::resolve::resolve;
|
||||
use crate::stdin::{parrot_stdin, read_from_stdin};
|
||||
use crate::ExitStatus;
|
||||
|
||||
/// Run the formatter over a single file, read from `stdin`.
|
||||
pub(crate) fn format_stdin(
|
||||
|
||||
@@ -5,7 +5,7 @@ use anyhow::Result;
|
||||
use itertools::Itertools;
|
||||
|
||||
use ruff_linter::warn_user_once;
|
||||
use ruff_workspace::resolver::{python_files_in_path, PyprojectConfig, ResolvedFile};
|
||||
use ruff_workspace::resolver::{PyprojectConfig, ResolvedFile, python_files_in_path};
|
||||
|
||||
use crate::args::ConfigArguments;
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use anyhow::{Result, bail};
|
||||
use itertools::Itertools;
|
||||
|
||||
use ruff_workspace::resolver::{python_files_in_path, PyprojectConfig, ResolvedFile};
|
||||
use ruff_workspace::resolver::{PyprojectConfig, ResolvedFile, python_files_in_path};
|
||||
|
||||
use crate::args::ConfigArguments;
|
||||
|
||||
|
||||
@@ -14,18 +14,18 @@ use rustc_hash::FxHashMap;
|
||||
|
||||
use ruff_diagnostics::Diagnostic;
|
||||
use ruff_linter::codes::Rule;
|
||||
use ruff_linter::linter::{lint_fix, lint_only, FixTable, FixerResult, LinterResult, ParseSource};
|
||||
use ruff_linter::message::{Message, SyntaxErrorMessage};
|
||||
use ruff_linter::linter::{FixTable, FixerResult, LinterResult, ParseSource, lint_fix, lint_only};
|
||||
use ruff_linter::message::Message;
|
||||
use ruff_linter::package::PackageRoot;
|
||||
use ruff_linter::pyproject_toml::lint_pyproject_toml;
|
||||
use ruff_linter::settings::types::UnsafeFixes;
|
||||
use ruff_linter::settings::{flags, LinterSettings};
|
||||
use ruff_linter::settings::{LinterSettings, flags};
|
||||
use ruff_linter::source_kind::{SourceError, SourceKind};
|
||||
use ruff_linter::{fs, IOError};
|
||||
use ruff_linter::{IOError, fs};
|
||||
use ruff_notebook::{Notebook, NotebookError, NotebookIndex};
|
||||
use ruff_python_ast::{PySourceType, SourceType, TomlSourceType};
|
||||
use ruff_source_file::SourceFileBuilder;
|
||||
use ruff_text_size::{TextRange, TextSize};
|
||||
use ruff_text_size::TextRange;
|
||||
use ruff_workspace::Settings;
|
||||
|
||||
use crate::cache::{Cache, FileCacheKey, LintCacheData};
|
||||
@@ -71,7 +71,7 @@ impl Diagnostics {
|
||||
TextRange::default(),
|
||||
),
|
||||
source_file,
|
||||
TextSize::default(),
|
||||
None,
|
||||
)],
|
||||
FxHashMap::default(),
|
||||
)
|
||||
@@ -102,11 +102,7 @@ impl Diagnostics {
|
||||
let name = path.map_or_else(|| "-".into(), Path::to_string_lossy);
|
||||
let dummy = SourceFileBuilder::new(name, "").finish();
|
||||
Self::new(
|
||||
vec![Message::SyntaxError(SyntaxErrorMessage {
|
||||
message: err.to_string(),
|
||||
range: TextRange::default(),
|
||||
file: dummy,
|
||||
})],
|
||||
vec![Message::syntax_error(err, TextRange::default(), dummy)],
|
||||
FxHashMap::default(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#![allow(clippy::print_stdout)]
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{self, stdout, BufWriter, Write};
|
||||
use std::io::{self, BufWriter, Write, stdout};
|
||||
use std::num::NonZeroUsize;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
@@ -11,10 +11,10 @@ use anyhow::Result;
|
||||
use clap::CommandFactory;
|
||||
use colored::Colorize;
|
||||
use log::warn;
|
||||
use notify::{recommended_watcher, RecursiveMode, Watcher};
|
||||
use notify::{RecursiveMode, Watcher, recommended_watcher};
|
||||
|
||||
use args::{GlobalConfigArgs, ServerCommand};
|
||||
use ruff_linter::logging::{set_up_logging, LogLevel};
|
||||
use ruff_linter::logging::{LogLevel, set_up_logging};
|
||||
use ruff_linter::settings::flags::FixMode;
|
||||
use ruff_linter::settings::types::OutputFormat;
|
||||
use ruff_linter::{fs, warn_user, warn_user_once};
|
||||
@@ -488,7 +488,7 @@ pub fn check(args: CheckCommand, global_options: GlobalConfigArgs) -> Result<Exi
|
||||
mod test_file_change_detector {
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::{change_detected, ChangeKind};
|
||||
use crate::{ChangeKind, change_detected};
|
||||
|
||||
#[test]
|
||||
fn detect_correct_file_change() {
|
||||
|
||||
@@ -5,7 +5,7 @@ use clap::Parser;
|
||||
use colored::Colorize;
|
||||
|
||||
use ruff::args::Args;
|
||||
use ruff::{run, ExitStatus};
|
||||
use ruff::{ExitStatus, run};
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[global_allocator]
|
||||
@@ -15,6 +15,7 @@ static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
|
||||
not(target_os = "windows"),
|
||||
not(target_os = "openbsd"),
|
||||
not(target_os = "aix"),
|
||||
not(target_os = "android"),
|
||||
any(
|
||||
target_arch = "x86_64",
|
||||
target_arch = "aarch64",
|
||||
|
||||
@@ -1,23 +1,22 @@
|
||||
use std::cmp::Reverse;
|
||||
use std::fmt::Display;
|
||||
use std::hash::Hash;
|
||||
use std::io::Write;
|
||||
|
||||
use anyhow::Result;
|
||||
use bitflags::bitflags;
|
||||
use colored::Colorize;
|
||||
use itertools::{iterate, Itertools};
|
||||
use itertools::{Itertools, iterate};
|
||||
use ruff_linter::codes::NoqaCode;
|
||||
use serde::Serialize;
|
||||
|
||||
use ruff_linter::fs::relativize_path;
|
||||
use ruff_linter::logging::LogLevel;
|
||||
use ruff_linter::message::{
|
||||
AzureEmitter, Emitter, EmitterContext, GithubEmitter, GitlabEmitter, GroupedEmitter,
|
||||
JsonEmitter, JsonLinesEmitter, JunitEmitter, Message, MessageKind, PylintEmitter,
|
||||
RdjsonEmitter, SarifEmitter, TextEmitter,
|
||||
JsonEmitter, JsonLinesEmitter, JunitEmitter, Message, PylintEmitter, RdjsonEmitter,
|
||||
SarifEmitter, TextEmitter,
|
||||
};
|
||||
use ruff_linter::notify_user;
|
||||
use ruff_linter::registry::Rule;
|
||||
use ruff_linter::settings::flags::{self};
|
||||
use ruff_linter::settings::types::{OutputFormat, UnsafeFixes};
|
||||
|
||||
@@ -37,59 +36,12 @@ bitflags! {
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ExpandedStatistics {
|
||||
code: Option<SerializeRuleAsCode>,
|
||||
name: SerializeMessageKindAsTitle,
|
||||
code: Option<NoqaCode>,
|
||||
name: &'static str,
|
||||
count: usize,
|
||||
fixable: bool,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
struct SerializeRuleAsCode(Rule);
|
||||
|
||||
impl Serialize for SerializeRuleAsCode {
|
||||
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
serializer.serialize_str(&self.0.noqa_code().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for SerializeRuleAsCode {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0.noqa_code())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Rule> for SerializeRuleAsCode {
|
||||
fn from(rule: Rule) -> Self {
|
||||
Self(rule)
|
||||
}
|
||||
}
|
||||
|
||||
struct SerializeMessageKindAsTitle(MessageKind);
|
||||
|
||||
impl Serialize for SerializeMessageKindAsTitle {
|
||||
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
serializer.serialize_str(self.0.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for SerializeMessageKindAsTitle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(self.0.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MessageKind> for SerializeMessageKindAsTitle {
|
||||
fn from(kind: MessageKind) -> Self {
|
||||
Self(kind)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Printer {
|
||||
format: OutputFormat,
|
||||
log_level: LogLevel,
|
||||
@@ -157,7 +109,8 @@ impl Printer {
|
||||
} else {
|
||||
"es"
|
||||
};
|
||||
writeln!(writer,
|
||||
writeln!(
|
||||
writer,
|
||||
"{fix_prefix} {} fixable with the `--fix` option ({} hidden fix{es} can be enabled with the `--unsafe-fixes` option).",
|
||||
fixables.applicable, fixables.inapplicable_unsafe
|
||||
)?;
|
||||
@@ -175,7 +128,8 @@ impl Printer {
|
||||
} else {
|
||||
"es"
|
||||
};
|
||||
writeln!(writer,
|
||||
writeln!(
|
||||
writer,
|
||||
"No fixes available ({} hidden fix{es} can be enabled with the `--unsafe-fixes` option).",
|
||||
fixables.inapplicable_unsafe
|
||||
)?;
|
||||
@@ -205,15 +159,27 @@ impl Printer {
|
||||
if fixed > 0 {
|
||||
let s = if fixed == 1 { "" } else { "s" };
|
||||
if self.fix_mode.is_apply() {
|
||||
writeln!(writer, "Fixed {fixed} error{s} ({unapplied} additional fix{es} available with `--unsafe-fixes`).")?;
|
||||
writeln!(
|
||||
writer,
|
||||
"Fixed {fixed} error{s} ({unapplied} additional fix{es} available with `--unsafe-fixes`)."
|
||||
)?;
|
||||
} else {
|
||||
writeln!(writer, "Would fix {fixed} error{s} ({unapplied} additional fix{es} available with `--unsafe-fixes`).")?;
|
||||
writeln!(
|
||||
writer,
|
||||
"Would fix {fixed} error{s} ({unapplied} additional fix{es} available with `--unsafe-fixes`)."
|
||||
)?;
|
||||
}
|
||||
} else {
|
||||
if self.fix_mode.is_apply() {
|
||||
writeln!(writer, "No errors fixed ({unapplied} fix{es} available with `--unsafe-fixes`).")?;
|
||||
writeln!(
|
||||
writer,
|
||||
"No errors fixed ({unapplied} fix{es} available with `--unsafe-fixes`)."
|
||||
)?;
|
||||
} else {
|
||||
writeln!(writer, "No errors would be fixed ({unapplied} fix{es} available with `--unsafe-fixes`).")?;
|
||||
writeln!(
|
||||
writer,
|
||||
"No errors would be fixed ({unapplied} fix{es} available with `--unsafe-fixes`)."
|
||||
)?;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -336,21 +302,25 @@ impl Printer {
|
||||
let statistics: Vec<ExpandedStatistics> = diagnostics
|
||||
.messages
|
||||
.iter()
|
||||
.sorted_by_key(|message| (message.rule(), message.fixable()))
|
||||
.fold(vec![], |mut acc: Vec<(&Message, usize)>, message| {
|
||||
if let Some((prev_message, count)) = acc.last_mut() {
|
||||
if prev_message.rule() == message.rule() {
|
||||
*count += 1;
|
||||
return acc;
|
||||
.map(|message| (message.to_noqa_code(), message))
|
||||
.sorted_by_key(|(code, message)| (*code, message.fixable()))
|
||||
.fold(
|
||||
vec![],
|
||||
|mut acc: Vec<((Option<NoqaCode>, &Message), usize)>, (code, message)| {
|
||||
if let Some(((prev_code, _prev_message), count)) = acc.last_mut() {
|
||||
if *prev_code == code {
|
||||
*count += 1;
|
||||
return acc;
|
||||
}
|
||||
}
|
||||
}
|
||||
acc.push((message, 1));
|
||||
acc
|
||||
})
|
||||
acc.push(((code, message), 1));
|
||||
acc
|
||||
},
|
||||
)
|
||||
.iter()
|
||||
.map(|&(message, count)| ExpandedStatistics {
|
||||
code: message.rule().map(std::convert::Into::into),
|
||||
name: message.kind().into(),
|
||||
.map(|&((code, message), count)| ExpandedStatistics {
|
||||
code,
|
||||
name: message.name(),
|
||||
count,
|
||||
fixable: if let Some(fix) = message.fix() {
|
||||
fix.applies(self.unsafe_fixes.required_applicability())
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use anyhow::{Result, bail};
|
||||
use log::debug;
|
||||
use path_absolutize::path_dedot;
|
||||
|
||||
use ruff_workspace::configuration::Configuration;
|
||||
use ruff_workspace::pyproject::{self, find_fallback_target_version};
|
||||
use ruff_workspace::resolver::{
|
||||
resolve_root_settings, ConfigurationOrigin, ConfigurationTransformer, PyprojectConfig,
|
||||
PyprojectDiscoveryStrategy,
|
||||
ConfigurationOrigin, ConfigurationTransformer, PyprojectConfig, PyprojectDiscoveryStrategy,
|
||||
resolve_root_settings,
|
||||
};
|
||||
|
||||
use ruff_python_ast as ast;
|
||||
|
||||
@@ -1157,18 +1157,20 @@ include = ["*.ipy"]
|
||||
|
||||
#[test]
|
||||
fn warn_invalid_noqa_with_no_diagnostics() {
|
||||
assert_cmd_snapshot!(Command::new(get_cargo_bin(BIN_NAME))
|
||||
.args(STDIN_BASE_OPTIONS)
|
||||
.args(["--isolated"])
|
||||
.arg("--select")
|
||||
.arg("F401")
|
||||
.arg("-")
|
||||
.pass_stdin(
|
||||
r#"
|
||||
assert_cmd_snapshot!(
|
||||
Command::new(get_cargo_bin(BIN_NAME))
|
||||
.args(STDIN_BASE_OPTIONS)
|
||||
.args(["--isolated"])
|
||||
.arg("--select")
|
||||
.arg("F401")
|
||||
.arg("-")
|
||||
.pass_stdin(
|
||||
r#"
|
||||
# ruff: noqa: AAA101
|
||||
print("Hello world!")
|
||||
"#
|
||||
));
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -4997,30 +4999,34 @@ fn flake8_import_convention_invalid_aliases_config_module_name() -> Result<()> {
|
||||
|
||||
#[test]
|
||||
fn flake8_import_convention_unused_aliased_import() {
|
||||
assert_cmd_snapshot!(Command::new(get_cargo_bin(BIN_NAME))
|
||||
.args(STDIN_BASE_OPTIONS)
|
||||
.arg("--config")
|
||||
.arg(r#"lint.isort.required-imports = ["import pandas"]"#)
|
||||
.args(["--select", "I002,ICN001,F401"])
|
||||
.args(["--stdin-filename", "test.py"])
|
||||
.arg("--unsafe-fixes")
|
||||
.arg("--fix")
|
||||
.arg("-")
|
||||
.pass_stdin("1"));
|
||||
assert_cmd_snapshot!(
|
||||
Command::new(get_cargo_bin(BIN_NAME))
|
||||
.args(STDIN_BASE_OPTIONS)
|
||||
.arg("--config")
|
||||
.arg(r#"lint.isort.required-imports = ["import pandas"]"#)
|
||||
.args(["--select", "I002,ICN001,F401"])
|
||||
.args(["--stdin-filename", "test.py"])
|
||||
.arg("--unsafe-fixes")
|
||||
.arg("--fix")
|
||||
.arg("-")
|
||||
.pass_stdin("1")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flake8_import_convention_unused_aliased_import_no_conflict() {
|
||||
assert_cmd_snapshot!(Command::new(get_cargo_bin(BIN_NAME))
|
||||
.args(STDIN_BASE_OPTIONS)
|
||||
.arg("--config")
|
||||
.arg(r#"lint.isort.required-imports = ["import pandas as pd"]"#)
|
||||
.args(["--select", "I002,ICN001,F401"])
|
||||
.args(["--stdin-filename", "test.py"])
|
||||
.arg("--unsafe-fixes")
|
||||
.arg("--fix")
|
||||
.arg("-")
|
||||
.pass_stdin("1"));
|
||||
assert_cmd_snapshot!(
|
||||
Command::new(get_cargo_bin(BIN_NAME))
|
||||
.args(STDIN_BASE_OPTIONS)
|
||||
.arg("--config")
|
||||
.arg(r#"lint.isort.required-imports = ["import pandas as pd"]"#)
|
||||
.args(["--select", "I002,ICN001,F401"])
|
||||
.args(["--stdin-filename", "test.py"])
|
||||
.arg("--unsafe-fixes")
|
||||
.arg("--fix")
|
||||
.arg("-")
|
||||
.pass_stdin("1")
|
||||
);
|
||||
}
|
||||
|
||||
// See: https://github.com/astral-sh/ruff/issues/16177
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
//!
|
||||
//! The above snippet has been built out of the following structure:
|
||||
use crate::snippet;
|
||||
use std::cmp::{max, min, Reverse};
|
||||
use std::cmp::{Reverse, max, min};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Display;
|
||||
use std::ops::Range;
|
||||
@@ -41,7 +41,7 @@ use std::{cmp, fmt};
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
use crate::renderer::styled_buffer::StyledBuffer;
|
||||
use crate::renderer::{stylesheet::Stylesheet, Margin, Style, DEFAULT_TERM_WIDTH};
|
||||
use crate::renderer::{DEFAULT_TERM_WIDTH, Margin, Style, stylesheet::Stylesheet};
|
||||
|
||||
const ANONYMIZED_LINE_NUM: &str = "LL";
|
||||
const ERROR_TXT: &str = "error";
|
||||
@@ -1273,10 +1273,7 @@ fn fold_body(body: Vec<DisplayLine<'_>>) -> Vec<DisplayLine<'_>> {
|
||||
let inline_marks = lines
|
||||
.last()
|
||||
.and_then(|line| {
|
||||
if let DisplayLine::Source {
|
||||
ref inline_marks, ..
|
||||
} = line
|
||||
{
|
||||
if let DisplayLine::Source { inline_marks, .. } = line {
|
||||
let inline_marks = inline_marks.clone();
|
||||
Some(inline_marks)
|
||||
} else {
|
||||
|
||||
@@ -2,8 +2,8 @@ mod deserialize;
|
||||
|
||||
use crate::deserialize::Fixture;
|
||||
use ruff_annotate_snippets::{Message, Renderer};
|
||||
use snapbox::data::DataFormat;
|
||||
use snapbox::Data;
|
||||
use snapbox::data::DataFormat;
|
||||
use std::error::Error;
|
||||
|
||||
fn main() {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
use std::path::Path;
|
||||
|
||||
use ruff_benchmark::criterion::{
|
||||
criterion_group, criterion_main, BenchmarkId, Criterion, Throughput,
|
||||
BenchmarkId, Criterion, Throughput, criterion_group, criterion_main,
|
||||
};
|
||||
|
||||
use ruff_benchmark::{
|
||||
TestCase, LARGE_DATASET, NUMPY_CTYPESLIB, NUMPY_GLOBALS, PYDANTIC_TYPES, UNICODE_PYPINYIN,
|
||||
LARGE_DATASET, NUMPY_CTYPESLIB, NUMPY_GLOBALS, PYDANTIC_TYPES, TestCase, UNICODE_PYPINYIN,
|
||||
};
|
||||
use ruff_python_formatter::{format_module_ast, PreviewMode, PyFormatOptions};
|
||||
use ruff_python_parser::{parse, Mode, ParseOptions};
|
||||
use ruff_python_formatter::{PreviewMode, PyFormatOptions, format_module_ast};
|
||||
use ruff_python_parser::{Mode, ParseOptions, parse};
|
||||
use ruff_python_trivia::CommentRanges;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
use ruff_benchmark::criterion;
|
||||
|
||||
use criterion::{
|
||||
criterion_group, criterion_main, measurement::WallTime, BenchmarkId, Criterion, Throughput,
|
||||
BenchmarkId, Criterion, Throughput, criterion_group, criterion_main, measurement::WallTime,
|
||||
};
|
||||
use ruff_benchmark::{
|
||||
TestCase, LARGE_DATASET, NUMPY_CTYPESLIB, NUMPY_GLOBALS, PYDANTIC_TYPES, UNICODE_PYPINYIN,
|
||||
LARGE_DATASET, NUMPY_CTYPESLIB, NUMPY_GLOBALS, PYDANTIC_TYPES, TestCase, UNICODE_PYPINYIN,
|
||||
};
|
||||
use ruff_python_parser::{lexer, Mode, TokenKind};
|
||||
use ruff_python_parser::{Mode, TokenKind, lexer};
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[global_allocator]
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
use ruff_benchmark::criterion;
|
||||
|
||||
use criterion::{
|
||||
criterion_group, criterion_main, BenchmarkGroup, BenchmarkId, Criterion, Throughput,
|
||||
BenchmarkGroup, BenchmarkId, Criterion, Throughput, criterion_group, criterion_main,
|
||||
};
|
||||
use ruff_benchmark::{
|
||||
TestCase, LARGE_DATASET, NUMPY_CTYPESLIB, NUMPY_GLOBALS, PYDANTIC_TYPES, UNICODE_PYPINYIN,
|
||||
LARGE_DATASET, NUMPY_CTYPESLIB, NUMPY_GLOBALS, PYDANTIC_TYPES, TestCase, UNICODE_PYPINYIN,
|
||||
};
|
||||
use ruff_linter::linter::{lint_only, ParseSource};
|
||||
use ruff_linter::linter::{ParseSource, lint_only};
|
||||
use ruff_linter::rule_selector::PreviewOptions;
|
||||
use ruff_linter::settings::rule_table::RuleTable;
|
||||
use ruff_linter::settings::types::PreviewMode;
|
||||
use ruff_linter::settings::{flags, LinterSettings};
|
||||
use ruff_linter::settings::{LinterSettings, flags};
|
||||
use ruff_linter::source_kind::SourceKind;
|
||||
use ruff_linter::{registry::Rule, RuleSelector};
|
||||
use ruff_linter::{RuleSelector, registry::Rule};
|
||||
use ruff_python_ast::PySourceType;
|
||||
use ruff_python_parser::parse_module;
|
||||
|
||||
@@ -45,8 +45,8 @@ static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
|
||||
target_arch = "powerpc64"
|
||||
)
|
||||
))]
|
||||
#[unsafe(export_name = "_rjem_malloc_conf")]
|
||||
#[expect(non_upper_case_globals)]
|
||||
#[export_name = "_rjem_malloc_conf"]
|
||||
#[expect(unsafe_code)]
|
||||
pub static _rjem_malloc_conf: &[u8] = b"dirty_decay_ms:-1,muzzy_decay_ms:-1\0";
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
use ruff_benchmark::criterion;
|
||||
|
||||
use criterion::{
|
||||
criterion_group, criterion_main, measurement::WallTime, BenchmarkId, Criterion, Throughput,
|
||||
BenchmarkId, Criterion, Throughput, criterion_group, criterion_main, measurement::WallTime,
|
||||
};
|
||||
use ruff_benchmark::{
|
||||
TestCase, LARGE_DATASET, NUMPY_CTYPESLIB, NUMPY_GLOBALS, PYDANTIC_TYPES, UNICODE_PYPINYIN,
|
||||
LARGE_DATASET, NUMPY_CTYPESLIB, NUMPY_GLOBALS, PYDANTIC_TYPES, TestCase, UNICODE_PYPINYIN,
|
||||
};
|
||||
use ruff_python_ast::statement_visitor::{walk_stmt, StatementVisitor};
|
||||
use ruff_python_ast::Stmt;
|
||||
use ruff_python_ast::statement_visitor::{StatementVisitor, walk_stmt};
|
||||
use ruff_python_parser::parse_module;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
|
||||
@@ -3,13 +3,13 @@ use ruff_benchmark::criterion;
|
||||
|
||||
use std::ops::Range;
|
||||
|
||||
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
|
||||
use criterion::{BatchSize, Criterion, criterion_group, criterion_main};
|
||||
use rayon::ThreadPoolBuilder;
|
||||
use rustc_hash::FxHashSet;
|
||||
|
||||
use ruff_benchmark::TestFile;
|
||||
use ruff_db::diagnostic::{Diagnostic, DiagnosticId, Severity};
|
||||
use ruff_db::files::{system_path_to_file, File};
|
||||
use ruff_db::files::{File, system_path_to_file};
|
||||
use ruff_db::source::source_text;
|
||||
use ruff_db::system::{MemoryFileSystem, SystemPath, SystemPathBuf, TestSystem};
|
||||
use ruff_python_ast::PythonVersion;
|
||||
@@ -59,13 +59,7 @@ type KeyDiagnosticFields = (
|
||||
Severity,
|
||||
);
|
||||
|
||||
static EXPECTED_TOMLLIB_DIAGNOSTICS: &[KeyDiagnosticFields] = &[(
|
||||
DiagnosticId::lint("unused-ignore-comment"),
|
||||
Some("/src/tomllib/_parser.py"),
|
||||
Some(22299..22333),
|
||||
"Unused blanket `type: ignore` directive",
|
||||
Severity::Warning,
|
||||
)];
|
||||
static EXPECTED_TOMLLIB_DIAGNOSTICS: &[KeyDiagnosticFields] = &[];
|
||||
|
||||
fn tomllib_path(file: &TestFile) -> SystemPathBuf {
|
||||
SystemPathBuf::from("src").join(file.name())
|
||||
@@ -203,7 +197,7 @@ fn assert_diagnostics(db: &dyn Db, diagnostics: &[Diagnostic], expected: &[KeyDi
|
||||
diagnostic.id(),
|
||||
diagnostic
|
||||
.primary_span()
|
||||
.map(|span| span.file())
|
||||
.map(|span| span.expect_ty_file())
|
||||
.map(|file| file.path(db).as_str()),
|
||||
diagnostic
|
||||
.primary_span()
|
||||
@@ -307,6 +301,56 @@ fn benchmark_many_string_assignments(criterion: &mut Criterion) {
|
||||
});
|
||||
}
|
||||
|
||||
fn benchmark_many_tuple_assignments(criterion: &mut Criterion) {
|
||||
setup_rayon();
|
||||
|
||||
criterion.bench_function("ty_micro[many_tuple_assignments]", |b| {
|
||||
b.iter_batched_ref(
|
||||
|| {
|
||||
// This is a micro benchmark, but it is effectively identical to a code sample
|
||||
// observed in https://github.com/astral-sh/ty/issues/362
|
||||
setup_micro_case(
|
||||
r#"
|
||||
def flag() -> bool:
|
||||
return True
|
||||
|
||||
t = ()
|
||||
if flag():
|
||||
t += (1,)
|
||||
if flag():
|
||||
t += (2,)
|
||||
if flag():
|
||||
t += (3,)
|
||||
if flag():
|
||||
t += (4,)
|
||||
if flag():
|
||||
t += (5,)
|
||||
if flag():
|
||||
t += (6,)
|
||||
if flag():
|
||||
t += (7,)
|
||||
if flag():
|
||||
t += (8,)
|
||||
|
||||
# Perform some kind of operation on the union type
|
||||
print(1 in t)
|
||||
"#,
|
||||
)
|
||||
},
|
||||
|case| {
|
||||
let Case { db, .. } = case;
|
||||
let result = db.check().unwrap();
|
||||
assert_eq!(result.len(), 0);
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
criterion_group!(check_file, benchmark_cold, benchmark_incremental);
|
||||
criterion_group!(micro, benchmark_many_string_assignments);
|
||||
criterion_group!(
|
||||
micro,
|
||||
benchmark_many_string_assignments,
|
||||
benchmark_many_tuple_assignments
|
||||
);
|
||||
criterion_main!(check_file, micro);
|
||||
|
||||
@@ -2,8 +2,8 @@ use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::num::{
|
||||
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroU128, NonZeroU16,
|
||||
NonZeroU32, NonZeroU64, NonZeroU8,
|
||||
NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroU8, NonZeroU16, NonZeroU32,
|
||||
NonZeroU64, NonZeroU128,
|
||||
};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
|
||||
@@ -36,7 +36,6 @@ path-slash = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true, optional = true }
|
||||
tracing-tree = { workspace = true, optional = true }
|
||||
rustc-hash = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
|
||||
@@ -55,4 +54,4 @@ cache = ["ruff_cache"]
|
||||
os = ["ignore", "dep:etcetera"]
|
||||
serde = ["dep:serde", "camino/serde1"]
|
||||
# Exposes testing utilities.
|
||||
testing = ["tracing-subscriber", "tracing-tree"]
|
||||
testing = ["tracing-subscriber"]
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
use std::{fmt::Formatter, sync::Arc};
|
||||
|
||||
use thiserror::Error;
|
||||
use render::{FileResolver, Input};
|
||||
use ruff_source_file::{SourceCode, SourceFile};
|
||||
|
||||
use ruff_annotate_snippets::Level as AnnotateLevel;
|
||||
use ruff_text_size::{Ranged, TextRange};
|
||||
|
||||
pub use self::render::DisplayDiagnostic;
|
||||
use crate::files::File;
|
||||
use crate::Db;
|
||||
use crate::{Db, files::File};
|
||||
|
||||
use self::render::FileResolver;
|
||||
mod render;
|
||||
mod stylesheet;
|
||||
|
||||
@@ -115,10 +114,9 @@ impl Diagnostic {
|
||||
/// callers should prefer using this with `write!` instead of `writeln!`.
|
||||
pub fn display<'a>(
|
||||
&'a self,
|
||||
db: &'a dyn Db,
|
||||
resolver: &'a dyn FileResolver,
|
||||
config: &'a DisplayDiagnosticConfig,
|
||||
) -> DisplayDiagnostic<'a> {
|
||||
let resolver = FileResolver::new(db);
|
||||
DisplayDiagnostic::new(resolver, config, self)
|
||||
}
|
||||
|
||||
@@ -233,6 +231,16 @@ impl Diagnostic {
|
||||
self.primary_annotation().map(|ann| ann.tags.as_slice())
|
||||
}
|
||||
|
||||
/// Returns the "primary" span of this diagnostic, panicking if it does not exist.
|
||||
///
|
||||
/// This should typically only be used when working with diagnostics in Ruff, where diagnostics
|
||||
/// are currently required to have a primary span.
|
||||
///
|
||||
/// See [`Diagnostic::primary_span`] for more details.
|
||||
pub fn expect_primary_span(&self) -> Span {
|
||||
self.primary_span().expect("Expected a primary span")
|
||||
}
|
||||
|
||||
/// Returns a key that can be used to sort two diagnostics into the canonical order
|
||||
/// in which they should appear when rendered.
|
||||
pub fn rendering_sort_key<'a>(&'a self, db: &'a dyn Db) -> impl Ord + 'a {
|
||||
@@ -241,6 +249,25 @@ impl Diagnostic {
|
||||
diagnostic: self,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns all annotations, skipping the first primary annotation.
|
||||
pub fn secondary_annotations(&self) -> impl Iterator<Item = &Annotation> {
|
||||
let mut seen_primary = false;
|
||||
self.inner.annotations.iter().filter(move |ann| {
|
||||
if seen_primary {
|
||||
true
|
||||
} else if ann.is_primary {
|
||||
seen_primary = true;
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn sub_diagnostics(&self) -> &[SubDiagnostic] {
|
||||
&self.inner.subs
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
@@ -267,11 +294,7 @@ impl Ord for RenderingSortKey<'_> {
|
||||
self.diagnostic.primary_span(),
|
||||
other.diagnostic.primary_span(),
|
||||
) {
|
||||
let order = span1
|
||||
.file()
|
||||
.path(self.db)
|
||||
.as_str()
|
||||
.cmp(span2.file().path(self.db).as_str());
|
||||
let order = span1.file().path(&self.db).cmp(span2.file().path(&self.db));
|
||||
if order.is_ne() {
|
||||
return order;
|
||||
}
|
||||
@@ -367,6 +390,57 @@ impl SubDiagnostic {
|
||||
pub fn annotate(&mut self, ann: Annotation) {
|
||||
self.inner.annotations.push(ann);
|
||||
}
|
||||
|
||||
pub fn annotations(&self) -> &[Annotation] {
|
||||
&self.inner.annotations
|
||||
}
|
||||
|
||||
/// Returns a shared borrow of the "primary" annotation of this diagnostic
|
||||
/// if one exists.
|
||||
///
|
||||
/// When there are multiple primary annotations, then the first one that
|
||||
/// was added to this diagnostic is returned.
|
||||
pub fn primary_annotation(&self) -> Option<&Annotation> {
|
||||
self.inner.annotations.iter().find(|ann| ann.is_primary)
|
||||
}
|
||||
|
||||
/// Introspects this diagnostic and returns what kind of "primary" message
|
||||
/// it contains for concise formatting.
|
||||
///
|
||||
/// When we concisely format diagnostics, we likely want to not only
|
||||
/// include the primary diagnostic message but also the message attached
|
||||
/// to the primary annotation. In particular, the primary annotation often
|
||||
/// contains *essential* information or context for understanding the
|
||||
/// diagnostic.
|
||||
///
|
||||
/// The reason why we don't just always return both the main diagnostic
|
||||
/// message and the primary annotation message is because this was written
|
||||
/// in the midst of an incremental migration of ty over to the new
|
||||
/// diagnostic data model. At time of writing, diagnostics were still
|
||||
/// constructed in the old model where the main diagnostic message and the
|
||||
/// primary annotation message were not distinguished from each other. So
|
||||
/// for now, we carefully return what kind of messages this diagnostic
|
||||
/// contains. In effect, if this diagnostic has a non-empty main message
|
||||
/// *and* a non-empty primary annotation message, then the diagnostic is
|
||||
/// 100% using the new diagnostic data model and we can format things
|
||||
/// appropriately.
|
||||
///
|
||||
/// The type returned implements the `std::fmt::Display` trait. In most
|
||||
/// cases, just converting it to a string (or printing it) will do what
|
||||
/// you want.
|
||||
pub fn concise_message(&self) -> ConciseMessage {
|
||||
let main = self.inner.message.as_str();
|
||||
let annotation = self
|
||||
.primary_annotation()
|
||||
.and_then(|ann| ann.get_message())
|
||||
.unwrap_or_default();
|
||||
match (main.is_empty(), annotation.is_empty()) {
|
||||
(false, true) => ConciseMessage::MainDiagnostic(main),
|
||||
(true, false) => ConciseMessage::PrimaryAnnotation(annotation),
|
||||
(false, false) => ConciseMessage::Both { main, annotation },
|
||||
(true, true) => ConciseMessage::Empty,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
@@ -489,6 +563,11 @@ impl Annotation {
|
||||
&self.span
|
||||
}
|
||||
|
||||
/// Sets the span on this annotation.
|
||||
pub fn set_span(&mut self, span: Span) {
|
||||
self.span = span;
|
||||
}
|
||||
|
||||
/// Returns the tags associated with this annotation.
|
||||
pub fn get_tags(&self) -> &[DiagnosticTag] {
|
||||
&self.tags
|
||||
@@ -608,62 +687,84 @@ impl DiagnosticId {
|
||||
code.split_once(':').map(|(_, rest)| rest)
|
||||
}
|
||||
|
||||
/// Returns `true` if this `DiagnosticId` matches the given name.
|
||||
/// Returns a concise description of this diagnostic ID.
|
||||
///
|
||||
/// ## Examples
|
||||
/// ```
|
||||
/// use ruff_db::diagnostic::DiagnosticId;
|
||||
///
|
||||
/// assert!(DiagnosticId::Io.matches("io"));
|
||||
/// assert!(DiagnosticId::lint("test").matches("lint:test"));
|
||||
/// assert!(!DiagnosticId::lint("test").matches("test"));
|
||||
/// ```
|
||||
pub fn matches(&self, expected_name: &str) -> bool {
|
||||
match self.as_str() {
|
||||
Ok(id) => id == expected_name,
|
||||
Err(DiagnosticAsStrError::Category { category, name }) => expected_name
|
||||
.strip_prefix(category)
|
||||
.and_then(|prefix| prefix.strip_prefix(":"))
|
||||
.is_some_and(|rest| rest == name),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> Result<&str, DiagnosticAsStrError> {
|
||||
Ok(match self {
|
||||
/// Note that this doesn't include the lint's category. It
|
||||
/// only includes the lint's name.
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
DiagnosticId::Panic => "panic",
|
||||
DiagnosticId::Io => "io",
|
||||
DiagnosticId::InvalidSyntax => "invalid-syntax",
|
||||
DiagnosticId::Lint(name) => {
|
||||
return Err(DiagnosticAsStrError::Category {
|
||||
category: "lint",
|
||||
name: name.as_str(),
|
||||
})
|
||||
}
|
||||
DiagnosticId::Lint(name) => name.as_str(),
|
||||
DiagnosticId::RevealedType => "revealed-type",
|
||||
DiagnosticId::UnknownRule => "unknown-rule",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Error)]
|
||||
pub enum DiagnosticAsStrError {
|
||||
/// The id can't be converted to a string because it belongs to a sub-category.
|
||||
#[error("id from a sub-category: {category}:{name}")]
|
||||
Category {
|
||||
/// The id's category.
|
||||
category: &'static str,
|
||||
/// The diagnostic id in this category.
|
||||
name: &'static str,
|
||||
},
|
||||
pub fn is_invalid_syntax(&self) -> bool {
|
||||
matches!(self, Self::InvalidSyntax)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for DiagnosticId {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
match self.as_str() {
|
||||
Ok(name) => f.write_str(name),
|
||||
Err(DiagnosticAsStrError::Category { category, name }) => {
|
||||
write!(f, "{category}:{name}")
|
||||
}
|
||||
write!(f, "{}", self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// A unified file representation for both ruff and ty.
|
||||
///
|
||||
/// Such a representation is needed for rendering [`Diagnostic`]s that can optionally contain
|
||||
/// [`Annotation`]s with [`Span`]s that need to refer to the text of a file. However, ty and ruff
|
||||
/// use very different file types: a `Copy`-able salsa-interned [`File`], and a heavier-weight
|
||||
/// [`SourceFile`], respectively.
|
||||
///
|
||||
/// This enum presents a unified interface to these two types for the sake of creating [`Span`]s and
|
||||
/// emitting diagnostics from both ty and ruff.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum UnifiedFile {
|
||||
Ty(File),
|
||||
Ruff(SourceFile),
|
||||
}
|
||||
|
||||
impl UnifiedFile {
|
||||
pub fn path<'a>(&'a self, resolver: &'a dyn FileResolver) -> &'a str {
|
||||
match self {
|
||||
UnifiedFile::Ty(file) => resolver.path(*file),
|
||||
UnifiedFile::Ruff(file) => file.name(),
|
||||
}
|
||||
}
|
||||
|
||||
fn diagnostic_source(&self, resolver: &dyn FileResolver) -> DiagnosticSource {
|
||||
match self {
|
||||
UnifiedFile::Ty(file) => DiagnosticSource::Ty(resolver.input(*file)),
|
||||
UnifiedFile::Ruff(file) => DiagnosticSource::Ruff(file.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A unified wrapper for types that can be converted to a [`SourceCode`].
|
||||
///
|
||||
/// As with [`UnifiedFile`], ruff and ty use slightly different representations for source code.
|
||||
/// [`DiagnosticSource`] wraps both of these and provides the single
|
||||
/// [`DiagnosticSource::as_source_code`] method to produce a [`SourceCode`] with the appropriate
|
||||
/// lifetimes.
|
||||
///
|
||||
/// See [`UnifiedFile::diagnostic_source`] for a way to obtain a [`DiagnosticSource`] from a file
|
||||
/// and [`FileResolver`].
|
||||
#[derive(Clone, Debug)]
|
||||
enum DiagnosticSource {
|
||||
Ty(Input),
|
||||
Ruff(SourceFile),
|
||||
}
|
||||
|
||||
impl DiagnosticSource {
|
||||
/// Returns this input as a `SourceCode` for convenient querying.
|
||||
fn as_source_code(&self) -> SourceCode {
|
||||
match self {
|
||||
DiagnosticSource::Ty(input) => SourceCode::new(input.text.as_str(), &input.line_index),
|
||||
DiagnosticSource::Ruff(source) => SourceCode::new(source.source_text(), source.index()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -675,14 +776,14 @@ impl std::fmt::Display for DiagnosticId {
|
||||
/// the entire file. For example, when the file should be executable but isn't.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Span {
|
||||
file: File,
|
||||
file: UnifiedFile,
|
||||
range: Option<TextRange>,
|
||||
}
|
||||
|
||||
impl Span {
|
||||
/// Returns the `File` attached to this `Span`.
|
||||
pub fn file(&self) -> File {
|
||||
self.file
|
||||
/// Returns the `UnifiedFile` attached to this `Span`.
|
||||
pub fn file(&self) -> &UnifiedFile {
|
||||
&self.file
|
||||
}
|
||||
|
||||
/// Returns the range, if available, attached to this `Span`.
|
||||
@@ -703,10 +804,38 @@ impl Span {
|
||||
pub fn with_optional_range(self, range: Option<TextRange>) -> Span {
|
||||
Span { range, ..self }
|
||||
}
|
||||
|
||||
/// Returns the [`File`] attached to this [`Span`].
|
||||
///
|
||||
/// Panics if the file is a [`UnifiedFile::Ruff`] instead of a [`UnifiedFile::Ty`].
|
||||
pub fn expect_ty_file(&self) -> File {
|
||||
match self.file {
|
||||
UnifiedFile::Ty(file) => file,
|
||||
UnifiedFile::Ruff(_) => panic!("Expected a ty `File`, found a ruff `SourceFile`"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the [`SourceFile`] attached to this [`Span`].
|
||||
///
|
||||
/// Panics if the file is a [`UnifiedFile::Ty`] instead of a [`UnifiedFile::Ruff`].
|
||||
pub fn expect_ruff_file(&self) -> &SourceFile {
|
||||
match &self.file {
|
||||
UnifiedFile::Ty(_) => panic!("Expected a ruff `SourceFile`, found a ty `File`"),
|
||||
UnifiedFile::Ruff(file) => file,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<File> for Span {
|
||||
fn from(file: File) -> Span {
|
||||
let file = UnifiedFile::Ty(file);
|
||||
Span { file, range: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SourceFile> for Span {
|
||||
fn from(file: SourceFile) -> Self {
|
||||
let file = UnifiedFile::Ruff(file);
|
||||
Span { file, range: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,16 +7,17 @@ use ruff_annotate_snippets::{
|
||||
use ruff_source_file::{LineIndex, OneIndexed, SourceCode};
|
||||
use ruff_text_size::{TextRange, TextSize};
|
||||
|
||||
use crate::diagnostic::stylesheet::{fmt_styled, DiagnosticStylesheet};
|
||||
use crate::diagnostic::stylesheet::{DiagnosticStylesheet, fmt_styled};
|
||||
use crate::{
|
||||
files::File,
|
||||
source::{line_index, source_text, SourceText},
|
||||
system::SystemPath,
|
||||
Db,
|
||||
files::File,
|
||||
source::{SourceText, line_index, source_text},
|
||||
system::SystemPath,
|
||||
};
|
||||
|
||||
use super::{
|
||||
Annotation, Diagnostic, DiagnosticFormat, DisplayDiagnosticConfig, Severity, SubDiagnostic,
|
||||
Annotation, Diagnostic, DiagnosticFormat, DiagnosticSource, DisplayDiagnosticConfig, Severity,
|
||||
SubDiagnostic,
|
||||
};
|
||||
|
||||
/// A type that implements `std::fmt::Display` for diagnostic rendering.
|
||||
@@ -30,17 +31,16 @@ use super::{
|
||||
/// values. When using Salsa, this most commonly corresponds to the lifetime
|
||||
/// of a Salsa `Db`.
|
||||
/// * The lifetime of the diagnostic being rendered.
|
||||
#[derive(Debug)]
|
||||
pub struct DisplayDiagnostic<'a> {
|
||||
config: &'a DisplayDiagnosticConfig,
|
||||
resolver: FileResolver<'a>,
|
||||
resolver: &'a dyn FileResolver,
|
||||
annotate_renderer: AnnotateRenderer,
|
||||
diag: &'a Diagnostic,
|
||||
}
|
||||
|
||||
impl<'a> DisplayDiagnostic<'a> {
|
||||
pub(crate) fn new(
|
||||
resolver: FileResolver<'a>,
|
||||
resolver: &'a dyn FileResolver,
|
||||
config: &'a DisplayDiagnosticConfig,
|
||||
diag: &'a Diagnostic,
|
||||
) -> DisplayDiagnostic<'a> {
|
||||
@@ -86,11 +86,13 @@ impl std::fmt::Display for DisplayDiagnostic<'_> {
|
||||
write!(
|
||||
f,
|
||||
" {path}",
|
||||
path = fmt_styled(self.resolver.path(span.file()), stylesheet.emphasis)
|
||||
path = fmt_styled(span.file().path(self.resolver), stylesheet.emphasis)
|
||||
)?;
|
||||
if let Some(range) = span.range() {
|
||||
let input = self.resolver.input(span.file());
|
||||
let start = input.as_source_code().line_column(range.start());
|
||||
let diagnostic_source = span.file().diagnostic_source(self.resolver);
|
||||
let start = diagnostic_source
|
||||
.as_source_code()
|
||||
.line_column(range.start());
|
||||
|
||||
write!(
|
||||
f,
|
||||
@@ -115,7 +117,7 @@ impl std::fmt::Display for DisplayDiagnostic<'_> {
|
||||
.emphasis(stylesheet.emphasis)
|
||||
.none(stylesheet.none);
|
||||
|
||||
let resolved = Resolved::new(&self.resolver, self.diag);
|
||||
let resolved = Resolved::new(self.resolver, self.diag);
|
||||
let renderable = resolved.to_renderable(self.config.context);
|
||||
for diag in renderable.diagnostics.iter() {
|
||||
writeln!(f, "{}", renderer.render(diag.to_annotate()))?;
|
||||
@@ -138,26 +140,23 @@ impl std::fmt::Display for DisplayDiagnostic<'_> {
|
||||
/// both.)
|
||||
#[derive(Debug)]
|
||||
struct Resolved<'a> {
|
||||
id: String,
|
||||
diagnostics: Vec<ResolvedDiagnostic<'a>>,
|
||||
}
|
||||
|
||||
impl<'a> Resolved<'a> {
|
||||
/// Creates a new resolved set of diagnostics.
|
||||
fn new(resolver: &FileResolver<'a>, diag: &'a Diagnostic) -> Resolved<'a> {
|
||||
fn new(resolver: &'a dyn FileResolver, diag: &'a Diagnostic) -> Resolved<'a> {
|
||||
let mut diagnostics = vec![];
|
||||
diagnostics.push(ResolvedDiagnostic::from_diagnostic(resolver, diag));
|
||||
for sub in &diag.inner.subs {
|
||||
diagnostics.push(ResolvedDiagnostic::from_sub_diagnostic(resolver, sub));
|
||||
}
|
||||
let id = diag.inner.id.to_string();
|
||||
Resolved { id, diagnostics }
|
||||
Resolved { diagnostics }
|
||||
}
|
||||
|
||||
/// Creates a value that is amenable to rendering directly.
|
||||
fn to_renderable(&self, context: usize) -> Renderable<'_> {
|
||||
Renderable {
|
||||
id: &self.id,
|
||||
diagnostics: self
|
||||
.diagnostics
|
||||
.iter()
|
||||
@@ -175,6 +174,7 @@ impl<'a> Resolved<'a> {
|
||||
#[derive(Debug)]
|
||||
struct ResolvedDiagnostic<'a> {
|
||||
severity: Severity,
|
||||
id: Option<String>,
|
||||
message: String,
|
||||
annotations: Vec<ResolvedAnnotation<'a>>,
|
||||
}
|
||||
@@ -182,7 +182,7 @@ struct ResolvedDiagnostic<'a> {
|
||||
impl<'a> ResolvedDiagnostic<'a> {
|
||||
/// Resolve a single diagnostic.
|
||||
fn from_diagnostic(
|
||||
resolver: &FileResolver<'a>,
|
||||
resolver: &'a dyn FileResolver,
|
||||
diag: &'a Diagnostic,
|
||||
) -> ResolvedDiagnostic<'a> {
|
||||
let annotations: Vec<_> = diag
|
||||
@@ -190,25 +190,16 @@ impl<'a> ResolvedDiagnostic<'a> {
|
||||
.annotations
|
||||
.iter()
|
||||
.filter_map(|ann| {
|
||||
let path = resolver.path(ann.span.file);
|
||||
let input = resolver.input(ann.span.file);
|
||||
ResolvedAnnotation::new(path, &input, ann)
|
||||
let path = ann.span.file.path(resolver);
|
||||
let diagnostic_source = ann.span.file.diagnostic_source(resolver);
|
||||
ResolvedAnnotation::new(path, &diagnostic_source, ann)
|
||||
})
|
||||
.collect();
|
||||
let message = if diag.inner.message.as_str().is_empty() {
|
||||
diag.inner.id.to_string()
|
||||
} else {
|
||||
// TODO: See the comment on `Renderable::id` for
|
||||
// a plausible better idea than smushing the ID
|
||||
// into the diagnostic message.
|
||||
format!(
|
||||
"{id}: {message}",
|
||||
id = diag.inner.id,
|
||||
message = diag.inner.message.as_str(),
|
||||
)
|
||||
};
|
||||
let id = Some(diag.inner.id.to_string());
|
||||
let message = diag.inner.message.as_str().to_string();
|
||||
ResolvedDiagnostic {
|
||||
severity: diag.inner.severity,
|
||||
id,
|
||||
message,
|
||||
annotations,
|
||||
}
|
||||
@@ -216,7 +207,7 @@ impl<'a> ResolvedDiagnostic<'a> {
|
||||
|
||||
/// Resolve a single sub-diagnostic.
|
||||
fn from_sub_diagnostic(
|
||||
resolver: &FileResolver<'a>,
|
||||
resolver: &'a dyn FileResolver,
|
||||
diag: &'a SubDiagnostic,
|
||||
) -> ResolvedDiagnostic<'a> {
|
||||
let annotations: Vec<_> = diag
|
||||
@@ -224,13 +215,14 @@ impl<'a> ResolvedDiagnostic<'a> {
|
||||
.annotations
|
||||
.iter()
|
||||
.filter_map(|ann| {
|
||||
let path = resolver.path(ann.span.file);
|
||||
let input = resolver.input(ann.span.file);
|
||||
ResolvedAnnotation::new(path, &input, ann)
|
||||
let path = ann.span.file.path(resolver);
|
||||
let diagnostic_source = ann.span.file.diagnostic_source(resolver);
|
||||
ResolvedAnnotation::new(path, &diagnostic_source, ann)
|
||||
})
|
||||
.collect();
|
||||
ResolvedDiagnostic {
|
||||
severity: diag.inner.severity,
|
||||
id: None,
|
||||
message: diag.inner.message.as_str().to_string(),
|
||||
annotations,
|
||||
}
|
||||
@@ -259,10 +251,18 @@ impl<'a> ResolvedDiagnostic<'a> {
|
||||
continue;
|
||||
};
|
||||
|
||||
let prev_context_ends =
|
||||
context_after(&prev.input.as_source_code(), context, prev.line_end).get();
|
||||
let this_context_begins =
|
||||
context_before(&ann.input.as_source_code(), context, ann.line_start).get();
|
||||
let prev_context_ends = context_after(
|
||||
&prev.diagnostic_source.as_source_code(),
|
||||
context,
|
||||
prev.line_end,
|
||||
)
|
||||
.get();
|
||||
let this_context_begins = context_before(
|
||||
&ann.diagnostic_source.as_source_code(),
|
||||
context,
|
||||
ann.line_start,
|
||||
)
|
||||
.get();
|
||||
// The boundary case here is when `prev_context_ends`
|
||||
// is exactly one less than `this_context_begins`. In
|
||||
// that case, the context windows are adajcent and we
|
||||
@@ -289,6 +289,7 @@ impl<'a> ResolvedDiagnostic<'a> {
|
||||
.sort_by(|snips1, snips2| snips1.has_primary.cmp(&snips2.has_primary).reverse());
|
||||
RenderableDiagnostic {
|
||||
severity: self.severity,
|
||||
id: self.id.as_deref(),
|
||||
message: &self.message,
|
||||
snippets_by_input,
|
||||
}
|
||||
@@ -304,7 +305,7 @@ impl<'a> ResolvedDiagnostic<'a> {
|
||||
#[derive(Debug)]
|
||||
struct ResolvedAnnotation<'a> {
|
||||
path: &'a str,
|
||||
input: Input,
|
||||
diagnostic_source: DiagnosticSource,
|
||||
range: TextRange,
|
||||
line_start: OneIndexed,
|
||||
line_end: OneIndexed,
|
||||
@@ -318,8 +319,12 @@ impl<'a> ResolvedAnnotation<'a> {
|
||||
/// `path` is the path of the file that this annotation points to.
|
||||
///
|
||||
/// `input` is the contents of the file that this annotation points to.
|
||||
fn new(path: &'a str, input: &Input, ann: &'a Annotation) -> Option<ResolvedAnnotation<'a>> {
|
||||
let source = input.as_source_code();
|
||||
fn new(
|
||||
path: &'a str,
|
||||
diagnostic_source: &DiagnosticSource,
|
||||
ann: &'a Annotation,
|
||||
) -> Option<ResolvedAnnotation<'a>> {
|
||||
let source = diagnostic_source.as_source_code();
|
||||
let (range, line_start, line_end) = match (ann.span.range(), ann.message.is_some()) {
|
||||
// An annotation with no range AND no message is probably(?)
|
||||
// meaningless, but we should try to render it anyway.
|
||||
@@ -345,7 +350,7 @@ impl<'a> ResolvedAnnotation<'a> {
|
||||
};
|
||||
Some(ResolvedAnnotation {
|
||||
path,
|
||||
input: input.clone(),
|
||||
diagnostic_source: diagnostic_source.clone(),
|
||||
range,
|
||||
line_start,
|
||||
line_end,
|
||||
@@ -364,20 +369,6 @@ impl<'a> ResolvedAnnotation<'a> {
|
||||
/// renderable value. This is usually the lifetime of `Resolved`.
|
||||
#[derive(Debug)]
|
||||
struct Renderable<'r> {
|
||||
// TODO: This is currently unused in the rendering logic below. I'm not
|
||||
// 100% sure yet where I want to put it, but I like what `rustc` does:
|
||||
//
|
||||
// error[E0599]: no method named `sub_builder` <..snip..>
|
||||
//
|
||||
// I believe in order to do this, we'll need to patch it in to
|
||||
// `ruff_annotate_snippets` though. We leave it here for now with that plan
|
||||
// in mind.
|
||||
//
|
||||
// (At time of writing, 2025-03-13, we currently render the diagnostic
|
||||
// ID into the main message of the parent diagnostic. We don't use this
|
||||
// specific field to do that though.)
|
||||
#[expect(dead_code)]
|
||||
id: &'r str,
|
||||
diagnostics: Vec<RenderableDiagnostic<'r>>,
|
||||
}
|
||||
|
||||
@@ -386,6 +377,12 @@ struct Renderable<'r> {
|
||||
struct RenderableDiagnostic<'r> {
|
||||
/// The severity of the diagnostic.
|
||||
severity: Severity,
|
||||
/// The ID of the diagnostic. The ID can usually be used on the CLI or in a
|
||||
/// config file to change the severity of a lint.
|
||||
///
|
||||
/// An ID is always present for top-level diagnostics and always absent for
|
||||
/// sub-diagnostics.
|
||||
id: Option<&'r str>,
|
||||
/// The message emitted with the diagnostic, before any snippets are
|
||||
/// rendered.
|
||||
message: &'r str,
|
||||
@@ -406,7 +403,11 @@ impl RenderableDiagnostic<'_> {
|
||||
.iter()
|
||||
.map(|snippet| snippet.to_annotate(path))
|
||||
});
|
||||
level.title(self.message).snippets(snippets)
|
||||
let mut message = level.title(self.message);
|
||||
if let Some(id) = self.id {
|
||||
message = message.id(id);
|
||||
}
|
||||
message.snippets(snippets)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -510,8 +511,8 @@ impl<'r> RenderableSnippet<'r> {
|
||||
!anns.is_empty(),
|
||||
"creating a renderable snippet requires a non-zero number of annotations",
|
||||
);
|
||||
let input = &anns[0].input;
|
||||
let source = input.as_source_code();
|
||||
let diagnostic_source = &anns[0].diagnostic_source;
|
||||
let source = diagnostic_source.as_source_code();
|
||||
let has_primary = anns.iter().any(|ann| ann.is_primary);
|
||||
|
||||
let line_start = context_before(
|
||||
@@ -527,7 +528,7 @@ impl<'r> RenderableSnippet<'r> {
|
||||
|
||||
let snippet_start = source.line_start(line_start);
|
||||
let snippet_end = source.line_end(line_end);
|
||||
let snippet = input
|
||||
let snippet = diagnostic_source
|
||||
.as_source_code()
|
||||
.slice(TextRange::new(snippet_start, snippet_end));
|
||||
|
||||
@@ -613,7 +614,7 @@ impl<'r> RenderableAnnotation<'r> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that facilitates the retrieval of source code from a `Span`.
|
||||
/// A trait that facilitates the retrieval of source code from a `Span`.
|
||||
///
|
||||
/// At present, this is tightly coupled with a Salsa database. In the future,
|
||||
/// it is intended for this resolver to become an abstraction providing a
|
||||
@@ -628,36 +629,24 @@ impl<'r> RenderableAnnotation<'r> {
|
||||
/// callers will need to pass in a different "resolver" for turning `Span`s
|
||||
/// into actual file paths/contents. The infrastructure for this isn't fully in
|
||||
/// place, but this type serves to demarcate the intended abstraction boundary.
|
||||
pub(crate) struct FileResolver<'a> {
|
||||
db: &'a dyn Db,
|
||||
}
|
||||
|
||||
impl<'a> FileResolver<'a> {
|
||||
/// Creates a new resolver from a Salsa database.
|
||||
pub(crate) fn new(db: &'a dyn Db) -> FileResolver<'a> {
|
||||
FileResolver { db }
|
||||
}
|
||||
|
||||
pub trait FileResolver {
|
||||
/// Returns the path associated with the file given.
|
||||
fn path(&self, file: File) -> &'a str {
|
||||
relativize_path(
|
||||
self.db.system().current_directory(),
|
||||
file.path(self.db).as_str(),
|
||||
)
|
||||
}
|
||||
fn path(&self, file: File) -> &str;
|
||||
|
||||
/// Returns the input contents associated with the file given.
|
||||
fn input(&self, file: File) -> Input {
|
||||
Input {
|
||||
text: source_text(self.db, file),
|
||||
line_index: line_index(self.db, file),
|
||||
}
|
||||
}
|
||||
fn input(&self, file: File) -> Input;
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for FileResolver<'_> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
write!(f, "<salsa based file resolver>")
|
||||
impl FileResolver for &dyn Db {
|
||||
fn path(&self, file: File) -> &str {
|
||||
relativize_path(self.system().current_directory(), file.path(*self).as_str())
|
||||
}
|
||||
|
||||
fn input(&self, file: File) -> Input {
|
||||
Input {
|
||||
text: source_text(*self, file),
|
||||
line_index: line_index(*self, file),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -667,16 +656,9 @@ impl std::fmt::Debug for FileResolver<'_> {
|
||||
/// This contains the actual content of that input as well as a
|
||||
/// line index for efficiently querying its contents.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Input {
|
||||
text: SourceText,
|
||||
line_index: LineIndex,
|
||||
}
|
||||
|
||||
impl Input {
|
||||
/// Returns this input as a `SourceCode` for convenient querying.
|
||||
fn as_source_code(&self) -> SourceCode<'_, '_> {
|
||||
SourceCode::new(self.text.as_str(), &self.line_index)
|
||||
}
|
||||
pub struct Input {
|
||||
pub(crate) text: SourceText,
|
||||
pub(crate) line_index: LineIndex,
|
||||
}
|
||||
|
||||
/// Returns the line number accounting for the given `len`
|
||||
@@ -726,6 +708,7 @@ fn relativize_path<'p>(cwd: &SystemPath, path: &'p str) -> &'p str {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use crate::Upcast;
|
||||
use crate::diagnostic::{Annotation, DiagnosticId, Severity, Span};
|
||||
use crate::files::system_path_to_file;
|
||||
use crate::system::{DbWithWritableSystem, SystemPath};
|
||||
@@ -803,7 +786,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:1
|
||||
|
|
||||
3 | canary
|
||||
@@ -827,7 +810,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
warning: lint:test-diagnostic: main diagnostic message
|
||||
warning[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:1
|
||||
|
|
||||
3 | canary
|
||||
@@ -847,7 +830,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
info: lint:test-diagnostic: main diagnostic message
|
||||
info[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:1
|
||||
|
|
||||
3 | canary
|
||||
@@ -874,7 +857,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:1:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -893,7 +876,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:1:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -914,7 +897,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> non-ascii:5:1
|
||||
|
|
||||
3 | ΔΔΔΔΔΔΔΔΔΔΔΔ
|
||||
@@ -933,7 +916,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> non-ascii:2:2
|
||||
|
|
||||
1 | ☃☃☃☃☃☃☃☃☃☃☃☃
|
||||
@@ -957,7 +940,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:1
|
||||
|
|
||||
4 | dog
|
||||
@@ -974,7 +957,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:1
|
||||
|
|
||||
5 | elephant
|
||||
@@ -989,7 +972,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:1:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -1006,7 +989,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:11:1
|
||||
|
|
||||
9 | inchworm
|
||||
@@ -1023,7 +1006,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -1056,7 +1039,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:1:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -1100,7 +1083,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:1:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -1125,7 +1108,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:1:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -1153,7 +1136,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:1:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -1181,7 +1164,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:1:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -1206,7 +1189,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:1:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -1237,7 +1220,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:1:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -1275,7 +1258,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> spacey-animals:8:1
|
||||
|
|
||||
7 | dog
|
||||
@@ -1292,7 +1275,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> spacey-animals:12:1
|
||||
|
|
||||
11 | gorilla
|
||||
@@ -1310,7 +1293,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> spacey-animals:13:1
|
||||
|
|
||||
11 | gorilla
|
||||
@@ -1350,7 +1333,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> spacey-animals:3:1
|
||||
|
|
||||
3 | beetle
|
||||
@@ -1379,7 +1362,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:3:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -1416,7 +1399,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:3:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -1453,7 +1436,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:3:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -1481,7 +1464,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:3:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -1517,7 +1500,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:3:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -1556,7 +1539,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:3:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -1604,7 +1587,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:3:1
|
||||
|
|
||||
1 | aardvark
|
||||
@@ -1640,7 +1623,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:1
|
||||
|
|
||||
3 | canary
|
||||
@@ -1663,7 +1646,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:1
|
||||
|
|
||||
3 | canary
|
||||
@@ -1683,7 +1666,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:1
|
||||
|
|
||||
3 | canary
|
||||
@@ -1703,7 +1686,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:4
|
||||
|
|
||||
3 | canary
|
||||
@@ -1725,7 +1708,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:4
|
||||
|
|
||||
3 | canary
|
||||
@@ -1757,7 +1740,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:4:1
|
||||
|
|
||||
2 | beetle
|
||||
@@ -1786,7 +1769,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:4:1
|
||||
|
|
||||
2 | beetle
|
||||
@@ -1817,7 +1800,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:1
|
||||
|
|
||||
3 | canary
|
||||
@@ -1852,7 +1835,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:1
|
||||
|
|
||||
3 | canary
|
||||
@@ -1880,7 +1863,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:1
|
||||
|
|
||||
3 | canary
|
||||
@@ -1912,7 +1895,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:3
|
||||
|
|
||||
3 | canary
|
||||
@@ -1934,7 +1917,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:3
|
||||
|
|
||||
3 | canary
|
||||
@@ -1967,7 +1950,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:8:1
|
||||
|
|
||||
6 | finch
|
||||
@@ -2007,7 +1990,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:5:1
|
||||
|
|
||||
5 | elephant
|
||||
@@ -2051,7 +2034,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> fruits:1:1
|
||||
|
|
||||
1 | apple
|
||||
@@ -2086,7 +2069,7 @@ watermelon
|
||||
insta::assert_snapshot!(
|
||||
env.render(&diag),
|
||||
@r"
|
||||
error: lint:test-diagnostic: main diagnostic message
|
||||
error[test-diagnostic]: main diagnostic message
|
||||
--> animals:11:1
|
||||
|
|
||||
11 | kangaroo
|
||||
@@ -2174,8 +2157,9 @@ watermelon
|
||||
fn span(&self, path: &str, line_offset_start: &str, line_offset_end: &str) -> Span {
|
||||
let span = self.path(path);
|
||||
|
||||
let text = source_text(&self.db, span.file());
|
||||
let line_index = line_index(&self.db, span.file());
|
||||
let file = span.expect_ty_file();
|
||||
let text = source_text(&self.db, file);
|
||||
let line_index = line_index(&self.db, file);
|
||||
let source = SourceCode::new(text.as_str(), &line_index);
|
||||
|
||||
let (line_start, offset_start) = parse_line_offset(line_offset_start);
|
||||
@@ -2237,7 +2221,7 @@ watermelon
|
||||
///
|
||||
/// (This will set the "printed" flag on `Diagnostic`.)
|
||||
fn render(&self, diag: &Diagnostic) -> String {
|
||||
diag.display(&self.db, &self.config).to_string()
|
||||
diag.display(&self.db.upcast(), &self.config).to_string()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,12 +11,13 @@ use ruff_text_size::{Ranged, TextRange};
|
||||
use salsa::plumbing::AsId;
|
||||
use salsa::{Durability, Setter};
|
||||
|
||||
use crate::diagnostic::{Span, UnifiedFile};
|
||||
use crate::file_revision::FileRevision;
|
||||
use crate::files::file_root::FileRoots;
|
||||
use crate::files::private::FileStatus;
|
||||
use crate::system::{SystemPath, SystemPathBuf, SystemVirtualPath, SystemVirtualPathBuf};
|
||||
use crate::vendored::{VendoredPath, VendoredPathBuf};
|
||||
use crate::{vendored, Db, FxDashMap};
|
||||
use crate::{Db, FxDashMap, vendored};
|
||||
|
||||
mod file_root;
|
||||
mod path;
|
||||
@@ -277,7 +278,7 @@ impl std::panic::RefUnwindSafe for Files {}
|
||||
#[salsa::input]
|
||||
pub struct File {
|
||||
/// The path of the file (immutable).
|
||||
#[return_ref]
|
||||
#[returns(ref)]
|
||||
pub path: FilePath,
|
||||
|
||||
/// The unix permissions of the file. Only supported on unix systems. Always `None` on Windows
|
||||
@@ -549,10 +550,33 @@ impl Ranged for FileRange {
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&Span> for FileRange {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(value: &Span) -> Result<Self, Self::Error> {
|
||||
let UnifiedFile::Ty(file) = value.file() else {
|
||||
return Err(());
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
file: *file,
|
||||
range: value.range().ok_or(())?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<Span> for FileRange {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(value: Span) -> Result<Self, Self::Error> {
|
||||
Self::try_from(&value)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::file_revision::FileRevision;
|
||||
use crate::files::{system_path_to_file, vendored_path_to_file, FileError};
|
||||
use crate::files::{FileError, system_path_to_file, vendored_path_to_file};
|
||||
use crate::system::DbWithWritableSystem as _;
|
||||
use crate::tests::TestDb;
|
||||
use crate::vendored::VendoredFileSystemBuilder;
|
||||
|
||||
@@ -3,9 +3,9 @@ use std::fmt::Formatter;
|
||||
use path_slash::PathExt;
|
||||
use salsa::Durability;
|
||||
|
||||
use crate::Db;
|
||||
use crate::file_revision::FileRevision;
|
||||
use crate::system::{SystemPath, SystemPathBuf};
|
||||
use crate::Db;
|
||||
|
||||
/// A root path for files tracked by the database.
|
||||
///
|
||||
@@ -19,8 +19,8 @@ use crate::Db;
|
||||
#[salsa::input(debug)]
|
||||
pub struct FileRoot {
|
||||
/// The path of a root is guaranteed to never change.
|
||||
#[return_ref]
|
||||
path_buf: SystemPathBuf,
|
||||
#[returns(deref)]
|
||||
pub path: SystemPathBuf,
|
||||
|
||||
/// The kind of the root at the time of its creation.
|
||||
kind_at_time_of_creation: FileRootKind,
|
||||
@@ -32,10 +32,6 @@ pub struct FileRoot {
|
||||
}
|
||||
|
||||
impl FileRoot {
|
||||
pub fn path(self, db: &dyn Db) -> &SystemPath {
|
||||
self.path_buf(db)
|
||||
}
|
||||
|
||||
pub fn durability(self, db: &dyn Db) -> salsa::Durability {
|
||||
self.kind_at_time_of_creation(db).durability()
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::files::{system_path_to_file, vendored_path_to_file, File};
|
||||
use crate::Db;
|
||||
use crate::files::{File, system_path_to_file, vendored_path_to_file};
|
||||
use crate::system::{SystemPath, SystemPathBuf, SystemVirtualPath, SystemVirtualPathBuf};
|
||||
use crate::vendored::{VendoredPath, VendoredPathBuf};
|
||||
use crate::Db;
|
||||
use std::fmt::{Display, Formatter};
|
||||
|
||||
/// Path to a file.
|
||||
|
||||
@@ -61,13 +61,15 @@ pub fn max_parallelism() -> NonZeroUsize {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::files::Files;
|
||||
use crate::system::TestSystem;
|
||||
use crate::system::{DbWithTestSystem, System};
|
||||
use crate::vendored::VendoredFileSystem;
|
||||
use crate::Db;
|
||||
use crate::{Db, Upcast};
|
||||
|
||||
type Events = Arc<Mutex<Vec<salsa::Event>>>;
|
||||
|
||||
/// Database that can be used for testing.
|
||||
///
|
||||
@@ -79,36 +81,37 @@ mod tests {
|
||||
files: Files,
|
||||
system: TestSystem,
|
||||
vendored: VendoredFileSystem,
|
||||
events: Arc<std::sync::Mutex<Vec<salsa::Event>>>,
|
||||
events: Events,
|
||||
}
|
||||
|
||||
impl TestDb {
|
||||
pub(crate) fn new() -> Self {
|
||||
let events = Events::default();
|
||||
Self {
|
||||
storage: salsa::Storage::default(),
|
||||
storage: salsa::Storage::new(Some(Box::new({
|
||||
let events = events.clone();
|
||||
move |event| {
|
||||
tracing::trace!("event: {:?}", event);
|
||||
let mut events = events.lock().unwrap();
|
||||
events.push(event);
|
||||
}
|
||||
}))),
|
||||
system: TestSystem::default(),
|
||||
vendored: VendoredFileSystem::default(),
|
||||
events: std::sync::Arc::default(),
|
||||
events,
|
||||
files: Files::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Empties the internal store of salsa events that have been emitted,
|
||||
/// and returns them as a `Vec` (equivalent to [`std::mem::take`]).
|
||||
///
|
||||
/// ## Panics
|
||||
/// If there are pending database snapshots.
|
||||
pub(crate) fn take_salsa_events(&mut self) -> Vec<salsa::Event> {
|
||||
let inner = Arc::get_mut(&mut self.events)
|
||||
.expect("expected no pending salsa database snapshots.");
|
||||
let mut events = self.events.lock().unwrap();
|
||||
|
||||
std::mem::take(inner.get_mut().unwrap())
|
||||
std::mem::take(&mut *events)
|
||||
}
|
||||
|
||||
/// Clears the emitted salsa events.
|
||||
///
|
||||
/// ## Panics
|
||||
/// If there are pending database snapshots.
|
||||
pub(crate) fn clear_salsa_events(&mut self) {
|
||||
self.take_salsa_events();
|
||||
}
|
||||
@@ -133,7 +136,16 @@ mod tests {
|
||||
}
|
||||
|
||||
fn python_version(&self) -> ruff_python_ast::PythonVersion {
|
||||
ruff_python_ast::PythonVersion::latest()
|
||||
ruff_python_ast::PythonVersion::latest_ty()
|
||||
}
|
||||
}
|
||||
|
||||
impl Upcast<dyn Db> for TestDb {
|
||||
fn upcast(&self) -> &(dyn Db + 'static) {
|
||||
self
|
||||
}
|
||||
fn upcast_mut(&mut self) -> &mut (dyn Db + 'static) {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,12 +160,5 @@ mod tests {
|
||||
}
|
||||
|
||||
#[salsa::db]
|
||||
impl salsa::Database for TestDb {
|
||||
fn salsa_event(&self, event: &dyn Fn() -> salsa::Event) {
|
||||
let event = event();
|
||||
tracing::trace!("event: {:?}", event);
|
||||
let mut events = self.events.lock().unwrap();
|
||||
events.push(event);
|
||||
}
|
||||
}
|
||||
impl salsa::Database for TestDb {}
|
||||
}
|
||||
|
||||
@@ -3,11 +3,11 @@ use std::ops::Deref;
|
||||
use std::sync::Arc;
|
||||
|
||||
use ruff_python_ast::ModModule;
|
||||
use ruff_python_parser::{parse_unchecked, ParseOptions, Parsed};
|
||||
use ruff_python_parser::{ParseOptions, Parsed, parse_unchecked};
|
||||
|
||||
use crate::Db;
|
||||
use crate::files::File;
|
||||
use crate::source::source_text;
|
||||
use crate::Db;
|
||||
|
||||
/// Returns the parsed AST of `file`, including its token stream.
|
||||
///
|
||||
@@ -20,7 +20,7 @@ use crate::Db;
|
||||
/// reflected in the changed AST offsets.
|
||||
/// The other reason is that Ruff's AST doesn't implement `Eq` which Sala requires
|
||||
/// for determining if a query result is unchanged.
|
||||
#[salsa::tracked(return_ref, no_eq)]
|
||||
#[salsa::tracked(returns(ref), no_eq)]
|
||||
pub fn parsed_module(db: &dyn Db, file: File) -> ParsedModule {
|
||||
let _span = tracing::trace_span!("parsed_module", ?file).entered();
|
||||
|
||||
@@ -79,6 +79,7 @@ impl Eq for ParsedModule {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::Db;
|
||||
use crate::files::{system_path_to_file, vendored_path_to_file};
|
||||
use crate::parsed::parsed_module;
|
||||
use crate::system::{
|
||||
@@ -86,7 +87,6 @@ mod tests {
|
||||
};
|
||||
use crate::tests::TestDb;
|
||||
use crate::vendored::{VendoredFileSystemBuilder, VendoredPath};
|
||||
use crate::Db;
|
||||
use zip::CompressionMethod;
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -7,8 +7,8 @@ use ruff_notebook::Notebook;
|
||||
use ruff_python_ast::PySourceType;
|
||||
use ruff_source_file::LineIndex;
|
||||
|
||||
use crate::files::{File, FilePath};
|
||||
use crate::Db;
|
||||
use crate::files::{File, FilePath};
|
||||
|
||||
/// Reads the source text of a python text file (must be valid UTF8) or notebook.
|
||||
#[salsa::tracked]
|
||||
@@ -133,7 +133,7 @@ struct SourceTextInner {
|
||||
#[derive(Eq, PartialEq)]
|
||||
enum SourceTextKind {
|
||||
Text(String),
|
||||
Notebook(Notebook),
|
||||
Notebook(Box<Notebook>),
|
||||
}
|
||||
|
||||
impl From<String> for SourceTextKind {
|
||||
@@ -144,7 +144,7 @@ impl From<String> for SourceTextKind {
|
||||
|
||||
impl From<Notebook> for SourceTextKind {
|
||||
fn from(notebook: Notebook) -> Self {
|
||||
SourceTextKind::Notebook(notebook)
|
||||
SourceTextKind::Notebook(Box::new(notebook))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,9 +216,11 @@ mod tests {
|
||||
|
||||
let events = db.take_salsa_events();
|
||||
|
||||
assert!(!events
|
||||
.iter()
|
||||
.any(|event| matches!(event.kind, EventKind::WillExecute { .. })));
|
||||
assert!(
|
||||
!events
|
||||
.iter()
|
||||
.any(|event| matches!(event.kind, EventKind::WillExecute { .. }))
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -19,8 +19,8 @@ use walk_directory::WalkDirectoryBuilder;
|
||||
use crate::file_revision::FileRevision;
|
||||
|
||||
pub use self::path::{
|
||||
deduplicate_nested_paths, DeduplicatedNestedPathsIter, SystemPath, SystemPathBuf,
|
||||
SystemVirtualPath, SystemVirtualPathBuf,
|
||||
DeduplicatedNestedPathsIter, SystemPath, SystemPathBuf, SystemVirtualPath,
|
||||
SystemVirtualPathBuf, deduplicate_nested_paths,
|
||||
};
|
||||
|
||||
mod memory_fs;
|
||||
@@ -167,7 +167,7 @@ pub trait System: Debug {
|
||||
&self,
|
||||
pattern: &str,
|
||||
) -> std::result::Result<
|
||||
Box<dyn Iterator<Item = std::result::Result<SystemPathBuf, GlobError>>>,
|
||||
Box<dyn Iterator<Item = std::result::Result<SystemPathBuf, GlobError>> + '_>,
|
||||
PatternError,
|
||||
>;
|
||||
|
||||
|
||||
@@ -7,8 +7,8 @@ use filetime::FileTime;
|
||||
use rustc_hash::FxHashMap;
|
||||
|
||||
use crate::system::{
|
||||
file_time_now, walk_directory, DirectoryEntry, FileType, GlobError, GlobErrorKind, Metadata,
|
||||
Result, SystemPath, SystemPathBuf, SystemVirtualPath, SystemVirtualPathBuf,
|
||||
DirectoryEntry, FileType, GlobError, GlobErrorKind, Metadata, Result, SystemPath,
|
||||
SystemPathBuf, SystemVirtualPath, SystemVirtualPathBuf, file_time_now, walk_directory,
|
||||
};
|
||||
|
||||
use super::walk_directory::{
|
||||
@@ -236,7 +236,7 @@ impl MemoryFileSystem {
|
||||
&self,
|
||||
pattern: &str,
|
||||
) -> std::result::Result<
|
||||
impl Iterator<Item = std::result::Result<SystemPathBuf, GlobError>>,
|
||||
impl Iterator<Item = std::result::Result<SystemPathBuf, GlobError>> + '_,
|
||||
glob::PatternError,
|
||||
> {
|
||||
// Very naive implementation that iterates over all files and collects all that match the given pattern.
|
||||
@@ -463,17 +463,17 @@ fn not_found() -> std::io::Error {
|
||||
fn is_a_directory() -> std::io::Error {
|
||||
// Note: Rust returns `ErrorKind::IsADirectory` for this error but this is a nightly only variant :(.
|
||||
// So we have to use other for now.
|
||||
std::io::Error::new(std::io::ErrorKind::Other, "Is a directory")
|
||||
std::io::Error::other("Is a directory")
|
||||
}
|
||||
|
||||
fn not_a_directory() -> std::io::Error {
|
||||
// Note: Rust returns `ErrorKind::NotADirectory` for this error but this is a nightly only variant :(.
|
||||
// So we have to use `Other` for now.
|
||||
std::io::Error::new(std::io::ErrorKind::Other, "Not a directory")
|
||||
std::io::Error::other("Not a directory")
|
||||
}
|
||||
|
||||
fn directory_not_empty() -> std::io::Error {
|
||||
std::io::Error::new(std::io::ErrorKind::Other, "directory not empty")
|
||||
std::io::Error::other("directory not empty")
|
||||
}
|
||||
|
||||
fn create_dir_all(
|
||||
@@ -701,8 +701,8 @@ mod tests {
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::system::walk_directory::tests::DirectoryEntryToString;
|
||||
use crate::system::walk_directory::WalkState;
|
||||
use crate::system::walk_directory::tests::DirectoryEntryToString;
|
||||
use crate::system::{
|
||||
DirectoryEntry, FileType, MemoryFileSystem, Result, SystemPath, SystemPathBuf,
|
||||
SystemVirtualPath,
|
||||
|
||||
@@ -256,7 +256,9 @@ impl OsSystem {
|
||||
let Ok(canonicalized) = SystemPathBuf::from_path_buf(canonicalized) else {
|
||||
// The original path is valid UTF8 but the canonicalized path isn't. This definitely suggests
|
||||
// that a symlink is involved. Fall back to the slow path.
|
||||
tracing::debug!("Falling back to the slow case-sensitive path existence check because the canonicalized path of `{simplified}` is not valid UTF-8");
|
||||
tracing::debug!(
|
||||
"Falling back to the slow case-sensitive path existence check because the canonicalized path of `{simplified}` is not valid UTF-8"
|
||||
);
|
||||
return None;
|
||||
};
|
||||
|
||||
@@ -266,7 +268,9 @@ impl OsSystem {
|
||||
// `path` pointed to a symlink (or some other none reversible path normalization happened).
|
||||
// In this case, fall back to the slow path.
|
||||
if simplified_canonicalized.as_str().to_lowercase() != simplified.as_str().to_lowercase() {
|
||||
tracing::debug!("Falling back to the slow case-sensitive path existence check for `{simplified}` because the canonicalized path `{simplified_canonicalized}` differs not only by casing");
|
||||
tracing::debug!(
|
||||
"Falling back to the slow case-sensitive path existence check for `{simplified}` because the canonicalized path `{simplified_canonicalized}` differs not only by casing"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -662,8 +666,8 @@ fn detect_case_sensitivity(path: &SystemPath) -> CaseSensitivity {
|
||||
mod tests {
|
||||
use tempfile::TempDir;
|
||||
|
||||
use crate::system::walk_directory::tests::DirectoryEntryToString;
|
||||
use crate::system::DirectoryEntry;
|
||||
use crate::system::walk_directory::tests::DirectoryEntryToString;
|
||||
|
||||
use super::*;
|
||||
|
||||
|
||||
@@ -3,15 +3,15 @@ use ruff_notebook::{Notebook, NotebookError};
|
||||
use std::panic::RefUnwindSafe;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::Db;
|
||||
use crate::files::File;
|
||||
use crate::system::{
|
||||
CaseSensitivity, DirectoryEntry, GlobError, MemoryFileSystem, Metadata, Result, System,
|
||||
SystemPath, SystemPathBuf, SystemVirtualPath,
|
||||
};
|
||||
use crate::Db;
|
||||
|
||||
use super::walk_directory::WalkDirectoryBuilder;
|
||||
use super::WritableSystem;
|
||||
use super::walk_directory::WalkDirectoryBuilder;
|
||||
|
||||
/// System implementation intended for testing.
|
||||
///
|
||||
@@ -117,7 +117,7 @@ impl System for TestSystem {
|
||||
&self,
|
||||
pattern: &str,
|
||||
) -> std::result::Result<
|
||||
Box<dyn Iterator<Item = std::result::Result<SystemPathBuf, GlobError>>>,
|
||||
Box<dyn Iterator<Item = std::result::Result<SystemPathBuf, GlobError>> + '_>,
|
||||
PatternError,
|
||||
> {
|
||||
self.system().glob(pattern)
|
||||
@@ -343,7 +343,7 @@ impl System for InMemorySystem {
|
||||
&self,
|
||||
pattern: &str,
|
||||
) -> std::result::Result<
|
||||
Box<dyn Iterator<Item = std::result::Result<SystemPathBuf, GlobError>>>,
|
||||
Box<dyn Iterator<Item = std::result::Result<SystemPathBuf, GlobError>> + '_>,
|
||||
PatternError,
|
||||
> {
|
||||
let iterator = self.memory_fs.glob(pattern)?;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Test helpers for working with Salsa databases
|
||||
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
|
||||
pub fn assert_function_query_was_not_run<Db, Q, QDb, I, R>(
|
||||
db: &Db,
|
||||
@@ -141,7 +141,6 @@ pub fn setup_logging_with_filter(filter: &str) -> Option<LoggingGuard> {
|
||||
#[derive(Debug)]
|
||||
pub struct LoggingBuilder {
|
||||
filter: EnvFilter,
|
||||
hierarchical: bool,
|
||||
}
|
||||
|
||||
impl LoggingBuilder {
|
||||
@@ -154,50 +153,26 @@ impl LoggingBuilder {
|
||||
.parse()
|
||||
.expect("Hardcoded directive to be valid"),
|
||||
),
|
||||
hierarchical: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_filter(filter: &str) -> Option<Self> {
|
||||
let filter = EnvFilter::builder().parse(filter).ok()?;
|
||||
|
||||
Some(Self {
|
||||
filter,
|
||||
hierarchical: false,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn with_hierarchical(mut self, hierarchical: bool) -> Self {
|
||||
self.hierarchical = hierarchical;
|
||||
self
|
||||
Some(Self { filter })
|
||||
}
|
||||
|
||||
pub fn build(self) -> LoggingGuard {
|
||||
let registry = tracing_subscriber::registry().with(self.filter);
|
||||
|
||||
let guard = if self.hierarchical {
|
||||
let subscriber = registry.with(
|
||||
tracing_tree::HierarchicalLayer::default()
|
||||
.with_indent_lines(true)
|
||||
.with_indent_amount(2)
|
||||
.with_bracketed_fields(true)
|
||||
.with_thread_ids(true)
|
||||
.with_targets(true)
|
||||
.with_writer(std::io::stderr)
|
||||
.with_timer(tracing_tree::time::Uptime::default()),
|
||||
);
|
||||
let subscriber = registry.with(
|
||||
tracing_subscriber::fmt::layer()
|
||||
.compact()
|
||||
.with_writer(std::io::stderr)
|
||||
.with_timer(tracing_subscriber::fmt::time()),
|
||||
);
|
||||
|
||||
tracing::subscriber::set_default(subscriber)
|
||||
} else {
|
||||
let subscriber = registry.with(
|
||||
tracing_subscriber::fmt::layer()
|
||||
.compact()
|
||||
.with_writer(std::io::stderr)
|
||||
.with_timer(tracing_subscriber::fmt::time()),
|
||||
);
|
||||
|
||||
tracing::subscriber::set_default(subscriber)
|
||||
};
|
||||
let guard = tracing::subscriber::set_default(subscriber);
|
||||
|
||||
LoggingGuard { _guard: guard }
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use crate::file_revision::FileRevision;
|
||||
use zip::result::ZipResult;
|
||||
use zip::write::FileOptions;
|
||||
use zip::{read::ZipFile, CompressionMethod, ZipArchive, ZipWriter};
|
||||
use zip::{CompressionMethod, ZipArchive, ZipWriter, read::ZipFile};
|
||||
|
||||
pub use self::path::{VendoredPath, VendoredPathBuf};
|
||||
|
||||
@@ -503,9 +503,11 @@ pub(crate) mod tests {
|
||||
let path = VendoredPath::new(path);
|
||||
assert!(!mock_typeshed.exists(path));
|
||||
assert!(mock_typeshed.metadata(path).is_err());
|
||||
assert!(mock_typeshed
|
||||
.read_to_string(path)
|
||||
.is_err_and(|err| err.to_string().contains("file not found")));
|
||||
assert!(
|
||||
mock_typeshed
|
||||
.read_to_string(path)
|
||||
.is_err_and(|err| err.to_string().contains("file not found"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -11,12 +11,14 @@ repository = { workspace = true }
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
ty = { workspace = true }
|
||||
ty_project = { workspace = true, features = ["schemars"] }
|
||||
ruff = { workspace = true }
|
||||
ruff_diagnostics = { workspace = true }
|
||||
ruff_formatter = { workspace = true }
|
||||
ruff_linter = { workspace = true, features = ["schemars"] }
|
||||
ruff_notebook = { workspace = true }
|
||||
ruff_options_metadata = { workspace = true }
|
||||
ruff_python_ast = { workspace = true }
|
||||
ruff_python_codegen = { workspace = true }
|
||||
ruff_python_formatter = { workspace = true }
|
||||
@@ -31,6 +33,7 @@ imara-diff = { workspace = true }
|
||||
indicatif = { workspace = true }
|
||||
itertools = { workspace = true }
|
||||
libcst = { workspace = true }
|
||||
markdown = { version = "1.0.0" }
|
||||
pretty_assertions = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
regex = { workspace = true }
|
||||
@@ -44,6 +47,7 @@ toml = { workspace = true, features = ["parse"] }
|
||||
tracing = { workspace = true }
|
||||
tracing-indicatif = { workspace = true }
|
||||
tracing-subscriber = { workspace = true, features = ["env-filter"] }
|
||||
url = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
indoc = { workspace = true }
|
||||
|
||||
@@ -9,11 +9,11 @@ use std::process::ExitCode;
|
||||
use std::time::{Duration, Instant};
|
||||
use std::{fmt, fs, io, iter};
|
||||
|
||||
use anyhow::{bail, format_err, Context, Error};
|
||||
use anyhow::{Context, Error, bail, format_err};
|
||||
use clap::{CommandFactory, FromArgMatches};
|
||||
use imara_diff::intern::InternedInput;
|
||||
use imara_diff::sink::Counter;
|
||||
use imara_diff::{diff, Algorithm};
|
||||
use imara_diff::{Algorithm, diff};
|
||||
use indicatif::ProgressStyle;
|
||||
#[cfg_attr(feature = "singlethreaded", allow(unused_imports))]
|
||||
use rayon::iter::{IntoParallelIterator, ParallelIterator};
|
||||
@@ -21,11 +21,11 @@ use serde::Deserialize;
|
||||
use similar::{ChangeTag, TextDiff};
|
||||
use tempfile::NamedTempFile;
|
||||
use tracing::{debug, error, info, info_span};
|
||||
use tracing_indicatif::span_ext::IndicatifSpanExt;
|
||||
use tracing_indicatif::IndicatifLayer;
|
||||
use tracing_indicatif::span_ext::IndicatifSpanExt;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
use ruff::args::{ConfigArguments, FormatArguments, FormatCommand, GlobalConfigArgs, LogLevelArgs};
|
||||
use ruff::resolve::resolve;
|
||||
@@ -33,10 +33,10 @@ use ruff_formatter::{FormatError, LineWidth, PrintError};
|
||||
use ruff_linter::logging::LogLevel;
|
||||
use ruff_linter::settings::types::{FilePattern, FilePatternSet};
|
||||
use ruff_python_formatter::{
|
||||
format_module_source, FormatModuleError, MagicTrailingComma, PreviewMode, PyFormatOptions,
|
||||
FormatModuleError, MagicTrailingComma, PreviewMode, PyFormatOptions, format_module_source,
|
||||
};
|
||||
use ruff_python_parser::ParseError;
|
||||
use ruff_workspace::resolver::{python_files_in_path, PyprojectConfig, ResolvedFile, Resolver};
|
||||
use ruff_workspace::resolver::{PyprojectConfig, ResolvedFile, Resolver, python_files_in_path};
|
||||
|
||||
fn parse_cli(dirs: &[PathBuf]) -> anyhow::Result<(FormatArguments, ConfigArguments)> {
|
||||
let args_matches = FormatCommand::command()
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
use anyhow::Result;
|
||||
|
||||
use crate::{generate_cli_help, generate_docs, generate_json_schema, generate_ty_schema};
|
||||
use crate::{
|
||||
generate_cli_help, generate_docs, generate_json_schema, generate_ty_cli_reference,
|
||||
generate_ty_options, generate_ty_rules, generate_ty_schema,
|
||||
};
|
||||
|
||||
pub(crate) const REGENERATE_ALL_COMMAND: &str = "cargo dev generate-all";
|
||||
|
||||
@@ -38,5 +41,8 @@ pub(crate) fn main(args: &Args) -> Result<()> {
|
||||
generate_docs::main(&generate_docs::Args {
|
||||
dry_run: args.mode.is_dry_run(),
|
||||
})?;
|
||||
generate_ty_options::main(&generate_ty_options::Args { mode: args.mode })?;
|
||||
generate_ty_rules::main(&generate_ty_rules::Args { mode: args.mode })?;
|
||||
generate_ty_cli_reference::main(&generate_ty_cli_reference::Args { mode: args.mode })?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
//! Generate CLI help.
|
||||
#![allow(clippy::print_stdout)]
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::{fs, str};
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::CommandFactory;
|
||||
use pretty_assertions::StrComparison;
|
||||
|
||||
use ruff::args;
|
||||
|
||||
use crate::generate_all::{Mode, REGENERATE_ALL_COMMAND};
|
||||
use crate::ROOT_DIR;
|
||||
use crate::generate_all::{Mode, REGENERATE_ALL_COMMAND};
|
||||
|
||||
const COMMAND_HELP_BEGIN_PRAGMA: &str = "<!-- Begin auto-generated command help. -->\n";
|
||||
const COMMAND_HELP_END_PRAGMA: &str = "<!-- End auto-generated command help. -->";
|
||||
@@ -141,7 +140,7 @@ mod tests {
|
||||
|
||||
use crate::generate_all::Mode;
|
||||
|
||||
use super::{main, Args};
|
||||
use super::{Args, main};
|
||||
|
||||
#[test]
|
||||
fn test_generate_json_schema() -> Result<()> {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Generate Markdown documentation for applicable rules.
|
||||
#![allow(clippy::print_stdout, clippy::print_stderr)]
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fmt::Write as _;
|
||||
@@ -13,8 +12,8 @@ use strum::IntoEnumIterator;
|
||||
|
||||
use ruff_diagnostics::FixAvailability;
|
||||
use ruff_linter::registry::{Linter, Rule, RuleNamespace};
|
||||
use ruff_options_metadata::{OptionEntry, OptionsMetadata};
|
||||
use ruff_workspace::options::Options;
|
||||
use ruff_workspace::options_base::{OptionEntry, OptionsMetadata};
|
||||
|
||||
use crate::ROOT_DIR;
|
||||
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
#![allow(clippy::print_stdout, clippy::print_stderr)]
|
||||
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use anyhow::{Result, bail};
|
||||
use pretty_assertions::StrComparison;
|
||||
use schemars::schema_for;
|
||||
|
||||
use crate::generate_all::{Mode, REGENERATE_ALL_COMMAND};
|
||||
use crate::ROOT_DIR;
|
||||
use crate::generate_all::{Mode, REGENERATE_ALL_COMMAND};
|
||||
use ruff_workspace::options::Options;
|
||||
|
||||
#[derive(clap::Args)]
|
||||
@@ -58,7 +56,7 @@ mod tests {
|
||||
|
||||
use crate::generate_all::Mode;
|
||||
|
||||
use super::{main, Args};
|
||||
use super::{Args, main};
|
||||
|
||||
#[test]
|
||||
fn test_generate_json_schema() -> Result<()> {
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
use itertools::Itertools;
|
||||
use std::fmt::Write;
|
||||
|
||||
use ruff_options_metadata::{OptionField, OptionSet, OptionsMetadata, Visit};
|
||||
use ruff_python_trivia::textwrap;
|
||||
use ruff_workspace::options::Options;
|
||||
use ruff_workspace::options_base::{OptionField, OptionSet, OptionsMetadata, Visit};
|
||||
|
||||
pub(crate) fn generate() -> String {
|
||||
let mut output = String::new();
|
||||
@@ -100,8 +100,8 @@ fn emit_field(output: &mut String, name: &str, field: &OptionField, parents: &[S
|
||||
if parents_anchor.is_empty() {
|
||||
let _ = writeln!(output, "{header_level} [`{name}`](#{name}) {{: #{name} }}");
|
||||
} else {
|
||||
let _ =
|
||||
writeln!(output,
|
||||
let _ = writeln!(
|
||||
output,
|
||||
"{header_level} [`{name}`](#{parents_anchor}_{name}) {{: #{parents_anchor}_{name} }}"
|
||||
);
|
||||
|
||||
|
||||
@@ -11,8 +11,8 @@ use strum::IntoEnumIterator;
|
||||
use ruff_diagnostics::FixAvailability;
|
||||
use ruff_linter::registry::{Linter, Rule, RuleNamespace};
|
||||
use ruff_linter::upstream_categories::UpstreamCategoryAndPrefix;
|
||||
use ruff_options_metadata::OptionsMetadata;
|
||||
use ruff_workspace::options::Options;
|
||||
use ruff_workspace::options_base::OptionsMetadata;
|
||||
|
||||
const FIX_SYMBOL: &str = "🛠️";
|
||||
const PREVIEW_SYMBOL: &str = "🧪";
|
||||
@@ -48,7 +48,9 @@ fn generate_table(table_out: &mut String, rules: impl IntoIterator<Item = Rule>,
|
||||
format!("<span title='Automatic fix available'>{FIX_SYMBOL}</span>")
|
||||
}
|
||||
FixAvailability::None => {
|
||||
format!("<span title='Automatic fix not available' style='opacity: 0.1' aria-hidden='true'>{FIX_SYMBOL}</span>")
|
||||
format!(
|
||||
"<span title='Automatic fix not available' style='opacity: 0.1' aria-hidden='true'>{FIX_SYMBOL}</span>"
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -108,22 +110,26 @@ pub(crate) fn generate() -> String {
|
||||
);
|
||||
table_out.push_str("<br />");
|
||||
|
||||
let _ = write!(&mut table_out,
|
||||
let _ = write!(
|
||||
&mut table_out,
|
||||
"{SPACER}{PREVIEW_SYMBOL}{SPACER} The rule is unstable and is in [\"preview\"](faq.md#what-is-preview)."
|
||||
);
|
||||
table_out.push_str("<br />");
|
||||
|
||||
let _ = write!(&mut table_out,
|
||||
let _ = write!(
|
||||
&mut table_out,
|
||||
"{SPACER}{WARNING_SYMBOL}{SPACER} The rule has been deprecated and will be removed in a future release."
|
||||
);
|
||||
table_out.push_str("<br />");
|
||||
|
||||
let _ = write!(&mut table_out,
|
||||
let _ = write!(
|
||||
&mut table_out,
|
||||
"{SPACER}{REMOVED_SYMBOL}{SPACER} The rule has been removed only the documentation is available."
|
||||
);
|
||||
table_out.push_str("<br />");
|
||||
|
||||
let _ = write!(&mut table_out,
|
||||
let _ = write!(
|
||||
&mut table_out,
|
||||
"{SPACER}{FIX_SYMBOL}{SPACER} The rule is automatically fixable by the `--fix` command-line option."
|
||||
);
|
||||
table_out.push_str("<br />");
|
||||
|
||||
334
crates/ruff_dev/src/generate_ty_cli_reference.rs
Normal file
334
crates/ruff_dev/src/generate_ty_cli_reference.rs
Normal file
@@ -0,0 +1,334 @@
|
||||
//! Generate a Markdown-compatible reference for the ty command-line interface.
|
||||
use std::cmp::max;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use clap::{Command, CommandFactory};
|
||||
use itertools::Itertools;
|
||||
use pretty_assertions::StrComparison;
|
||||
|
||||
use crate::ROOT_DIR;
|
||||
use crate::generate_all::{Mode, REGENERATE_ALL_COMMAND};
|
||||
|
||||
use ty::Cli;
|
||||
|
||||
const SHOW_HIDDEN_COMMANDS: &[&str] = &["generate-shell-completion"];
|
||||
|
||||
#[derive(clap::Args)]
|
||||
pub(crate) struct Args {
|
||||
#[arg(long, default_value_t, value_enum)]
|
||||
pub(crate) mode: Mode,
|
||||
}
|
||||
|
||||
pub(crate) fn main(args: &Args) -> Result<()> {
|
||||
let reference_string = generate();
|
||||
let filename = "crates/ty/docs/cli.md";
|
||||
let reference_path = PathBuf::from(ROOT_DIR).join(filename);
|
||||
|
||||
match args.mode {
|
||||
Mode::DryRun => {
|
||||
println!("{reference_string}");
|
||||
}
|
||||
Mode::Check => match std::fs::read_to_string(reference_path) {
|
||||
Ok(current) => {
|
||||
if current == reference_string {
|
||||
println!("Up-to-date: {filename}");
|
||||
} else {
|
||||
let comparison = StrComparison::new(¤t, &reference_string);
|
||||
bail!(
|
||||
"{filename} changed, please run `{REGENERATE_ALL_COMMAND}`:\n{comparison}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
|
||||
bail!("{filename} not found, please run `{REGENERATE_ALL_COMMAND}`");
|
||||
}
|
||||
Err(err) => {
|
||||
bail!("{filename} changed, please run `{REGENERATE_ALL_COMMAND}`:\n{err}");
|
||||
}
|
||||
},
|
||||
Mode::Write => match std::fs::read_to_string(&reference_path) {
|
||||
Ok(current) => {
|
||||
if current == reference_string {
|
||||
println!("Up-to-date: {filename}");
|
||||
} else {
|
||||
println!("Updating: {filename}");
|
||||
std::fs::write(reference_path, reference_string.as_bytes())?;
|
||||
}
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
|
||||
println!("Updating: {filename}");
|
||||
std::fs::write(reference_path, reference_string.as_bytes())?;
|
||||
}
|
||||
Err(err) => {
|
||||
bail!("{filename} changed, please run `cargo dev generate-cli-reference`:\n{err}");
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn generate() -> String {
|
||||
let mut output = String::new();
|
||||
|
||||
let mut ty = Cli::command();
|
||||
|
||||
// It is very important to build the command before beginning inspection or subcommands
|
||||
// will be missing all of the propagated options.
|
||||
ty.build();
|
||||
|
||||
let mut parents = Vec::new();
|
||||
|
||||
output.push_str("# CLI Reference\n\n");
|
||||
generate_command(&mut output, &ty, &mut parents);
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
#[allow(clippy::format_push_string)]
|
||||
fn generate_command<'a>(output: &mut String, command: &'a Command, parents: &mut Vec<&'a Command>) {
|
||||
if command.is_hide_set() && !SHOW_HIDDEN_COMMANDS.contains(&command.get_name()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Generate the command header.
|
||||
let name = if parents.is_empty() {
|
||||
command.get_name().to_string()
|
||||
} else {
|
||||
format!(
|
||||
"{} {}",
|
||||
parents.iter().map(|cmd| cmd.get_name()).join(" "),
|
||||
command.get_name()
|
||||
)
|
||||
};
|
||||
|
||||
// Display the top-level `ty` command at the same level as its children
|
||||
let level = max(2, parents.len() + 1);
|
||||
output.push_str(&format!("{} {name}\n\n", "#".repeat(level)));
|
||||
|
||||
// Display the command description.
|
||||
if let Some(about) = command.get_long_about().or_else(|| command.get_about()) {
|
||||
output.push_str(&about.to_string());
|
||||
output.push_str("\n\n");
|
||||
}
|
||||
|
||||
// Display the usage
|
||||
{
|
||||
// This appears to be the simplest way to get rendered usage from Clap,
|
||||
// it is complicated to render it manually. It's annoying that it
|
||||
// requires a mutable reference but it doesn't really matter.
|
||||
let mut command = command.clone();
|
||||
output.push_str("<h3 class=\"cli-reference\">Usage</h3>\n\n");
|
||||
output.push_str(&format!(
|
||||
"```\n{}\n```",
|
||||
command
|
||||
.render_usage()
|
||||
.to_string()
|
||||
.trim_start_matches("Usage: "),
|
||||
));
|
||||
output.push_str("\n\n");
|
||||
}
|
||||
|
||||
if command.get_name() == "help" {
|
||||
return;
|
||||
}
|
||||
|
||||
// Display a list of child commands
|
||||
let mut subcommands = command.get_subcommands().peekable();
|
||||
let has_subcommands = subcommands.peek().is_some();
|
||||
if has_subcommands {
|
||||
output.push_str("<h3 class=\"cli-reference\">Commands</h3>\n\n");
|
||||
output.push_str("<dl class=\"cli-reference\">");
|
||||
|
||||
for subcommand in subcommands {
|
||||
if subcommand.is_hide_set() {
|
||||
continue;
|
||||
}
|
||||
let subcommand_name = format!("{name} {}", subcommand.get_name());
|
||||
output.push_str(&format!(
|
||||
"<dt><a href=\"#{}\"><code>{subcommand_name}</code></a></dt>",
|
||||
subcommand_name.replace(' ', "-")
|
||||
));
|
||||
if let Some(about) = subcommand.get_about() {
|
||||
output.push_str(&format!(
|
||||
"<dd>{}</dd>\n",
|
||||
markdown::to_html(&about.to_string())
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
output.push_str("</dl>\n\n");
|
||||
}
|
||||
|
||||
// Do not display options for commands with children
|
||||
if !has_subcommands {
|
||||
let name_key = name.replace(' ', "-");
|
||||
|
||||
// Display positional arguments
|
||||
let mut arguments = command
|
||||
.get_positionals()
|
||||
.filter(|arg| !arg.is_hide_set())
|
||||
.peekable();
|
||||
|
||||
if arguments.peek().is_some() {
|
||||
output.push_str("<h3 class=\"cli-reference\">Arguments</h3>\n\n");
|
||||
output.push_str("<dl class=\"cli-reference\">");
|
||||
|
||||
for arg in arguments {
|
||||
let id = format!("{name_key}--{}", arg.get_id());
|
||||
output.push_str(&format!("<dt id=\"{id}\">"));
|
||||
output.push_str(&format!(
|
||||
"<a href=\"#{id}\"><code>{}</code></a>",
|
||||
arg.get_id().to_string().to_uppercase(),
|
||||
));
|
||||
output.push_str("</dt>");
|
||||
if let Some(help) = arg.get_long_help().or_else(|| arg.get_help()) {
|
||||
output.push_str("<dd>");
|
||||
output.push_str(&format!("{}\n", markdown::to_html(&help.to_string())));
|
||||
output.push_str("</dd>");
|
||||
}
|
||||
}
|
||||
|
||||
output.push_str("</dl>\n\n");
|
||||
}
|
||||
|
||||
// Display options and flags
|
||||
let mut options = command
|
||||
.get_arguments()
|
||||
.filter(|arg| !arg.is_positional())
|
||||
.filter(|arg| !arg.is_hide_set())
|
||||
.sorted_by_key(|arg| arg.get_id())
|
||||
.peekable();
|
||||
|
||||
if options.peek().is_some() {
|
||||
output.push_str("<h3 class=\"cli-reference\">Options</h3>\n\n");
|
||||
output.push_str("<dl class=\"cli-reference\">");
|
||||
for opt in options {
|
||||
let Some(long) = opt.get_long() else { continue };
|
||||
let id = format!("{name_key}--{long}");
|
||||
|
||||
output.push_str(&format!("<dt id=\"{id}\">"));
|
||||
output.push_str(&format!("<a href=\"#{id}\"><code>--{long}</code></a>"));
|
||||
for long_alias in opt.get_all_aliases().into_iter().flatten() {
|
||||
output.push_str(&format!(", <code>--{long_alias}</code>"));
|
||||
}
|
||||
if let Some(short) = opt.get_short() {
|
||||
output.push_str(&format!(", <code>-{short}</code>"));
|
||||
}
|
||||
for short_alias in opt.get_all_short_aliases().into_iter().flatten() {
|
||||
output.push_str(&format!(", <code>-{short_alias}</code>"));
|
||||
}
|
||||
|
||||
// Re-implements private `Arg::is_takes_value_set` used in `Command::get_opts`
|
||||
if opt
|
||||
.get_num_args()
|
||||
.unwrap_or_else(|| 1.into())
|
||||
.takes_values()
|
||||
{
|
||||
if let Some(values) = opt.get_value_names() {
|
||||
for value in values {
|
||||
output.push_str(&format!(
|
||||
" <i>{}</i>",
|
||||
value.to_lowercase().replace('_', "-")
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
output.push_str("</dt>");
|
||||
if let Some(help) = opt.get_long_help().or_else(|| opt.get_help()) {
|
||||
output.push_str("<dd>");
|
||||
output.push_str(&format!("{}\n", markdown::to_html(&help.to_string())));
|
||||
emit_env_option(opt, output);
|
||||
emit_default_option(opt, output);
|
||||
emit_possible_options(opt, output);
|
||||
output.push_str("</dd>");
|
||||
}
|
||||
}
|
||||
|
||||
output.push_str("</dl>");
|
||||
}
|
||||
|
||||
output.push_str("\n\n");
|
||||
}
|
||||
|
||||
parents.push(command);
|
||||
|
||||
// Recurse to all of the subcommands.
|
||||
for subcommand in command.get_subcommands() {
|
||||
generate_command(output, subcommand, parents);
|
||||
}
|
||||
|
||||
parents.pop();
|
||||
}
|
||||
|
||||
fn emit_env_option(opt: &clap::Arg, output: &mut String) {
|
||||
if opt.is_hide_env_set() {
|
||||
return;
|
||||
}
|
||||
if let Some(env) = opt.get_env() {
|
||||
output.push_str(&markdown::to_html(&format!(
|
||||
"May also be set with the `{}` environment variable.",
|
||||
env.to_string_lossy()
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_default_option(opt: &clap::Arg, output: &mut String) {
|
||||
if opt.is_hide_default_value_set() || !opt.get_num_args().expect("built").takes_values() {
|
||||
return;
|
||||
}
|
||||
|
||||
let values = opt.get_default_values();
|
||||
if !values.is_empty() {
|
||||
let value = format!(
|
||||
"\n[default: {}]",
|
||||
opt.get_default_values()
|
||||
.iter()
|
||||
.map(|s| s.to_string_lossy())
|
||||
.join(",")
|
||||
);
|
||||
output.push_str(&markdown::to_html(&value));
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_possible_options(opt: &clap::Arg, output: &mut String) {
|
||||
if opt.is_hide_possible_values_set() {
|
||||
return;
|
||||
}
|
||||
|
||||
let values = opt.get_possible_values();
|
||||
if !values.is_empty() {
|
||||
let value = format!(
|
||||
"\nPossible values:\n{}",
|
||||
values
|
||||
.into_iter()
|
||||
.filter(|value| !value.is_hide_set())
|
||||
.map(|value| {
|
||||
let name = value.get_name();
|
||||
value.get_help().map_or_else(
|
||||
|| format!(" - `{name}`"),
|
||||
|help| format!(" - `{name}`: {help}"),
|
||||
)
|
||||
})
|
||||
.collect_vec()
|
||||
.join("\n"),
|
||||
);
|
||||
output.push_str(&markdown::to_html(&value));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use anyhow::Result;
|
||||
|
||||
use crate::generate_all::Mode;
|
||||
|
||||
use super::{Args, main};
|
||||
|
||||
#[test]
|
||||
fn ty_cli_reference_is_up_to_date() -> Result<()> {
|
||||
main(&Args { mode: Mode::Check })
|
||||
}
|
||||
}
|
||||
257
crates/ruff_dev/src/generate_ty_options.rs
Normal file
257
crates/ruff_dev/src/generate_ty_options.rs
Normal file
@@ -0,0 +1,257 @@
|
||||
//! Generate a Markdown-compatible listing of configuration options for `pyproject.toml`.
|
||||
|
||||
use anyhow::bail;
|
||||
use itertools::Itertools;
|
||||
use pretty_assertions::StrComparison;
|
||||
use std::{fmt::Write, path::PathBuf};
|
||||
|
||||
use ruff_options_metadata::{OptionField, OptionSet, OptionsMetadata, Visit};
|
||||
use ty_project::metadata::Options;
|
||||
|
||||
use crate::{
|
||||
ROOT_DIR,
|
||||
generate_all::{Mode, REGENERATE_ALL_COMMAND},
|
||||
};
|
||||
|
||||
#[derive(clap::Args)]
|
||||
pub(crate) struct Args {
|
||||
/// Write the generated table to stdout (rather than to `crates/ty/docs/configuration.md`).
|
||||
#[arg(long, default_value_t, value_enum)]
|
||||
pub(crate) mode: Mode,
|
||||
}
|
||||
|
||||
pub(crate) fn main(args: &Args) -> anyhow::Result<()> {
|
||||
let mut output = String::new();
|
||||
let file_name = "crates/ty/docs/configuration.md";
|
||||
let markdown_path = PathBuf::from(ROOT_DIR).join(file_name);
|
||||
|
||||
generate_set(
|
||||
&mut output,
|
||||
Set::Toplevel(Options::metadata()),
|
||||
&mut Vec::new(),
|
||||
);
|
||||
|
||||
match args.mode {
|
||||
Mode::DryRun => {
|
||||
println!("{output}");
|
||||
}
|
||||
Mode::Check => {
|
||||
let current = std::fs::read_to_string(&markdown_path)?;
|
||||
if output == current {
|
||||
println!("Up-to-date: {file_name}",);
|
||||
} else {
|
||||
let comparison = StrComparison::new(¤t, &output);
|
||||
bail!("{file_name} changed, please run `{REGENERATE_ALL_COMMAND}`:\n{comparison}",);
|
||||
}
|
||||
}
|
||||
Mode::Write => {
|
||||
let current = std::fs::read_to_string(&markdown_path)?;
|
||||
if current == output {
|
||||
println!("Up-to-date: {file_name}",);
|
||||
} else {
|
||||
println!("Updating: {file_name}",);
|
||||
std::fs::write(markdown_path, output.as_bytes())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn generate_set(output: &mut String, set: Set, parents: &mut Vec<Set>) {
|
||||
match &set {
|
||||
Set::Toplevel(_) => {
|
||||
output.push_str("# Configuration\n");
|
||||
}
|
||||
Set::Named { name, .. } => {
|
||||
let title = parents
|
||||
.iter()
|
||||
.filter_map(|set| set.name())
|
||||
.chain(std::iter::once(name.as_str()))
|
||||
.join(".");
|
||||
writeln!(output, "## `{title}`\n",).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(documentation) = set.metadata().documentation() {
|
||||
output.push_str(documentation);
|
||||
output.push('\n');
|
||||
output.push('\n');
|
||||
}
|
||||
|
||||
let mut visitor = CollectOptionsVisitor::default();
|
||||
set.metadata().record(&mut visitor);
|
||||
|
||||
let (mut fields, mut sets) = (visitor.fields, visitor.groups);
|
||||
|
||||
fields.sort_unstable_by(|(name, _), (name2, _)| name.cmp(name2));
|
||||
sets.sort_unstable_by(|(name, _), (name2, _)| name.cmp(name2));
|
||||
|
||||
parents.push(set);
|
||||
|
||||
// Generate the fields.
|
||||
for (name, field) in &fields {
|
||||
emit_field(output, name, field, parents.as_slice());
|
||||
output.push_str("---\n\n");
|
||||
}
|
||||
|
||||
// Generate all the sub-sets.
|
||||
for (set_name, sub_set) in &sets {
|
||||
generate_set(
|
||||
output,
|
||||
Set::Named {
|
||||
name: set_name.to_string(),
|
||||
set: *sub_set,
|
||||
},
|
||||
parents,
|
||||
);
|
||||
}
|
||||
|
||||
parents.pop();
|
||||
}
|
||||
|
||||
enum Set {
|
||||
Toplevel(OptionSet),
|
||||
Named { name: String, set: OptionSet },
|
||||
}
|
||||
|
||||
impl Set {
|
||||
fn name(&self) -> Option<&str> {
|
||||
match self {
|
||||
Set::Toplevel(_) => None,
|
||||
Set::Named { name, .. } => Some(name),
|
||||
}
|
||||
}
|
||||
|
||||
fn metadata(&self) -> &OptionSet {
|
||||
match self {
|
||||
Set::Toplevel(set) => set,
|
||||
Set::Named { set, .. } => set,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_field(output: &mut String, name: &str, field: &OptionField, parents: &[Set]) {
|
||||
let header_level = if parents.is_empty() { "###" } else { "####" };
|
||||
|
||||
let _ = writeln!(output, "{header_level} `{name}`");
|
||||
|
||||
output.push('\n');
|
||||
|
||||
if let Some(deprecated) = &field.deprecated {
|
||||
output.push_str("> [!WARN] \"Deprecated\"\n");
|
||||
output.push_str("> This option has been deprecated");
|
||||
|
||||
if let Some(since) = deprecated.since {
|
||||
write!(output, " in {since}").unwrap();
|
||||
}
|
||||
|
||||
output.push('.');
|
||||
|
||||
if let Some(message) = deprecated.message {
|
||||
writeln!(output, " {message}").unwrap();
|
||||
}
|
||||
|
||||
output.push('\n');
|
||||
}
|
||||
|
||||
output.push_str(field.doc);
|
||||
output.push_str("\n\n");
|
||||
let _ = writeln!(output, "**Default value**: `{}`", field.default);
|
||||
output.push('\n');
|
||||
let _ = writeln!(output, "**Type**: `{}`", field.value_type);
|
||||
output.push('\n');
|
||||
output.push_str("**Example usage** (`pyproject.toml`):\n\n");
|
||||
output.push_str(&format_example(
|
||||
&format_header(
|
||||
field.scope,
|
||||
field.example,
|
||||
parents,
|
||||
ConfigurationFile::PyprojectToml,
|
||||
),
|
||||
field.example,
|
||||
));
|
||||
output.push('\n');
|
||||
}
|
||||
|
||||
fn format_example(header: &str, content: &str) -> String {
|
||||
if header.is_empty() {
|
||||
format!("```toml\n{content}\n```\n",)
|
||||
} else {
|
||||
format!("```toml\n{header}\n{content}\n```\n",)
|
||||
}
|
||||
}
|
||||
|
||||
/// Format the TOML header for the example usage for a given option.
|
||||
///
|
||||
/// For example: `[tool.ruff.format]` or `[tool.ruff.lint.isort]`.
|
||||
fn format_header(
|
||||
scope: Option<&str>,
|
||||
example: &str,
|
||||
parents: &[Set],
|
||||
configuration: ConfigurationFile,
|
||||
) -> String {
|
||||
let tool_parent = match configuration {
|
||||
ConfigurationFile::PyprojectToml => Some("tool.ty"),
|
||||
ConfigurationFile::TyToml => None,
|
||||
};
|
||||
|
||||
let header = tool_parent
|
||||
.into_iter()
|
||||
.chain(parents.iter().filter_map(|parent| parent.name()))
|
||||
.chain(scope)
|
||||
.join(".");
|
||||
|
||||
// Ex) `[[tool.ty.xx]]`
|
||||
if example.starts_with(&format!("[[{header}")) {
|
||||
return String::new();
|
||||
}
|
||||
// Ex) `[tool.ty.rules]`
|
||||
if example.starts_with(&format!("[{header}")) {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
if header.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("[{header}]")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct CollectOptionsVisitor {
|
||||
groups: Vec<(String, OptionSet)>,
|
||||
fields: Vec<(String, OptionField)>,
|
||||
}
|
||||
|
||||
impl Visit for CollectOptionsVisitor {
|
||||
fn record_set(&mut self, name: &str, group: OptionSet) {
|
||||
self.groups.push((name.to_owned(), group));
|
||||
}
|
||||
|
||||
fn record_field(&mut self, name: &str, field: OptionField) {
|
||||
self.fields.push((name.to_owned(), field));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
enum ConfigurationFile {
|
||||
PyprojectToml,
|
||||
#[expect(dead_code)]
|
||||
TyToml,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use anyhow::Result;
|
||||
|
||||
use crate::generate_all::Mode;
|
||||
|
||||
use super::{Args, main};
|
||||
|
||||
#[test]
|
||||
fn ty_configuration_markdown_up_to_date() -> Result<()> {
|
||||
main(&Args { mode: Mode::Check })?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
143
crates/ruff_dev/src/generate_ty_rules.rs
Normal file
143
crates/ruff_dev/src/generate_ty_rules.rs
Normal file
@@ -0,0 +1,143 @@
|
||||
//! Generates the rules table for ty
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::fmt::Write as _;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use itertools::Itertools as _;
|
||||
use pretty_assertions::StrComparison;
|
||||
|
||||
use crate::ROOT_DIR;
|
||||
use crate::generate_all::{Mode, REGENERATE_ALL_COMMAND};
|
||||
|
||||
#[derive(clap::Args)]
|
||||
pub(crate) struct Args {
|
||||
/// Write the generated table to stdout (rather than to `ty.schema.json`).
|
||||
#[arg(long, default_value_t, value_enum)]
|
||||
pub(crate) mode: Mode,
|
||||
}
|
||||
|
||||
pub(crate) fn main(args: &Args) -> Result<()> {
|
||||
let markdown = generate_markdown();
|
||||
let filename = "crates/ty/docs/rules.md";
|
||||
let schema_path = PathBuf::from(ROOT_DIR).join(filename);
|
||||
|
||||
match args.mode {
|
||||
Mode::DryRun => {
|
||||
println!("{markdown}");
|
||||
}
|
||||
Mode::Check => {
|
||||
let current = fs::read_to_string(schema_path)?;
|
||||
if current == markdown {
|
||||
println!("Up-to-date: {filename}");
|
||||
} else {
|
||||
let comparison = StrComparison::new(¤t, &markdown);
|
||||
bail!("{filename} changed, please run `{REGENERATE_ALL_COMMAND}`:\n{comparison}");
|
||||
}
|
||||
}
|
||||
Mode::Write => {
|
||||
let current = fs::read_to_string(&schema_path)?;
|
||||
if current == markdown {
|
||||
println!("Up-to-date: {filename}");
|
||||
} else {
|
||||
println!("Updating: {filename}");
|
||||
fs::write(schema_path, markdown.as_bytes())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn generate_markdown() -> String {
|
||||
let registry = &*ty_project::DEFAULT_LINT_REGISTRY;
|
||||
|
||||
let mut output = String::new();
|
||||
|
||||
let _ = writeln!(&mut output, "# Rules\n");
|
||||
|
||||
let mut lints: Vec<_> = registry.lints().iter().collect();
|
||||
lints.sort_by(|a, b| {
|
||||
a.default_level()
|
||||
.cmp(&b.default_level())
|
||||
.reverse()
|
||||
.then_with(|| a.name().cmp(&b.name()))
|
||||
});
|
||||
|
||||
for lint in lints {
|
||||
let _ = writeln!(&mut output, "## `{rule_name}`\n", rule_name = lint.name());
|
||||
|
||||
// Increase the header-level by one
|
||||
let documentation = lint
|
||||
.documentation_lines()
|
||||
.map(|line| {
|
||||
if line.starts_with('#') {
|
||||
Cow::Owned(format!("#{line}"))
|
||||
} else {
|
||||
Cow::Borrowed(line)
|
||||
}
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
let _ = writeln!(
|
||||
&mut output,
|
||||
r#"**Default level**: {level}
|
||||
|
||||
<details>
|
||||
<summary>{summary}</summary>
|
||||
|
||||
{documentation}
|
||||
|
||||
### Links
|
||||
* [Related issues](https://github.com/astral-sh/ty/issues?q=sort%3Aupdated-desc%20is%3Aissue%20is%3Aopen%20{encoded_name})
|
||||
* [View source](https://github.com/astral-sh/ruff/blob/main/{file}#L{line})
|
||||
</details>
|
||||
"#,
|
||||
level = lint.default_level(),
|
||||
// GitHub doesn't support markdown in `summary` headers
|
||||
summary = replace_inline_code(lint.summary()),
|
||||
encoded_name = url::form_urlencoded::byte_serialize(lint.name().as_str().as_bytes())
|
||||
.collect::<String>(),
|
||||
file = url::form_urlencoded::byte_serialize(lint.file().replace('\\', "/").as_bytes())
|
||||
.collect::<String>(),
|
||||
line = lint.line(),
|
||||
);
|
||||
}
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
/// Replaces inline code blocks (`code`) with `<code>code</code>`
|
||||
fn replace_inline_code(input: &str) -> String {
|
||||
let mut output = String::new();
|
||||
let mut parts = input.split('`');
|
||||
|
||||
while let Some(before) = parts.next() {
|
||||
if let Some(between) = parts.next() {
|
||||
output.push_str(before);
|
||||
output.push_str("<code>");
|
||||
output.push_str(between);
|
||||
output.push_str("</code>");
|
||||
} else {
|
||||
output.push_str(before);
|
||||
}
|
||||
}
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use anyhow::Result;
|
||||
|
||||
use crate::generate_all::Mode;
|
||||
|
||||
use super::{Args, main};
|
||||
|
||||
#[test]
|
||||
fn ty_rules_up_to_date() -> Result<()> {
|
||||
main(&Args { mode: Mode::Check })
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,12 @@
|
||||
#![allow(clippy::print_stdout, clippy::print_stderr)]
|
||||
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use anyhow::{Result, bail};
|
||||
use pretty_assertions::StrComparison;
|
||||
use schemars::schema_for;
|
||||
|
||||
use crate::generate_all::{Mode, REGENERATE_ALL_COMMAND};
|
||||
use crate::ROOT_DIR;
|
||||
use crate::generate_all::{Mode, REGENERATE_ALL_COMMAND};
|
||||
use ty_project::metadata::options::Options;
|
||||
|
||||
#[derive(clap::Args)]
|
||||
@@ -58,7 +56,7 @@ mod tests {
|
||||
|
||||
use crate::generate_all::Mode;
|
||||
|
||||
use super::{main, Args};
|
||||
use super::{Args, main};
|
||||
|
||||
#[test]
|
||||
fn test_generate_json_schema() -> Result<()> {
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
//!
|
||||
//! Within the ruff repository you can run it with `cargo dev`.
|
||||
|
||||
#![allow(clippy::print_stdout, clippy::print_stderr)]
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::{Parser, Subcommand};
|
||||
use ruff::{args::GlobalConfigArgs, check};
|
||||
@@ -15,6 +17,9 @@ mod generate_docs;
|
||||
mod generate_json_schema;
|
||||
mod generate_options;
|
||||
mod generate_rules_table;
|
||||
mod generate_ty_cli_reference;
|
||||
mod generate_ty_options;
|
||||
mod generate_ty_rules;
|
||||
mod generate_ty_schema;
|
||||
mod print_ast;
|
||||
mod print_cst;
|
||||
@@ -44,8 +49,10 @@ enum Command {
|
||||
GenerateTySchema(generate_ty_schema::Args),
|
||||
/// Generate a Markdown-compatible table of supported lint rules.
|
||||
GenerateRulesTable,
|
||||
GenerateTyRules(generate_ty_rules::Args),
|
||||
/// Generate a Markdown-compatible listing of configuration options.
|
||||
GenerateOptions,
|
||||
GenerateTyOptions(generate_ty_options::Args),
|
||||
/// Generate CLI help.
|
||||
GenerateCliHelp(generate_cli_help::Args),
|
||||
/// Generate Markdown docs.
|
||||
@@ -88,7 +95,9 @@ fn main() -> Result<ExitCode> {
|
||||
Command::GenerateJSONSchema(args) => generate_json_schema::main(&args)?,
|
||||
Command::GenerateTySchema(args) => generate_ty_schema::main(&args)?,
|
||||
Command::GenerateRulesTable => println!("{}", generate_rules_table::generate()),
|
||||
Command::GenerateTyRules(args) => generate_ty_rules::main(&args)?,
|
||||
Command::GenerateOptions => println!("{}", generate_options::generate()),
|
||||
Command::GenerateTyOptions(args) => generate_ty_options::main(&args)?,
|
||||
Command::GenerateCliHelp(args) => generate_cli_help::main(&args)?,
|
||||
Command::GenerateDocs(args) => generate_docs::main(&args)?,
|
||||
Command::PrintAST(args) => print_ast::main(&args)?,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Print the AST for a given Python file.
|
||||
#![allow(clippy::print_stdout, clippy::print_stderr)]
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -7,7 +6,7 @@ use anyhow::Result;
|
||||
|
||||
use ruff_linter::source_kind::SourceKind;
|
||||
use ruff_python_ast::PySourceType;
|
||||
use ruff_python_parser::{parse, ParseOptions};
|
||||
use ruff_python_parser::{ParseOptions, parse};
|
||||
|
||||
#[derive(clap::Args)]
|
||||
pub(crate) struct Args {
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
//! Print the `LibCST` CST for a given Python file.
|
||||
#![allow(clippy::print_stdout, clippy::print_stderr)]
|
||||
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use anyhow::{Result, bail};
|
||||
|
||||
#[derive(clap::Args)]
|
||||
pub(crate) struct Args {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Print the token stream for a given Python file.
|
||||
#![allow(clippy::print_stdout, clippy::print_stderr)]
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Run round-trip source code generation on a given Python or Jupyter notebook file.
|
||||
#![allow(clippy::print_stdout, clippy::print_stderr)]
|
||||
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -1,35 +1,29 @@
|
||||
use anyhow::Result;
|
||||
use log::debug;
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use ruff_text_size::{Ranged, TextRange, TextSize};
|
||||
|
||||
use crate::Fix;
|
||||
use crate::{Fix, Violation};
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct DiagnosticKind {
|
||||
pub struct Diagnostic {
|
||||
/// The identifier of the diagnostic, used to align the diagnostic with a rule.
|
||||
pub name: String,
|
||||
pub name: &'static str,
|
||||
/// The message body to display to the user, to explain the diagnostic.
|
||||
pub body: String,
|
||||
/// The message to display to the user, to explain the suggested fix.
|
||||
pub suggestion: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
pub struct Diagnostic {
|
||||
pub kind: DiagnosticKind,
|
||||
pub range: TextRange,
|
||||
pub fix: Option<Fix>,
|
||||
pub parent: Option<TextSize>,
|
||||
}
|
||||
|
||||
impl Diagnostic {
|
||||
pub fn new<T: Into<DiagnosticKind>>(kind: T, range: TextRange) -> Self {
|
||||
pub fn new<T: Violation>(kind: T, range: TextRange) -> Self {
|
||||
Self {
|
||||
kind: kind.into(),
|
||||
name: T::rule_name(),
|
||||
body: Violation::message(&kind),
|
||||
suggestion: Violation::fix_title(&kind),
|
||||
range,
|
||||
fix: None,
|
||||
parent: None,
|
||||
@@ -56,7 +50,7 @@ impl Diagnostic {
|
||||
pub fn try_set_fix(&mut self, func: impl FnOnce() -> Result<Fix>) {
|
||||
match func() {
|
||||
Ok(fix) => self.fix = Some(fix),
|
||||
Err(err) => debug!("Failed to create fix for {}: {}", self.kind.name, err),
|
||||
Err(err) => debug!("Failed to create fix for {}: {}", self.name, err),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,7 +61,7 @@ impl Diagnostic {
|
||||
match func() {
|
||||
Ok(None) => {}
|
||||
Ok(Some(fix)) => self.fix = Some(fix),
|
||||
Err(err) => debug!("Failed to create fix for {}: {}", self.kind.name, err),
|
||||
Err(err) => debug!("Failed to create fix for {}: {}", self.name, err),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
pub use diagnostic::{Diagnostic, DiagnosticKind};
|
||||
pub use diagnostic::Diagnostic;
|
||||
pub use edit::Edit;
|
||||
pub use fix::{Applicability, Fix, IsolationLevel};
|
||||
pub use source_map::{SourceMap, SourceMarker};
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use crate::DiagnosticKind;
|
||||
use std::fmt::{Debug, Display};
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
@@ -79,16 +78,3 @@ impl<V: AlwaysFixableViolation> Violation for V {
|
||||
<Self as AlwaysFixableViolation>::message_formats()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<T> for DiagnosticKind
|
||||
where
|
||||
T: Violation,
|
||||
{
|
||||
fn from(value: T) -> Self {
|
||||
Self {
|
||||
body: Violation::message(&value),
|
||||
suggestion: Violation::fix_title(&value),
|
||||
name: T::rule_name().to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ impl<'fmt, Context> Argument<'fmt, Context> {
|
||||
/// Called by the [ruff_formatter::format_args] macro.
|
||||
#[doc(hidden)]
|
||||
#[inline]
|
||||
pub fn new<F: Format<Context>>(value: &'fmt F) -> Self {
|
||||
pub const fn new<F: Format<Context>>(value: &'fmt F) -> Self {
|
||||
Self { value }
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ pub struct Arguments<'fmt, Context>(pub &'fmt [Argument<'fmt, Context>]);
|
||||
impl<'fmt, Context> Arguments<'fmt, Context> {
|
||||
#[doc(hidden)]
|
||||
#[inline]
|
||||
pub fn new(arguments: &'fmt [Argument<'fmt, Context>]) -> Self {
|
||||
pub const fn new(arguments: &'fmt [Argument<'fmt, Context>]) -> Self {
|
||||
Self(arguments)
|
||||
}
|
||||
|
||||
@@ -98,7 +98,7 @@ impl<'fmt, Context> From<&'fmt Argument<'fmt, Context>> for Arguments<'fmt, Cont
|
||||
mod tests {
|
||||
use crate::format_element::tag::Tag;
|
||||
use crate::prelude::*;
|
||||
use crate::{format_args, write, FormatState, VecBuffer};
|
||||
use crate::{FormatState, VecBuffer, format_args, write};
|
||||
|
||||
#[test]
|
||||
fn test_nesting() {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{write, Arguments, FormatElement};
|
||||
use super::{Arguments, FormatElement, write};
|
||||
use crate::format_element::Interned;
|
||||
use crate::prelude::{LineMode, Tag};
|
||||
use crate::{FormatResult, FormatState};
|
||||
|
||||
@@ -2,14 +2,14 @@ use std::cell::Cell;
|
||||
use std::marker::PhantomData;
|
||||
use std::num::NonZeroU8;
|
||||
|
||||
use ruff_text_size::TextRange;
|
||||
#[allow(clippy::enum_glob_use)]
|
||||
use Tag::*;
|
||||
use ruff_text_size::TextRange;
|
||||
|
||||
use crate::format_element::tag::{Condition, Tag};
|
||||
use crate::prelude::tag::{DedentMode, GroupMode, LabelId};
|
||||
use crate::prelude::*;
|
||||
use crate::{write, Argument, Arguments, FormatContext, FormatOptions, GroupId, TextSize};
|
||||
use crate::{Argument, Arguments, FormatContext, FormatOptions, GroupId, TextSize, write};
|
||||
use crate::{Buffer, VecBuffer};
|
||||
|
||||
/// A line break that only gets printed if the enclosing `Group` doesn't fit on a single line.
|
||||
@@ -402,7 +402,10 @@ where
|
||||
}
|
||||
|
||||
fn debug_assert_no_newlines(text: &str) {
|
||||
debug_assert!(!text.contains('\r'), "The content '{text}' contains an unsupported '\\r' line terminator character but text must only use line feeds '\\n' as line separator. Use '\\n' instead of '\\r' and '\\r\\n' to insert a line break in strings.");
|
||||
debug_assert!(
|
||||
!text.contains('\r'),
|
||||
"The content '{text}' contains an unsupported '\\r' line terminator character but text must only use line feeds '\\n' as line separator. Use '\\n' instead of '\\r' and '\\r\\n' to insert a line break in strings."
|
||||
);
|
||||
}
|
||||
|
||||
/// Pushes some content to the end of the current line.
|
||||
@@ -1388,7 +1391,7 @@ pub fn soft_space_or_block_indent<Context>(content: &impl Format<Context>) -> Bl
|
||||
pub fn group<Context>(content: &impl Format<Context>) -> Group<Context> {
|
||||
Group {
|
||||
content: Argument::new(content),
|
||||
group_id: None,
|
||||
id: None,
|
||||
should_expand: false,
|
||||
}
|
||||
}
|
||||
@@ -1396,14 +1399,14 @@ pub fn group<Context>(content: &impl Format<Context>) -> Group<Context> {
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct Group<'a, Context> {
|
||||
content: Argument<'a, Context>,
|
||||
group_id: Option<GroupId>,
|
||||
id: Option<GroupId>,
|
||||
should_expand: bool,
|
||||
}
|
||||
|
||||
impl<Context> Group<'_, Context> {
|
||||
#[must_use]
|
||||
pub fn with_group_id(mut self, group_id: Option<GroupId>) -> Self {
|
||||
self.group_id = group_id;
|
||||
pub fn with_id(mut self, group_id: Option<GroupId>) -> Self {
|
||||
self.id = group_id;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -1429,7 +1432,7 @@ impl<Context> Format<Context> for Group<'_, Context> {
|
||||
};
|
||||
|
||||
f.write_element(FormatElement::Tag(StartGroup(
|
||||
tag::Group::new().with_id(self.group_id).with_mode(mode),
|
||||
tag::Group::new().with_id(self.id).with_mode(mode),
|
||||
)));
|
||||
|
||||
Arguments::from(&self.content).fmt(f)?;
|
||||
@@ -1443,7 +1446,7 @@ impl<Context> Format<Context> for Group<'_, Context> {
|
||||
impl<Context> std::fmt::Debug for Group<'_, Context> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Group")
|
||||
.field("group_id", &self.group_id)
|
||||
.field("id", &self.id)
|
||||
.field("should_expand", &self.should_expand)
|
||||
.field("content", &"{{content}}")
|
||||
.finish()
|
||||
@@ -1642,7 +1645,7 @@ impl<Context> std::fmt::Debug for BestFitParenthesize<'_, Context> {
|
||||
/// soft_line_break(),
|
||||
/// if_group_breaks(&token(")"))
|
||||
/// ])
|
||||
/// .with_group_id(Some(parentheses_id))
|
||||
/// .with_id(Some(parentheses_id))
|
||||
/// .fmt(f)
|
||||
/// });
|
||||
///
|
||||
@@ -1991,7 +1994,7 @@ impl<Context> IfGroupBreaks<'_, Context> {
|
||||
/// })),
|
||||
/// token("]")
|
||||
/// ],
|
||||
/// ).with_group_id(Some(group_id))
|
||||
/// ).with_id(Some(group_id))
|
||||
/// ])
|
||||
/// })])?;
|
||||
///
|
||||
@@ -2046,7 +2049,7 @@ impl<Context> std::fmt::Debug for IfGroupBreaks<'_, Context> {
|
||||
/// let id = f.group_id("head");
|
||||
///
|
||||
/// write!(f, [
|
||||
/// group(&token("Head")).with_group_id(Some(id)),
|
||||
/// group(&token("Head")).with_id(Some(id)),
|
||||
/// if_group_breaks(&indent(&token("indented"))).with_group_id(Some(id)),
|
||||
/// if_group_fits_on_line(&token("indented")).with_group_id(Some(id))
|
||||
/// ])
|
||||
@@ -2071,7 +2074,7 @@ impl<Context> std::fmt::Debug for IfGroupBreaks<'_, Context> {
|
||||
/// let group_id = f.group_id("header");
|
||||
///
|
||||
/// write!(f, [
|
||||
/// group(&token("(aLongHeaderThatBreaksForSomeReason) =>")).with_group_id(Some(group_id)),
|
||||
/// group(&token("(aLongHeaderThatBreaksForSomeReason) =>")).with_id(Some(group_id)),
|
||||
/// indent_if_group_breaks(&format_args![hard_line_break(), token("a => b")], group_id)
|
||||
/// ])
|
||||
/// });
|
||||
@@ -2101,7 +2104,7 @@ impl<Context> std::fmt::Debug for IfGroupBreaks<'_, Context> {
|
||||
/// let group_id = f.group_id("header");
|
||||
///
|
||||
/// write!(f, [
|
||||
/// group(&token("(aLongHeaderThatBreaksForSomeReason) =>")).with_group_id(Some(group_id)),
|
||||
/// group(&token("(aLongHeaderThatBreaksForSomeReason) =>")).with_id(Some(group_id)),
|
||||
/// indent_if_group_breaks(&format_args![hard_line_break(), token("a => b")], group_id)
|
||||
/// ])
|
||||
/// });
|
||||
@@ -2564,7 +2567,7 @@ impl<'a, Context> BestFitting<'a, Context> {
|
||||
/// # Panics
|
||||
///
|
||||
/// When the slice contains less than two variants.
|
||||
pub fn from_arguments_unchecked(variants: Arguments<'a, Context>) -> Self {
|
||||
pub const fn from_arguments_unchecked(variants: Arguments<'a, Context>) -> Self {
|
||||
assert!(
|
||||
variants.0.len() >= 2,
|
||||
"Requires at least the least expanded and most expanded variants"
|
||||
@@ -2572,7 +2575,7 @@ impl<'a, Context> BestFitting<'a, Context> {
|
||||
|
||||
Self {
|
||||
variants,
|
||||
mode: BestFittingMode::default(),
|
||||
mode: BestFittingMode::FirstLine,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::prelude::TagKind;
|
||||
use crate::GroupId;
|
||||
use crate::prelude::TagKind;
|
||||
use ruff_text_size::TextRange;
|
||||
use std::error::Error;
|
||||
|
||||
@@ -29,16 +29,22 @@ pub enum FormatError {
|
||||
impl std::fmt::Display for FormatError {
|
||||
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
FormatError::SyntaxError {message} => {
|
||||
FormatError::SyntaxError { message } => {
|
||||
std::write!(fmt, "syntax error: {message}")
|
||||
},
|
||||
}
|
||||
FormatError::RangeError { input, tree } => std::write!(
|
||||
fmt,
|
||||
"formatting range {input:?} is larger than syntax tree {tree:?}"
|
||||
),
|
||||
FormatError::InvalidDocument(error) => std::write!(fmt, "Invalid document: {error}\n\n This is an internal Rome error. Please report if necessary."),
|
||||
FormatError::InvalidDocument(error) => std::write!(
|
||||
fmt,
|
||||
"Invalid document: {error}\n\n This is an internal Rome error. Please report if necessary."
|
||||
),
|
||||
FormatError::PoorLayout => {
|
||||
std::write!(fmt, "Poor layout: The formatter wasn't able to pick a good layout for your document. This is an internal Rome error. Please report if necessary.")
|
||||
std::write!(
|
||||
fmt,
|
||||
"Poor layout: The formatter wasn't able to pick a good layout for your document. This is an internal Rome error. Please report if necessary."
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,24 +145,37 @@ impl std::fmt::Display for InvalidDocumentError {
|
||||
InvalidDocumentError::ExpectedStart {
|
||||
expected_start,
|
||||
actual,
|
||||
} => {
|
||||
match actual {
|
||||
ActualStart::EndOfDocument => {
|
||||
std::write!(f, "Expected start tag of kind {expected_start:?} but at the end of document.")
|
||||
}
|
||||
ActualStart::Start(start) => {
|
||||
std::write!(f, "Expected start tag of kind {expected_start:?} but found start tag of kind {start:?}.")
|
||||
}
|
||||
ActualStart::End(end) => {
|
||||
std::write!(f, "Expected start tag of kind {expected_start:?} but found end tag of kind {end:?}.")
|
||||
}
|
||||
ActualStart::Content => {
|
||||
std::write!(f, "Expected start tag of kind {expected_start:?} but found non-tag element.")
|
||||
}
|
||||
} => match actual {
|
||||
ActualStart::EndOfDocument => {
|
||||
std::write!(
|
||||
f,
|
||||
"Expected start tag of kind {expected_start:?} but at the end of document."
|
||||
)
|
||||
}
|
||||
}
|
||||
ActualStart::Start(start) => {
|
||||
std::write!(
|
||||
f,
|
||||
"Expected start tag of kind {expected_start:?} but found start tag of kind {start:?}."
|
||||
)
|
||||
}
|
||||
ActualStart::End(end) => {
|
||||
std::write!(
|
||||
f,
|
||||
"Expected start tag of kind {expected_start:?} but found end tag of kind {end:?}."
|
||||
)
|
||||
}
|
||||
ActualStart::Content => {
|
||||
std::write!(
|
||||
f,
|
||||
"Expected start tag of kind {expected_start:?} but found non-tag element."
|
||||
)
|
||||
}
|
||||
},
|
||||
InvalidDocumentError::UnknownGroupId { group_id } => {
|
||||
std::write!(f, "Encountered unknown group id {group_id:?}. Ensure that the group with the id {group_id:?} exists and that the group is a parent of or comes before the element referring to it.")
|
||||
std::write!(
|
||||
f,
|
||||
"Encountered unknown group id {group_id:?}. Ensure that the group with the id {group_id:?} exists and that the group is a parent of or comes before the element referring to it."
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -543,7 +543,7 @@ impl TextWidth {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use crate::format_element::{normalize_newlines, LINE_TERMINATORS};
|
||||
use crate::format_element::{LINE_TERMINATORS, normalize_newlines};
|
||||
|
||||
#[test]
|
||||
fn test_normalize_newlines() {
|
||||
|
||||
@@ -8,8 +8,8 @@ use crate::prelude::tag::GroupMode;
|
||||
use crate::prelude::*;
|
||||
use crate::source_code::SourceCode;
|
||||
use crate::{
|
||||
format, write, BufferExtensions, Format, FormatContext, FormatElement, FormatOptions,
|
||||
FormatResult, Formatter, IndentStyle, IndentWidth, LineWidth, PrinterOptions,
|
||||
BufferExtensions, Format, FormatContext, FormatElement, FormatOptions, FormatResult, Formatter,
|
||||
IndentStyle, IndentWidth, LineWidth, PrinterOptions, format, write,
|
||||
};
|
||||
|
||||
use super::tag::Tag;
|
||||
@@ -811,8 +811,8 @@ mod tests {
|
||||
use ruff_text_size::{TextRange, TextSize};
|
||||
|
||||
use crate::prelude::*;
|
||||
use crate::{format, format_args, write};
|
||||
use crate::{SimpleFormatContext, SourceCode};
|
||||
use crate::{format, format_args, write};
|
||||
|
||||
#[test]
|
||||
fn display_elements() {
|
||||
|
||||
@@ -370,7 +370,10 @@ impl PartialEq for LabelId {
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
if is_equal {
|
||||
assert_eq!(self.name, other.name, "Two `LabelId`s with different names have the same `value`. Are you mixing labels of two different `LabelDefinition` or are the values returned by the `LabelDefinition` not unique?");
|
||||
assert_eq!(
|
||||
self.name, other.name,
|
||||
"Two `LabelId`s with different names have the same `value`. Are you mixing labels of two different `LabelDefinition` or are the values returned by the `LabelDefinition` not unique?"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ use crate::prelude::TagKind;
|
||||
use std::fmt;
|
||||
use std::fmt::{Debug, Display};
|
||||
use std::marker::PhantomData;
|
||||
use std::num::{NonZeroU16, NonZeroU8, TryFromIntError};
|
||||
use std::num::{NonZeroU8, NonZeroU16, TryFromIntError};
|
||||
|
||||
use crate::format_element::document::Document;
|
||||
use crate::printer::{Printer, PrinterOptions};
|
||||
@@ -50,7 +50,7 @@ pub use builders::BestFitting;
|
||||
pub use source_code::{SourceCode, SourceCodeSlice};
|
||||
|
||||
pub use crate::diagnostics::{ActualStart, FormatError, InvalidDocumentError, PrintError};
|
||||
pub use format_element::{normalize_newlines, FormatElement, LINE_TERMINATORS};
|
||||
pub use format_element::{FormatElement, LINE_TERMINATORS, normalize_newlines};
|
||||
pub use group_id::GroupId;
|
||||
use ruff_macros::CacheKey;
|
||||
use ruff_text_size::{TextLen, TextRange, TextSize};
|
||||
@@ -92,7 +92,7 @@ impl std::fmt::Display for IndentStyle {
|
||||
}
|
||||
}
|
||||
|
||||
/// The visual width of a indentation.
|
||||
/// The visual width of an indentation.
|
||||
///
|
||||
/// Determines the visual width of a tab character (`\t`) and the number of
|
||||
/// spaces per indent when using [`IndentStyle::Space`].
|
||||
@@ -207,7 +207,7 @@ pub trait FormatOptions {
|
||||
/// What's the max width of a line. Defaults to 80.
|
||||
fn line_width(&self) -> LineWidth;
|
||||
|
||||
/// Derives the print options from the these format options
|
||||
/// Derives the print options from these format options
|
||||
fn as_print_options(&self) -> PrinterOptions;
|
||||
}
|
||||
|
||||
|
||||
@@ -328,16 +328,16 @@ macro_rules! format {
|
||||
/// [`MostExpanded`]: crate::format_element::BestFittingVariants::most_expanded
|
||||
#[macro_export]
|
||||
macro_rules! best_fitting {
|
||||
($least_expanded:expr, $($tail:expr),+ $(,)?) => {{
|
||||
($least_expanded:expr, $($tail:expr),+ $(,)?) => {
|
||||
// OK because the macro syntax requires at least two variants.
|
||||
$crate::BestFitting::from_arguments_unchecked($crate::format_args!($least_expanded, $($tail),+))
|
||||
}}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::prelude::*;
|
||||
use crate::{write, FormatState, SimpleFormatOptions, VecBuffer};
|
||||
use crate::{FormatState, SimpleFormatOptions, VecBuffer, write};
|
||||
|
||||
struct TestFormat;
|
||||
|
||||
@@ -386,7 +386,7 @@ mod tests {
|
||||
#[test]
|
||||
fn best_fitting_variants_print_as_lists() {
|
||||
use crate::prelude::*;
|
||||
use crate::{format, format_args, Formatted};
|
||||
use crate::{Formatted, format, format_args};
|
||||
|
||||
// The second variant below should be selected when printing at a width of 30
|
||||
let formatted_best_fitting = format!(
|
||||
@@ -398,34 +398,36 @@ mod tests {
|
||||
format_args![token(
|
||||
"Something that will not fit on a line with 30 character print width."
|
||||
)],
|
||||
format_args![group(&format_args![
|
||||
token("Start"),
|
||||
soft_line_break(),
|
||||
group(&soft_block_indent(&format_args![
|
||||
token("1,"),
|
||||
soft_line_break_or_space(),
|
||||
token("2,"),
|
||||
soft_line_break_or_space(),
|
||||
token("3"),
|
||||
])),
|
||||
soft_line_break_or_space(),
|
||||
soft_block_indent(&format_args![
|
||||
token("1,"),
|
||||
soft_line_break_or_space(),
|
||||
token("2,"),
|
||||
soft_line_break_or_space(),
|
||||
group(&format_args!(
|
||||
token("A,"),
|
||||
format_args![
|
||||
group(&format_args![
|
||||
token("Start"),
|
||||
soft_line_break(),
|
||||
group(&soft_block_indent(&format_args![
|
||||
token("1,"),
|
||||
soft_line_break_or_space(),
|
||||
token("B")
|
||||
)),
|
||||
token("2,"),
|
||||
soft_line_break_or_space(),
|
||||
token("3"),
|
||||
])),
|
||||
soft_line_break_or_space(),
|
||||
token("3")
|
||||
]),
|
||||
soft_line_break_or_space(),
|
||||
token("End")
|
||||
])
|
||||
.should_expand(true)],
|
||||
soft_block_indent(&format_args![
|
||||
token("1,"),
|
||||
soft_line_break_or_space(),
|
||||
token("2,"),
|
||||
soft_line_break_or_space(),
|
||||
group(&format_args!(
|
||||
token("A,"),
|
||||
soft_line_break_or_space(),
|
||||
token("B")
|
||||
)),
|
||||
soft_line_break_or_space(),
|
||||
token("3")
|
||||
]),
|
||||
soft_line_break_or_space(),
|
||||
token("End")
|
||||
])
|
||||
.should_expand(true)
|
||||
],
|
||||
format_args!(token("Most"), hard_line_break(), token("Expanded"))
|
||||
]
|
||||
]
|
||||
|
||||
@@ -7,6 +7,6 @@ pub use crate::formatter::Formatter;
|
||||
pub use crate::printer::PrinterOptions;
|
||||
|
||||
pub use crate::{
|
||||
best_fitting, dbg_write, format, format_args, write, Buffer as _, BufferExtensions, Format,
|
||||
Format as _, FormatResult, FormatRule, FormatWithRule as _, SimpleFormatContext,
|
||||
Buffer as _, BufferExtensions, Format, Format as _, FormatResult, FormatRule,
|
||||
FormatWithRule as _, SimpleFormatContext, best_fitting, dbg_write, format, format_args, write,
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::format_element::tag::TagKind;
|
||||
use crate::format_element::PrintMode;
|
||||
use crate::format_element::tag::TagKind;
|
||||
use crate::printer::stack::{Stack, StackedStack};
|
||||
use crate::printer::{Indentation, MeasureMode};
|
||||
use crate::{IndentStyle, InvalidDocumentError, PrintError, PrintResult};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::printer::call_stack::PrintElementArgs;
|
||||
use crate::FormatElement;
|
||||
use crate::printer::call_stack::PrintElementArgs;
|
||||
|
||||
/// Stores the queued line suffixes.
|
||||
#[derive(Debug, Default)]
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::format_element::document::Document;
|
||||
use crate::format_element::tag::{Condition, GroupMode};
|
||||
use crate::format_element::{BestFittingMode, BestFittingVariants, LineMode, PrintMode};
|
||||
use crate::prelude::tag::{DedentMode, Tag, TagKind, VerbatimKind};
|
||||
use crate::prelude::{tag, TextWidth};
|
||||
use crate::prelude::{TextWidth, tag};
|
||||
use crate::printer::call_stack::{
|
||||
CallStack, FitsCallStack, PrintCallStack, PrintElementArgs, StackFrame,
|
||||
};
|
||||
@@ -1199,7 +1199,7 @@ impl<'a, 'print> FitsMeasurer<'a, 'print> {
|
||||
text_width: *text_width,
|
||||
},
|
||||
args,
|
||||
))
|
||||
));
|
||||
}
|
||||
FormatElement::SourceCodeSlice { slice, text_width } => {
|
||||
let text = slice.text(self.printer.source_code);
|
||||
@@ -1597,11 +1597,7 @@ enum Fits {
|
||||
|
||||
impl From<bool> for Fits {
|
||||
fn from(value: bool) -> Self {
|
||||
if value {
|
||||
Fits::Yes
|
||||
} else {
|
||||
Fits::No
|
||||
}
|
||||
if value { Fits::Yes } else { Fits::No }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1662,8 +1658,8 @@ mod tests {
|
||||
use crate::printer::{LineEnding, Printer, PrinterOptions};
|
||||
use crate::source_code::SourceCode;
|
||||
use crate::{
|
||||
format_args, write, Document, FormatState, IndentStyle, IndentWidth, LineWidth, Printed,
|
||||
VecBuffer,
|
||||
Document, FormatState, IndentStyle, IndentWidth, LineWidth, Printed, VecBuffer,
|
||||
format_args, write,
|
||||
};
|
||||
|
||||
fn format(root: &dyn Format<SimpleFormatContext>) -> Printed {
|
||||
@@ -1985,10 +1981,21 @@ two lines`,
|
||||
token("]")
|
||||
]),
|
||||
token(";"),
|
||||
line_suffix(&format_args![space(), token("// Using reserved width causes this content to not fit even though it's a line suffix element")], 93)
|
||||
line_suffix(
|
||||
&format_args![
|
||||
space(),
|
||||
token(
|
||||
"// Using reserved width causes this content to not fit even though it's a line suffix element"
|
||||
)
|
||||
],
|
||||
93
|
||||
)
|
||||
]);
|
||||
|
||||
assert_eq!(printed.as_code(), "[\n 1, 2, 3\n]; // Using reserved width causes this content to not fit even though it's a line suffix element");
|
||||
assert_eq!(
|
||||
printed.as_code(),
|
||||
"[\n 1, 2, 3\n]; // Using reserved width causes this content to not fit even though it's a line suffix element"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2002,7 +2009,7 @@ two lines`,
|
||||
token("The referenced group breaks."),
|
||||
hard_line_break()
|
||||
])
|
||||
.with_group_id(Some(group_id)),
|
||||
.with_id(Some(group_id)),
|
||||
group(&format_args![
|
||||
token("This group breaks because:"),
|
||||
soft_line_break_or_space(),
|
||||
@@ -2015,7 +2022,10 @@ two lines`,
|
||||
|
||||
let printed = format(&content);
|
||||
|
||||
assert_eq!(printed.as_code(), "The referenced group breaks.\nThis group breaks because:\nIt measures with the 'if_group_breaks' variant because the referenced group breaks and that's just way too much text.");
|
||||
assert_eq!(
|
||||
printed.as_code(),
|
||||
"The referenced group breaks.\nThis group breaks because:\nIt measures with the 'if_group_breaks' variant because the referenced group breaks and that's just way too much text."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2027,7 +2037,7 @@ two lines`,
|
||||
write!(
|
||||
f,
|
||||
[
|
||||
group(&token("Group with id-2")).with_group_id(Some(id_2)),
|
||||
group(&token("Group with id-2")).with_id(Some(id_2)),
|
||||
hard_line_break()
|
||||
]
|
||||
)?;
|
||||
@@ -2035,7 +2045,7 @@ two lines`,
|
||||
write!(
|
||||
f,
|
||||
[
|
||||
group(&token("Group with id-1 does not fit on the line because it exceeds the line width of 80 characters by")).with_group_id(Some(id_1)),
|
||||
group(&token("Group with id-1 does not fit on the line because it exceeds the line width of 80 characters by")).with_id(Some(id_1)),
|
||||
hard_line_break()
|
||||
]
|
||||
)?;
|
||||
|
||||
@@ -325,10 +325,10 @@ impl FitsEndPredicate for SingleEntryPredicate {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::FormatElement;
|
||||
use crate::format_element::LineMode;
|
||||
use crate::prelude::Tag;
|
||||
use crate::printer::queue::{PrintQueue, Queue};
|
||||
use crate::FormatElement;
|
||||
|
||||
#[test]
|
||||
fn extend_back_pop_last() {
|
||||
|
||||
@@ -65,7 +65,10 @@ pub struct SourceCodeSlice {
|
||||
impl SourceCodeSlice {
|
||||
/// Returns the slice's text.
|
||||
pub fn text<'a>(&self, code: SourceCode<'a>) -> &'a str {
|
||||
assert!(usize::from(self.range.end()) <= code.text.len(), "The range of this slice is out of bounds. Did you provide the correct source code for this slice?");
|
||||
assert!(
|
||||
usize::from(self.range.end()) <= code.text.len(),
|
||||
"The range of this slice is out of bounds. Did you provide the correct source code for this slice?"
|
||||
);
|
||||
&code.text[self.range]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use ruff_python_ast::visitor::source_order::{
|
||||
walk_expr, walk_module, walk_stmt, SourceOrderVisitor,
|
||||
SourceOrderVisitor, walk_expr, walk_module, walk_stmt,
|
||||
};
|
||||
use ruff_python_ast::{self as ast, Expr, Mod, Stmt};
|
||||
use ty_python_semantic::ModuleName;
|
||||
|
||||
@@ -9,8 +9,8 @@ use ruff_db::{Db as SourceDb, Upcast};
|
||||
use ruff_python_ast::PythonVersion;
|
||||
use ty_python_semantic::lint::{LintRegistry, RuleSelection};
|
||||
use ty_python_semantic::{
|
||||
default_lint_registry, Db, Program, ProgramSettings, PythonPath, PythonPlatform,
|
||||
SearchPathSettings,
|
||||
Db, Program, ProgramSettings, PythonPath, PythonPlatform, SearchPathSettings,
|
||||
default_lint_registry,
|
||||
};
|
||||
|
||||
static EMPTY_VENDORED: std::sync::LazyLock<VendoredFileSystem> = std::sync::LazyLock::new(|| {
|
||||
@@ -88,8 +88,8 @@ impl Db for ModuleDb {
|
||||
!file.path(self).is_vendored_path()
|
||||
}
|
||||
|
||||
fn rule_selection(&self) -> Arc<RuleSelection> {
|
||||
self.rule_selection.clone()
|
||||
fn rule_selection(&self) -> &RuleSelection {
|
||||
&self.rule_selection
|
||||
}
|
||||
|
||||
fn lint_registry(&self) -> &LintRegistry {
|
||||
@@ -98,6 +98,4 @@ impl Db for ModuleDb {
|
||||
}
|
||||
|
||||
#[salsa::db]
|
||||
impl salsa::Database for ModuleDb {
|
||||
fn salsa_event(&self, _event: &dyn Fn() -> salsa::Event) {}
|
||||
}
|
||||
impl salsa::Database for ModuleDb {}
|
||||
|
||||
@@ -4,7 +4,7 @@ use anyhow::Result;
|
||||
|
||||
use ruff_db::system::{SystemPath, SystemPathBuf};
|
||||
use ruff_python_ast::helpers::to_module_path;
|
||||
use ruff_python_parser::{parse, Mode, ParseOptions};
|
||||
use ruff_python_parser::{Mode, ParseOptions, parse};
|
||||
|
||||
use crate::collector::Collector;
|
||||
pub use crate::db::ModuleDb;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use ruff_db::files::FilePath;
|
||||
use ty_python_semantic::resolve_module;
|
||||
|
||||
use crate::collector::CollectedImport;
|
||||
use crate::ModuleDb;
|
||||
use crate::collector::CollectedImport;
|
||||
|
||||
/// Collect all imports for a given Python file.
|
||||
pub(crate) struct Resolver<'a> {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user