Merge remote-tracking branch 'origin/main' into fix/python-analyzer-install-prompt

Цей коміт міститься в:
l0ng-ai committed 2026-12-06 10:14:56 +08:00
коміт 8665d1b47d
466 files changed
+14136 -1801

No files matched your search

+1 -1
Переглянути файл
@@ -12,7 +12,7 @@ jobs:
cancel:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
script: |
// A merged or closed PR's remaining CI only holds runners other PRs wait for.
+24 -24
Переглянути файл
@@ -117,7 +117,7 @@ jobs:
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { components: "clippy, rustfmt" }
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
@@ -139,11 +139,11 @@ jobs:
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
rm -rf "$CARGO_TARGET_DIR"
fi
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
- uses: taiki-e/install-action@43dc658ea8a4fa76c68a84c0acd17c34169b6e2a # v2.90.12
with: { tool: nextest }
# ide-sdk's .NET status test and crates/ide-coverage/tests/dotnet_cli.rs run the real `dotnet`
# CLI; with CI set they fail, not skip, when it is missing.
- uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5.4.0
- uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
with:
dotnet-version: 10.0.x
- name: Linux deps
@@ -175,7 +175,7 @@ jobs:
- name: Restore Maven artifacts for Java build tests
id: jbuild-maven-cache
if: runner.environment == 'github-hosted'
uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: jbuild-maven-v2-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
@@ -209,13 +209,13 @@ jobs:
exit 1
- name: Save Maven artifacts for Java build tests
if: steps.jbuild-maven.outputs.prepared == 'true'
uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
# python_yappi.rs profiles real runs. Self-hosted runners have no setup-python; without
# YAPPI_PYTHON those tests return early.
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
if: runner.environment == 'github-hosted'
id: yappi-python
with: { python-version: "3.12", update-environment: false }
@@ -231,7 +231,7 @@ jobs:
"$venv_py" -m pip install yappi==1.7.6
echo "YAPPI_PYTHON=$venv_py" >> "$GITHUB_ENV"
# python_memray.rs profiles real runs. memray has no Windows build.
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
if: runner.os != 'Windows' && runner.environment == 'github-hosted'
id: memray-python
with: { python-version: "3.12", update-environment: false }
@@ -287,7 +287,7 @@ jobs:
timeout-minutes: 40
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: x86_64-unknown-linux-musl }
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
@@ -318,7 +318,7 @@ jobs:
timeout-minutes: 30
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: wasm32-wasip2, components: "clippy, rustfmt" }
- if: runner.environment != 'self-hosted'
@@ -354,9 +354,9 @@ jobs:
cargo test --locked --manifest-path "$dir/Cargo.toml"
echo "::endgroup::"
done
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
with: { node-version: 22, package-manager-cache: false }
# Plugin web pages (`web-src/`, their own pnpm projects): typecheck and test.
- name: Web pages typecheck and test
@@ -383,9 +383,9 @@ jobs:
timeout-minutes: 15
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
- uses: taiki-e/install-action@43dc658ea8a4fa76c68a84c0acd17c34169b6e2a # v2.90.12
with: { tool: cargo-deny }
- run: cargo deny check
@@ -396,19 +396,19 @@ jobs:
timeout-minutes: 30
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container.
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
if: runner.environment == 'self-hosted'
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
# src/features/dotnet/edit.test.ts and *.cli.test.ts run the real `dotnet` CLI; with CI set they fail, not skip, when it is missing.
- uses: actions/setup-dotnet@v5
- uses: actions/setup-dotnet@v6
with:
dotnet-version: |
10.0.x
@@ -429,10 +429,10 @@ jobs:
timeout-minutes: 15
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -451,10 +451,10 @@ jobs:
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -462,7 +462,7 @@ jobs:
- run: pnpm install --frozen-lockfile
- run: pnpm exec playwright install --with-deps chromium
- run: pnpm e2e --shard=${{ matrix.shard }}/4
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: failure()
with:
name: playwright-report-${{ matrix.shard }}
+2 -2
Переглянути файл
@@ -36,10 +36,10 @@ jobs:
echo "::notice::CNB_TOKEN unset: not mirroring $TAG"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
if: steps.token.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
if: steps.token.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download release
+3 -3
Переглянути файл
@@ -42,16 +42,16 @@ jobs:
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
if: steps.check.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
if: steps.check.outputs.skip != 'true'
with:
repository: ${{ env.TAP }}
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
path: tap
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
if: steps.check.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download DMGs
+10 -10
Переглянути файл
@@ -176,7 +176,7 @@ jobs:
# stripping local-variable debuginfo from fixtures debugged in the smoke job (CodeLLDB).
CARGO_PROFILE_DEV_DEBUG: line-tables-only
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
@@ -205,7 +205,7 @@ jobs:
test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke
# A tar keeps the executable bits, which artifacts drop.
tar -cf smoke-bin.tar smoke-bin
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
smoke:
@@ -224,21 +224,21 @@ jobs:
env:
CARGO_MANIFEST_DIR: ${{ github.workspace }}/crates/ide-host
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# Tool versions, shared with the evals (pnpm eval).
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
- if: contains(matrix.group.languages, 'rust')
uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { components: "rust-analyzer, rustfmt" }
- uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with: { name: smoke-bin }
- run: |
tar -xf smoke-bin.tar && rm smoke-bin.tar
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -264,19 +264,19 @@ jobs:
fi
- if: contains(matrix.group.languages, 'python')
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with: { python-version: "3.12" }
- if: contains(matrix.group.languages, 'python')
run: pip install "basedpyright==$BASEDPYRIGHT" "ruff==$RUFF"
- if: contains(matrix.group.languages, 'go')
uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
with: { go-version: "1.27", cache: false }
- if: contains(matrix.group.languages, 'go')
run: go install "golang.org/x/tools/gopls@$GOPLS"
- if: contains(matrix.group.languages, 'java') || contains(matrix.group.languages, 'kotlin')
uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
- if: contains(matrix.group.languages, 'java')
run: |
@@ -288,7 +288,7 @@ jobs:
# The Kotlin fixture has no Gradle wrapper: the server imports it with the Gradle on PATH.
- if: contains(matrix.group.languages, 'kotlin')
uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1
with:
gradle-version: "${{ env.GRADLE }}"
cache-read-only: ${{ github.ref != 'refs/heads/main' }}
+2 -2
Переглянути файл
@@ -30,7 +30,7 @@ jobs:
outputs:
tag: ${{ steps.tag.outputs.tag }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with: { ref: main, fetch-depth: 0 }
- id: changed
env:
@@ -41,7 +41,7 @@ jobs:
echo "::notice::main has not changed since $last"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
if: steps.changed.outputs.skip != 'true'
with: { node-version: 22 }
- name: Version commit and tag
+1 -1
Переглянути файл
@@ -18,7 +18,7 @@ jobs:
if: github.event.pull_request.user.type != 'Bot' && !github.event.pull_request.draft
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
script: |
const pr = context.payload.pull_request;
+8 -8
Переглянути файл
@@ -72,11 +72,11 @@ jobs:
target: x86_64-pc-windows-msvc
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with: { ref: "${{ env.TAG }}" }
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
with: { node-version: 22, cache: pnpm }
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: "${{ matrix.target }}" }
@@ -198,7 +198,7 @@ jobs:
- { runner: macos-latest, target: x86_64-apple-darwin, os: macos, arch: x86_64 }
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with: { ref: "${{ env.TAG }}" }
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: "${{ matrix.target }}" }
@@ -238,13 +238,13 @@ jobs:
env:
UPDATER_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
run: echo "updater=$([ -n "$UPDATER_KEY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
if: steps.signing.outputs.updater == 'true'
with: { ref: "${{ env.TAG }}" }
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
if: steps.signing.outputs.updater == 'true'
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
if: steps.signing.outputs.updater == 'true'
with: { node-version: 22, cache: pnpm }
- if: steps.signing.outputs.updater == 'true'
@@ -270,7 +270,7 @@ jobs:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
RELEASE_ID: ${{ inputs.release_id }}
with:
+6 -6
Переглянути файл
@@ -37,7 +37,7 @@ jobs:
outputs:
release_id: ${{ steps.release.outputs.id }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with: { ref: "${{ env.TAG }}" }
- name: Tag matches app version
run: |
@@ -57,7 +57,7 @@ jobs:
exit 1
fi
- id: release
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
NIGHTLY: ${{ inputs.nightly == true }}
with:
@@ -126,7 +126,7 @@ jobs:
echo "::warning::PLUGIN_SIGNING_KEY is not set: the official plugins are not published"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
if: steps.key.outputs.skip != 'true'
with: { ref: "${{ env.TAG }}" }
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
@@ -135,10 +135,10 @@ jobs:
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: steps.key.outputs.skip != 'true'
with: { key: release-plugins }
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
if: steps.key.outputs.skip != 'true'
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
if: steps.key.outputs.skip != 'true'
with: { node-version: 22 }
# Builds the web pages; fails when a checked-in component isn't built from these sources.
@@ -183,7 +183,7 @@ jobs:
needs: [create-release, binaries, plugins]
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
with:
+6 -1
Переглянути файл
@@ -4,7 +4,7 @@
`src/ui/brands/*.svg` use the unmodified logo paths from
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:odin`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:odin`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos; `dotnet_dark.svg` lightens .NET's purple for dark themes). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## DuckDB symbol
@@ -75,6 +75,11 @@ The read/write usage filter assets (`actions/showReadAccess{,_dark}.svg` and
[`e992ff4750b4c36afe2caadfa8b191a8f36fb7a2`](https://github.com/JetBrains/intellij-community/tree/e992ff4750b4c36afe2caadfa8b191a8f36fb7a2/platform/icons/src/expui/actions).
Their original copyright headers and Apache-2.0 licensing are retained.
The `actions/showImportStatements{,_dark}.svg` asset is copied unmodified from
`platform/icons/src/expui/actions/` at intellij-community commit
[`71290c3174`](https://github.com/JetBrains/intellij-community/tree/71290c3174/platform/icons/src).
Its original copyright headers and Apache-2.0 licensing are retained.
- [intellij-rust](https://github.com/intellij-rust/intellij-rust) (MIT):
`src/main/resources/icons/expui/rustFile{,_dark}.svg` →
`src/ui/expui/fileTypes/rust{,_dark}.svg`;
+53 -4
Переглянути файл
@@ -25,6 +25,8 @@ type Key = (PathBuf, PathBuf, String);
#[derive(Default)]
pub struct AgentCatalogs {
state: Mutex<State>,
/// Orders model requests by when they were made, not when they reach `state`.
tickets: std::sync::atomic::AtomicU64,
#[cfg(test)]
clock_ms: std::sync::atomic::AtomicU64,
}
@@ -49,6 +51,8 @@ struct Entry {
abort: Option<tokio::task::AbortHandle>,
flight_model: Option<String>,
requested_model: Option<String>,
/// Ticket of the newest model request applied: an older one arriving late can't supersede it.
model_ticket: u64,
model_failures: HashMap<String, ModelFailure>,
catalog: Option<CatalogData>,
}
@@ -254,11 +258,13 @@ impl AgentCatalogs {
}
let unavailable = || "The agent did not report settings for the selected model".to_owned();
let spec = shared.spec(provider).ok_or_else(unavailable)?;
// Taken now: the blocking task may run after a newer selection's request.
let ticket = self.ticket();
let flight = {
let catalogs = self.clone();
let shared = shared.clone();
let model = model.to_owned();
tokio::task::spawn_blocking(move || catalogs.request(&shared, spec, false, Some(&model)).1)
tokio::task::spawn_blocking(move || catalogs.request_with(&shared, spec, false, Some(&model), ticket).1)
.await
.map_err(|e| e.to_string())?
};
@@ -331,12 +337,49 @@ impl AgentCatalogs {
}
/// Start or join a lookup. No queued refresh can outlive the request that asked for it.
/// The model the running discovery of `provider` looks up, if one is running.
#[cfg(test)]
pub(crate) fn flight_model(&self, shared: &Shared, provider: &str) -> Option<Option<String>> {
let state = self.state.lock();
let entry = state.entries.get(&Self::key(shared, provider))?;
entry.flight.as_ref().map(|_| entry.flight_model.clone())
}
#[cfg(test)]
pub(crate) fn request_as_of(
self: &Arc<Self>,
shared: &Arc<Shared>,
spec: provider::ProviderSpec,
model: &str,
ticket: u64,
) -> Option<watch::Receiver<bool>> {
self.request_with(shared, spec, false, Some(model), ticket).1
}
pub(crate) fn ticket(&self) -> u64 {
self.tickets.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1
}
pub(crate) fn request(
self: &Arc<Self>,
shared: &Arc<Shared>,
spec: provider::ProviderSpec,
force: bool,
model: Option<&str>,
) -> (AgentModelCatalog, Option<watch::Receiver<bool>>) {
let ticket = self.ticket();
self.request_with(shared, spec, force, model, ticket)
}
/// [`Self::request`] for a request made when `ticket` was taken. A model request older than
/// the newest one applied neither changes the requested model nor supersedes its flight.
fn request_with(
self: &Arc<Self>,
shared: &Arc<Shared>,
spec: provider::ProviderSpec,
force: bool,
model: Option<&str>,
ticket: u64,
) -> (AgentModelCatalog, Option<watch::Receiver<bool>>) {
let key = Self::key(shared, &spec.id);
let context = LaunchContext::new(spec.clone(), &shared.paths.project_root);
@@ -388,6 +431,7 @@ impl AgentCatalogs {
abort: None,
flight_model: None,
requested_model: None,
model_ticket: 0,
model_failures: HashMap::new(),
},
);
@@ -404,10 +448,15 @@ impl AgentCatalogs {
|| (!fresh && catalog.model_option().is_none())
})
.map(str::to_owned);
if model.is_some() && entry.requested_model.as_deref() != model {
entry.requested_model = model.map(str::to_owned);
let stale = model.is_some() && ticket < entry.model_ticket;
if model.is_some() && !stale {
entry.model_ticket = ticket;
if entry.requested_model.as_deref() != model {
entry.requested_model = model.map(str::to_owned);
}
}
let superseded = model.is_some()
let superseded = !stale
&& model.is_some()
&& entry.flight.is_some()
&& (entry.flight_model.is_some() || target.is_some())
&& entry.flight_model.as_deref() != target.as_deref();
+4 -1
Переглянути файл
@@ -1574,6 +1574,9 @@ pub struct AgentPluginCapabilities {
pub hook_files: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub stdio_commands: Vec<String>,
/// Language server commands (`.lsp.json`, `lsp.json`, a manifest's `lspServers`) the agent starts.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub lsp_commands: Vec<String>,
#[serde(default)]
pub has_lsp: bool,
#[serde(default)]
@@ -1581,7 +1584,7 @@ pub struct AgentPluginCapabilities {
/// Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub native_harnesses: Vec<String>,
/// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents).
/// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands`, `lsp_commands` and `hook_files` contents).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub capability_hash: Option<String>,
+20 -4
Переглянути файл
@@ -134,13 +134,14 @@ impl Cli for Process {
}
}
/// Claude Code's configuration directory (`CLAUDE_CONFIG_DIR`, else `~/.claude`).
/// Claude Code's configuration directory (`CLAUDE_CONFIG_DIR`, else `~/.claude`); an empty value counts as
/// unset, and a leading `~` is the user's home.
pub(crate) fn config_dir(env: &[(String, String)]) -> Option<PathBuf> {
let set = env
.iter()
.find(|(k, _)| k == "CLAUDE_CONFIG_DIR")
.map(|(_, v)| PathBuf::from(v))
.or_else(|| std::env::var_os("CLAUDE_CONFIG_DIR").map(PathBuf::from));
.find(|(k, v)| k == "CLAUDE_CONFIG_DIR" && !v.is_empty())
.map(|(_, v)| PathBuf::from(crate::provider::expand_home(v)))
.or_else(|| std::env::var_os("CLAUDE_CONFIG_DIR").filter(|v| !v.is_empty()).map(PathBuf::from));
set.or_else(|| {
std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(|h| Path::new(&h).join(".claude"))
})
@@ -160,4 +161,19 @@ mod tests {
"--resume a --fork-session --session-id b"
);
}
#[test]
fn an_empty_config_dir_is_unset() {
let dir = config_dir(&[("CLAUDE_CONFIG_DIR".into(), String::new())]);
assert!(dir.is_some_and(|d| d.is_absolute()));
let set = config_dir(&[("CLAUDE_CONFIG_DIR".into(), "/home/me/.claude-work".into())]);
assert_eq!(set, Some(PathBuf::from("/home/me/.claude-work")));
}
#[test]
fn a_config_dir_under_the_home_folder_can_start_with_a_tilde() {
let home = crate::home_dir().unwrap();
let dir = config_dir(&[("CLAUDE_CONFIG_DIR".into(), "~/.claude-work".into())]);
assert_eq!(dir, Some(home.join(".claude-work")));
}
}
+5 -4
Переглянути файл
@@ -37,12 +37,13 @@ const DISCOVER_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(5) } else
const EARLY_CANCEL: Duration = Duration::from_secs(2);
const EXIT_GRACE: Duration = Duration::from_millis(100);
/// Copilot's configuration directory (`COPILOT_HOME`, otherwise `<home>/.copilot`).
/// Copilot's configuration directory (`COPILOT_HOME`, otherwise `<home>/.copilot`); an empty value counts as
/// unset, and a leading `~` is the user's home.
pub(crate) fn config_dir(env: &[(String, String)], home: Option<&Path>) -> Option<PathBuf> {
env.iter()
.find(|(key, _)| key == "COPILOT_HOME")
.map(|(_, value)| PathBuf::from(value))
.or_else(|| std::env::var_os("COPILOT_HOME").map(PathBuf::from))
.find(|(key, value)| key == "COPILOT_HOME" && !value.is_empty())
.map(|(_, value)| PathBuf::from(crate::provider::expand_home(value)))
.or_else(|| std::env::var_os("COPILOT_HOME").filter(|v| !v.is_empty()).map(PathBuf::from))
.or_else(|| home.map(|home| home.join(".copilot")))
}
+10
Переглянути файл
@@ -124,7 +124,17 @@ fn resolves_copilot_home_from_agent_env_or_user_home() {
);
if std::env::var_os("COPILOT_HOME").is_none() {
assert_eq!(super::config_dir(&[], Some(home)), Some(home.join(".copilot")));
assert_eq!(
super::config_dir(&[("COPILOT_HOME".into(), String::new())], Some(home)),
Some(home.join(".copilot"))
);
}
assert!(super::config_dir(&[("COPILOT_HOME".into(), String::new())], Some(home)).is_some_and(|d| d.is_absolute()));
let user_home = crate::home_dir().unwrap();
assert_eq!(
super::config_dir(&[("COPILOT_HOME".into(), "~/.copilot-work".into())], Some(home)),
Some(user_home.join(".copilot-work"))
);
}
#[test]
+145 -4
Переглянути файл
@@ -2203,13 +2203,15 @@ fn inspect_fetched_subtree(
}
skill_names.sort();
skill_names.dedup();
let ExecutableCapabilities { mcp_names, stdio_commands, hook_files, capability_hash, .. } = executable;
let ExecutableCapabilities { mcp_names, stdio_commands, lsp_commands, hook_files, capability_hash, .. } =
executable;
if formats.is_empty()
&& skill_names.is_empty()
&& mcp_names.is_empty()
&& rule_count == 0
&& hook_files.is_empty()
&& lsp_commands.is_empty()
&& subagent_count == 0
&& command_count == 0
{
@@ -2241,6 +2243,7 @@ fn inspect_fetched_subtree(
command_count,
hook_files,
stdio_commands,
lsp_commands,
has_lsp,
has_canvas_or_app,
native_harnesses: native_harnesses.into_iter().collect(),
@@ -2337,6 +2340,7 @@ impl PluginFiles for DiskPluginFiles<'_> {
struct ExecutableCapabilities {
mcp_names: BTreeSet<String>,
stdio_commands: Vec<String>,
lsp_commands: Vec<String>,
hook_files: Vec<String>,
hook_harnesses: BTreeSet<String>,
capability_hash: Option<String>,
@@ -2345,6 +2349,7 @@ struct ExecutableCapabilities {
fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabilities {
let mut mcp_names = BTreeSet::new();
let mut stdio_commands = BTreeSet::new();
let mut lsp_commands = BTreeSet::new();
let mut hook_files = BTreeSet::new();
let mut hook_harnesses = BTreeSet::new();
let mut hook_contents: BTreeMap<String, Vec<u8>> = BTreeMap::new();
@@ -2369,6 +2374,9 @@ fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabil
if let Some(mcp) = manifest.get("mcpServers") {
collect_in_memory_mcp_summary(mcp, files, &mut mcp_names, &mut stdio_commands);
}
if let Some(lsp) = manifest.get("lspServers") {
collect_lsp_commands(lsp, files, &mut lsp_commands, &mut HashSet::new());
}
let (paths, objects) = manifest_hook_declarations(rel, &manifest);
for path in paths {
add_hook_file(path, &mut hook_contents);
@@ -2382,6 +2390,13 @@ fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabil
collect_in_memory_mcp_summary(&value, files, &mut mcp_names, &mut stdio_commands);
}
}
for rel in [".lsp.json", "lsp.json"] {
if let Some(bytes) = files.read(rel)
&& let Ok(value) = parse_jsonc(&String::from_utf8_lossy(&bytes))
{
collect_lsp_commands(&value, files, &mut lsp_commands, &mut HashSet::new());
}
}
for (label, bytes) in inline_hooks {
hook_files.insert(label.clone());
hook_contents.insert(label, bytes);
@@ -2400,12 +2415,14 @@ fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabil
}
}
let stdio_commands: Vec<String> = stdio_commands.into_iter().collect();
let lsp_commands: Vec<String> = lsp_commands.into_iter().collect();
let digests: Vec<(&str, &[u8])> =
hook_contents.iter().map(|(rel, bytes)| (rel.as_str(), bytes.as_slice())).collect();
let capability_hash = compute_capability_hash(&stdio_commands, &digests);
let capability_hash = compute_capability_hash(&stdio_commands, &lsp_commands, &digests);
ExecutableCapabilities {
mcp_names,
stdio_commands,
lsp_commands,
hook_files: hook_files.into_iter().collect(),
hook_harnesses,
capability_hash,
@@ -2478,6 +2495,59 @@ fn collect_in_memory_mcp_summary_inner(
}
}
/// `name: command args env:K=V` for each language server a `.lsp.json` file, a manifest's
/// `lspServers` value (an object, a path to such a file, or a list of either) declares.
fn collect_lsp_commands(
val: &Value,
files: &dyn PluginFiles,
out: &mut BTreeSet<String>,
visited_files: &mut HashSet<String>,
) {
match val {
Value::String(rel) => {
let clean = rel.trim().trim_start_matches("./").trim_start_matches('/');
if visited_files.insert(clean.to_owned())
&& let Some(bytes) = files.read(clean)
&& let Ok(parsed) = parse_jsonc(&String::from_utf8_lossy(&bytes))
{
collect_lsp_commands(&parsed, files, out, visited_files);
}
}
Value::Array(items) => {
for item in items {
collect_lsp_commands(item, files, out, visited_files);
}
}
Value::Object(obj) => {
if let Some(nested) = obj.get("lspServers") {
collect_lsp_commands(nested, files, out, visited_files);
return;
}
for (name, entry) in obj {
let Some(cmd) = entry.get("command").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
else {
continue;
};
let mut parts = vec![cmd.to_owned()];
parts.extend(extract_string_array(entry.get("args")));
let env = entry
.get("env")
.and_then(Value::as_object)
.into_iter()
.flatten()
.map(|(key, value)| format!("{}={}", key, scalar_capability_value(value)))
.collect::<Vec<_>>()
.join(" ");
if !env.is_empty() {
parts.push(format!("env:{env}"));
}
out.insert(format!("{name}: {}", parts.join(" ")));
}
}
_ => {}
}
}
fn scalar_capability_value(value: &Value) -> String {
match value {
Value::String(value) => value.clone(),
@@ -2746,6 +2816,7 @@ pub fn inspect_plugin_dir(
&& mcp_names.is_empty()
&& rule_files.is_empty()
&& hook_rel_names.is_empty()
&& executable.lsp_commands.is_empty()
&& subagent_count == 0
&& command_count == 0)
{
@@ -2803,6 +2874,7 @@ pub fn inspect_plugin_dir(
command_count,
hook_files: hook_rel_names,
stdio_commands: executable.stdio_commands,
lsp_commands: executable.lsp_commands,
has_lsp,
has_canvas_or_app,
native_harnesses: native_harnesses.into_iter().collect(),
@@ -2815,8 +2887,12 @@ pub fn inspect_plugin_dir(
})
}
fn compute_capability_hash(stdio_commands: &[String], hooks: &[(&str, &[u8])]) -> Option<String> {
if stdio_commands.is_empty() && hooks.is_empty() {
fn compute_capability_hash(
stdio_commands: &[String],
lsp_commands: &[String],
hooks: &[(&str, &[u8])],
) -> Option<String> {
if stdio_commands.is_empty() && lsp_commands.is_empty() && hooks.is_empty() {
return None;
}
let mut hasher = blake3::Hasher::new();
@@ -2828,6 +2904,14 @@ fn compute_capability_hash(stdio_commands: &[String], hooks: &[(&str, &[u8])]) -
hasher.update(cmd.as_bytes());
hasher.update(b"\0");
}
// Only added when present, so the hash of a plugin without language servers stays as approved before.
let mut sorted_lsp = lsp_commands.to_vec();
sorted_lsp.sort();
for cmd in sorted_lsp {
hasher.update(b"lsp:");
hasher.update(cmd.as_bytes());
hasher.update(b"\0");
}
for (rel, bytes) in hooks {
hasher.update(b"hook:");
hasher.update(rel.as_bytes());
@@ -5682,6 +5766,63 @@ mod tests {
assert!(codex_text.contains("https://github.com/acme/plugins.git"));
}
#[test]
fn language_servers_a_plugin_ships_need_execution_consent() {
let tmp = tempfile::tempdir().unwrap();
// A `.lsp.json` file, an inline `lspServers` object and a path to one in the manifest.
let file = tmp.path().join("lsp-file");
write(&file.join(".claude-plugin/plugin.json"), r#"{"name":"lsp-file","version":"1.0.0"}"#);
write(&file.join(".lsp.json"), r#"{"go":{"command":"/bin/sh","args":["-c","touch /tmp/x"]}}"#);
let inline = tmp.path().join("lsp-inline");
write(
&inline.join(".claude-plugin/plugin.json"),
r#"{"name":"lsp-inline","lspServers":{"py":{"command":"pyright-langserver","args":["--stdio"],"env":{"A":"1"}}}}"#,
);
let linked = tmp.path().join("lsp-linked");
write(&linked.join(".claude-plugin/plugin.json"), r#"{"name":"lsp-linked","lspServers":"./servers.json"}"#);
write(&linked.join("servers.json"), r#"{"rs":{"command":"rust-analyzer"}}"#);
let cases = [
(&file, "go: /bin/sh -c touch /tmp/x"),
(&inline, "py: pyright-langserver --stdio env:A=1"),
(&linked, "rs: rust-analyzer"),
];
for (dir, command) in cases {
let installed = inspect_plugin_dir(dir, AgentPluginSource::ClaudeUser, McpScope::User, None, true)
.unwrap()
.capabilities;
let scanned = scan_local_subtree(dir, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin").unwrap();
let preview = inspect_fetched_subtree(&scanned, "plugin", None).unwrap().capabilities;
for caps in [&installed, &preview] {
assert_eq!(caps.lsp_commands, vec![command.to_owned()], "{}", dir.display());
assert!(caps.requires_consent, "{}", dir.display());
assert!(caps.capability_hash.is_some());
}
// The install dialog's approval matches the hash of the installed folder.
assert_eq!(installed.capability_hash, preview.capability_hash);
}
// Changing the server command invalidates an earlier approval.
let before = inspect_plugin_dir(&file, AgentPluginSource::ClaudeUser, McpScope::User, None, true).unwrap();
write(&file.join(".lsp.json"), r#"{"go":{"command":"gopls"}}"#);
let after = inspect_plugin_dir(&file, AgentPluginSource::ClaudeUser, McpScope::User, None, true).unwrap();
assert_ne!(before.capabilities.capability_hash, after.capabilities.capability_hash);
// A plugin without language servers keeps its hash: approvals given before stay valid.
let mut v1 = blake3::Hasher::new();
v1.update(b"openidea-agent-plugin-caps-v1\0mcp:k8s: npx -y k8s-mcp\0");
assert_eq!(
compute_capability_hash(&["k8s: npx -y k8s-mcp".to_owned()], &[], &[]),
Some(v1.finalize().to_hex().to_string())
);
let skills_only = tmp.path().join("skills-only");
write(&skills_only.join(".claude-plugin/plugin.json"), r#"{"name":"skills-only"}"#);
write(&skills_only.join("skills/a/SKILL.md"), "---\nname: a\ndescription: A\n---\n");
let caps = inspect_plugin_dir(&skills_only, AgentPluginSource::ClaudeUser, McpScope::User, None, true)
.unwrap()
.capabilities;
assert!(caps.lsp_commands.is_empty() && !caps.requires_consent && caps.capability_hash.is_none());
}
#[test]
fn marketplace_browse_preview_and_pinned_native_install_roundtrip() {
let tmp = tempfile::tempdir().unwrap();
+33 -1
Переглянути файл
@@ -194,6 +194,9 @@ impl ProviderSpec {
}
fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
for (_, value) in &mut self.env {
*value = expand_home(value);
}
if let Some(program) = self.managed_cli.take() {
self.command = program;
} else if self.driver != Driver::Acp {
@@ -235,7 +238,7 @@ impl ProviderSpec {
return Some(LoginLaunch {
program,
args: separate_args.iter().map(|s| (*s).to_owned()).collect(),
env: self.env.iter().cloned().collect(),
env: self.env.iter().map(|(name, value)| (name.clone(), expand_home(value))).collect(),
});
}
@@ -1201,6 +1204,21 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
specs
}
/// `value` with a leading `~` (alone or before a path separator) replaced by the user's home,
/// as a shell does for `NAME=~/path`.
pub(crate) fn expand_home(value: &str) -> String {
let rest = match value.strip_prefix('~') {
Some("") => "",
Some(rest) if rest.starts_with('/') || rest.starts_with('\\') => &rest[1..],
_ => return value.to_owned(),
};
match crate::home_dir() {
Some(home) if rest.is_empty() => home.to_string_lossy().into_owned(),
Some(home) => home.join(rest).to_string_lossy().into_owned(),
None => value.to_owned(),
}
}
/// Whether `command` resolves to an executable (a path, or a name on [`ide_core::tool_path::search_path`]).
#[cfg(test)]
pub(crate) fn installed(command: &str) -> bool {
@@ -1647,6 +1665,20 @@ mod tests {
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
}
#[test]
fn a_leading_tilde_in_the_environment_is_the_home_folder() {
let home = crate::home_dir().unwrap();
let mut spec = builtin_spec("claude").unwrap();
for (name, value) in [("A", "~/.claude-work"), ("B", "~"), ("C", "a~/b"), ("D", "~user/x"), ("E", "/abs")] {
spec.env.push((name.into(), value.into()));
}
let resolved = spec.resolve_for_launch(Path::new("."));
let value = |name: &str| resolved.env.iter().find(|(n, _)| n == name).map(|(_, v)| v.clone()).unwrap();
assert_eq!(value("A"), home.join(".claude-work").to_string_lossy());
assert_eq!(value("B"), home.to_string_lossy());
assert_eq!((value("C"), value("D"), value("E")), ("a~/b".into(), "~user/x".into(), "/abs".into()));
}
#[test]
fn acp_adapters_of_native_agents_are_unlisted_until_customized() {
let dir = tempfile::tempdir().unwrap();
+50
Переглянути файл
@@ -4455,6 +4455,56 @@ async fn rapid_idle_model_switches_share_discovery_and_never_apply_a_stale_compl
restored.shutdown();
}
/// A model request reaches the catalogs from a blocking task, so it may arrive after a newer
/// selection's; arriving late, it must not supersede (and abort) the newer discovery.
#[tokio::test(flavor = "multi_thread")]
async fn a_late_model_request_never_supersedes_a_newer_discovery() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.model_options.lock() = HashMap::from([
("big".into(), effort_options(&["low", "high"], "high")),
("small".into(), effort_options(&["minimal", "medium"], "minimal")),
("plain".into(), vec![]),
]);
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude-acp".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.shutdown();
let restored = Arc::new(manager(tmp.path(), agent.clone()));
let (catalogs, shared) = (restored.shared.paths.catalogs.clone(), restored.shared.clone());
let spec = || shared.spec("claude-acp").unwrap();
let late = catalogs.ticket();
let (release, gate) = std::sync::mpsc::channel();
*agent.model_config_gate.lock() = Some(gate);
let newer = {
let (catalogs, shared) = (catalogs.clone(), shared.clone());
tokio::spawn(async move { catalogs.load_levels(&shared, "claude-acp", "plain").await })
};
tokio::time::timeout(Duration::from_secs(5), async {
while agent.model_config_gate.lock().is_some() {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert_eq!(catalogs.flight_model(&shared, "claude-acp"), Some(Some("plain".into())));
catalogs.request_as_of(&shared, spec(), "small", late);
assert_eq!(catalogs.flight_model(&shared, "claude-acp"), Some(Some("plain".into())), "not superseded");
release.send(()).unwrap();
assert_eq!(newer.await.unwrap().unwrap(), Vec::<AgentConfigOption>::new());
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn explicit_service_tier_reaches_the_session_even_when_it_matches_the_reported_default() {
for value in [None, Some("false"), Some("true")] {
+45 -5
Переглянути файл
@@ -49,9 +49,8 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
&script,
format!(
r#"import org.gradle.util.GradleVersion
gradle.projectsEvaluated {{
def p = gradle.rootProject.project({})
{}
def register = {{ p ->
def update = {{ t ->
t.dependsOn 'processResources'
// Resolved here so the action holds no task or project (configuration cache).
@@ -63,9 +62,14 @@ gradle.projectsEvaluated {{
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaUpdateResources', update)
else p.tasks.create('openideaUpdateResources', update)
}}
// After the project's own `afterEvaluate` callbacks, as with `projectsEvaluated`; init scripts also
// run in included builds, which may have a project at the same path.
if (isolated) gradle.lifecycle.afterProject {{ p -> if (p.path == {path} && p.gradle.parent == null) p.afterEvaluate {{ register(p) }} }}
else gradle.projectsEvaluated {{ register(gradle.rootProject.project({path})) }}
"#,
literal(&p.path),
literal(&manifest.to_string_lossy())
crate::gradle::ISOLATED_PROJECTS_SCRIPT,
literal(&manifest.to_string_lossy()),
path = literal(&p.path),
),
)?;
return Ok(ResourceBuild {
@@ -204,6 +208,42 @@ mod tests {
assert!(!script.contains("build/resources/main")); // The task owns custom output locations.
}
/// The resource-update task's init script on a real Gradle, with and without Isolated Projects (#8261).
#[test]
fn gradle_resources_update_with_and_without_isolated_projects() {
let Some((gradle, version)) = crate::gradle::test_gradle() else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return;
};
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let builds = crate::gradle::write_test_builds(
&base,
// The build realizes tasks early and moves the resources in `afterEvaluate`.
"plugins { id 'java' }\ntasks.all {}\nafterEvaluate { sourceSets.main.output.resourcesDir = file('build/custom') }\n",
"plugins { java }\ntasks.all {}\nafterEvaluate { sourceSets[\"main\"].output.setResourcesDir(file(\"build/custom\")) }\n",
&[("src/main/resources/static/index.html", "after")],
);
for (root, isolated) in builds {
// Before Gradle 8.8 the script keeps reading the project from the root, as before.
if isolated && version < (8, 8) {
continue;
}
let cache = root.join("cache");
let mut model = crate::load(&root, &cache, None);
model.gradle[0].command = gradle.to_string_lossy().into_owned();
for pass in if isolated { &["miss", "hit"][..] } else { &["run"][..] } {
let plan = plan(&root, &model, Path::new("app"), &cache).unwrap();
let out = crate::gradle::run_test_gradle(&root, &plan.cwd, &plan.command, &plan.args)
.unwrap_or_else(|e| panic!("{pass}:\n{e}"));
assert_eq!(out.contains("Reusing configuration cache."), *pass == "hit", "{out}");
let dir = fs::read_to_string(cache.join("resource-output.txt")).unwrap();
assert_eq!(Path::new(&dir), root.join("app/build/custom"));
assert_eq!(fs::read_to_string(Path::new(&dir).join("static/index.html")).unwrap(), "after");
}
}
}
#[test]
fn publishes_maven_and_gradle_resource_outputs_to_the_runtime_classpath() {
for layout in ["target/classes", "build/resources/main", "custom resource output"] {
+5 -6
Переглянути файл
@@ -603,17 +603,16 @@ pub fn gradle_compile_file_plan(
fs::create_dir_all(cache)?;
let init_script = cache.join("gradle-compile-cp.init.gradle");
fs::write(&init_script, GRADLE_COMPILE_CP_INIT_SCRIPT)?;
let args = vec![
"--console=plain".into(),
"-q".into(),
"-Dorg.gradle.configuration-cache=false".into(),
let gradle_dir = subdir(root, &gradle.dir);
let mut args = vec!["--console=plain".into(), "-q".into(), "-Dorg.gradle.configuration-cache=false".into()];
args.extend(crate::gradle::no_isolated_projects(&gradle_dir, &gradle.env));
args.extend([
"--init-script".into(),
init_script.to_string_lossy().into_owned(),
format!("-Popenidea.target={}", project.path),
format!("-Popenidea.scope={scope}"),
"help".into(),
];
let gradle_dir = subdir(root, &gradle.dir);
]);
let mut reported: Option<String> = None;
let out = process::run_bounded(&gradle.command, &args, &gradle_dir, &gradle.env, cancel, |_, line| {
if let Some(json) = line.strip_prefix("@openidea-compile-cp\t") {
+170
Переглянути файл
@@ -12,6 +12,65 @@ use std::time::{Duration, Instant};
pub const SETTINGS_FILES: &[&str] = &["settings.gradle.kts", "settings.gradle"];
pub const BUILD_FILES: &[&str] = &["build.gradle.kts", "build.gradle"];
const ISOLATED_PROJECTS: [&str; 2] = ["org.gradle.isolated-projects", "org.gradle.unsafe.isolated-projects"];
/// Arguments turning Isolated Projects off for the IDE's own model reads of the build at `dir`, when
/// the build enables it: Gradle refuses them without the configuration cache, and their init scripts
/// read projects across the build. Other builds keep their command line. Gradle 9 still reads the
/// Gradle 8 name.
pub(crate) fn no_isolated_projects(dir: &Path, env: &BTreeMap<String, String>) -> Vec<String> {
// The variable as the Gradle process gets it: the project's and the login shell's environment too.
let inherited = ide_core::process::host_vars_in(dir)
.chain(ide_core::process::shell_env_in(dir))
.find(|(key, _)| key == "GRADLE_USER_HOME")
.map(|(_, value)| value);
let home = user_home(dir, env, inherited, dirs::home_dir());
if !isolated_projects(dir, home.as_deref()) {
return Vec::new();
}
ISOLATED_PROJECTS.iter().map(|key| format!("-D{key}=false")).collect()
}
fn user_home(
dir: &Path,
env: &BTreeMap<String, String>,
inherited: Option<std::ffi::OsString>,
home: Option<PathBuf>,
) -> Option<PathBuf> {
let set = env.get("GRADLE_USER_HOME").map(PathBuf::from).or_else(|| inherited.map(PathBuf::from));
set.map(|path| dir.join(path)).or_else(|| Some(home?.join(".gradle")))
}
/// The user home's `gradle.properties` overrides the build's; when the two names disagree, Gradle
/// keeps Isolated Projects off.
fn isolated_projects(dir: &Path, user_home: Option<&Path>) -> bool {
let user = user_home.map(file_properties).unwrap_or_default();
let build = file_properties(dir);
let values: Vec<bool> = ISOLATED_PROJECTS
.iter()
.filter_map(|key| user.get(*key).or_else(|| build.get(*key)))
.map(|value| value.eq_ignore_ascii_case("true"))
.collect();
values.contains(&true) && !values.contains(&false)
}
/// Groovy for init scripts that add a task to one project (needs `GradleVersion` imported): `isolated`
/// is whether the build enables Isolated Projects on Gradle 8.8+, where such a script must register
/// it from `gradle.lifecycle` instead of reading the project from the root. `BuildFeatures` (8.5+) is
/// only injected, so a class compiled at run time reads it.
pub(crate) const ISOLATED_PROJECTS_SCRIPT: &str = r#"def isolated = false
// When that fails, the build is treated as one without Isolated Projects.
if (GradleVersion.current() >= GradleVersion.version('8.8')) try {
def features = new GroovyClassLoader(Gradle.classLoader).parseClass('''
abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin<org.gradle.api.invocation.Gradle> {
@javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures()
boolean active
void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) }
}''')
gradle.pluginManager.apply(features)
isolated = gradle.plugins.getPlugin(features).active
} catch (Throwable ignored) {}
"#;
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -1125,6 +1184,70 @@ pub(crate) fn has_war_plugin(script: &str) -> bool {
script.split(|c: char| !c.is_alphanumeric() && c != '_').any(|word| word == "war")
}
/// A real Gradle for tests (`OPENIDEA_TEST_GRADLE`, else `gradle` on the search path) and its
/// version as (major, minor); `None` without it or without `JAVA_HOME`.
#[cfg(test)]
pub(crate) fn test_gradle() -> Option<(PathBuf, (u32, u32))> {
std::env::var_os("JAVA_HOME")?;
let gradle = std::env::var_os("OPENIDEA_TEST_GRADLE")
.map(PathBuf::from)
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()))?;
let out = std::process::Command::new(&gradle).arg("--version").output().ok()?;
let text = String::from_utf8_lossy(&out.stdout).into_owned();
let version = text.lines().find_map(|l| l.strip_prefix("Gradle "))?.trim().to_owned();
let mut parts = version.split('.').map(|p| p.parse::<u32>().unwrap_or(0));
Some((gradle.clone(), (parts.next()?, parts.next().unwrap_or(0))))
}
/// Runs a planned Gradle command in `root`; its output, or the failure with it.
#[cfg(test)]
pub(crate) fn run_test_gradle(root: &Path, cwd: &str, command: &str, args: &[String]) -> Result<String, String> {
let out = std::process::Command::new(command).args(args).current_dir(root.join(cwd)).output().unwrap();
let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
if out.status.success() { Ok(text) } else { Err(text) }
}
/// Two builds for init-script tests, each with `files` under `app`: one in the Groovy DSL without
/// Isolated Projects, one in the Kotlin DSL with it (and so the configuration cache).
#[cfg(test)]
pub(crate) fn write_test_builds(
base: &Path,
groovy: &str,
kotlin: &str,
files: &[(&str, &str)],
) -> [(PathBuf, bool); 2] {
let plain = base.join("plain");
let isolated = base.join("isolated");
let mut all = vec![
(plain.join("gradle.properties"), "org.gradle.daemon=false\n".to_owned()),
(plain.join("settings.gradle"), "rootProject.name = 'plain'\ninclude 'app'\n".to_owned()),
(plain.join("app/build.gradle"), groovy.to_owned()),
(
isolated.join("gradle.properties"),
"org.gradle.daemon=false\norg.gradle.configuration-cache=true\n\
org.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n"
.to_owned(),
),
(
isolated.join("settings.gradle.kts"),
"rootProject.name = \"isolated\"\ninclude(\"app\")\nincludeBuild(\"inc\")\n".to_owned(),
),
// An included build with a project at the same path, whose tasks are realized early.
(isolated.join("inc/settings.gradle.kts"), "rootProject.name = \"inc\"\ninclude(\"app\")\n".to_owned()),
(isolated.join("inc/app/build.gradle.kts"), "plugins { java }\ntasks.all {}\n".to_owned()),
(isolated.join("app/build.gradle.kts"), kotlin.to_owned()),
];
for (rel, text) in files {
all.push((plain.join("app").join(rel), text.to_string()));
all.push((isolated.join("app").join(rel), text.to_string()));
}
for (path, text) in all {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
[(plain, false), (isolated, true)]
}
#[cfg(test)]
mod tests {
#[test]
@@ -1578,6 +1701,53 @@ dependencies {
use super::*;
#[test]
fn isolated_projects_are_read_from_the_build_and_the_user_home() {
let temp = tempfile::tempdir().unwrap();
let (build, home) = (temp.path().join("build"), temp.path().join("home"));
std::fs::create_dir_all(&build).unwrap();
std::fs::create_dir_all(&home).unwrap();
let enabled = |user_home: Option<&Path>| isolated_projects(&build, user_home);
assert!(!enabled(Some(&home)), "no gradle.properties");
std::fs::write(build.join("gradle.properties"), "org.gradle.jvmargs=-Xmx2g\n").unwrap();
assert!(!enabled(Some(&home)), "not enabled");
std::fs::write(build.join("gradle.properties"), "org.gradle.isolated-projects=true\n").unwrap();
assert!(enabled(Some(&home)), "the build's gradle.properties");
assert!(enabled(None));
std::fs::write(home.join("gradle.properties"), "org.gradle.isolated-projects=false\n").unwrap();
assert!(!enabled(Some(&home)), "the user home overrides the build");
std::fs::write(build.join("gradle.properties"), "").unwrap();
std::fs::write(home.join("gradle.properties"), "org.gradle.unsafe.isolated-projects = true\n").unwrap();
assert!(enabled(Some(&home)), "the user home's gradle.properties, Gradle 8 name");
std::fs::write(build.join("gradle.properties"), "org.gradle.isolated-projects=false\n").unwrap();
assert!(!enabled(Some(&home)), "disabled under either name wins");
}
#[test]
fn the_gradle_user_home_is_the_builds_setting_then_the_environment_then_dot_gradle() {
let dir = Path::new("/build");
let env = BTreeMap::from([("GRADLE_USER_HOME".to_owned(), "/setting".to_owned())]);
let inherited = || Some(std::ffi::OsString::from("/inherited"));
let home = || Some(PathBuf::from("/home/u"));
assert_eq!(user_home(dir, &env, inherited(), home()), Some(PathBuf::from("/setting")));
assert_eq!(user_home(dir, &BTreeMap::new(), inherited(), home()), Some(PathBuf::from("/inherited")));
assert_eq!(user_home(dir, &BTreeMap::new(), None, home()), Some(PathBuf::from("/home/u/.gradle")));
let relative = Some(std::ffi::OsString::from("gradle-home"));
assert_eq!(user_home(dir, &BTreeMap::new(), relative, home()), Some(PathBuf::from("/build/gradle-home")));
}
#[test]
fn builds_without_isolated_projects_keep_their_command_line() {
let temp = tempfile::tempdir().unwrap();
let env = BTreeMap::from([("GRADLE_USER_HOME".to_owned(), temp.path().join("home").display().to_string())]);
assert!(no_isolated_projects(temp.path(), &env).is_empty());
std::fs::write(temp.path().join("gradle.properties"), "org.gradle.isolated-projects=true\n").unwrap();
assert_eq!(
no_isolated_projects(temp.path(), &env),
["-Dorg.gradle.isolated-projects=false", "-Dorg.gradle.unsafe.isolated-projects=false"]
);
}
#[test]
fn settings_scripts() {
let kts = r#"
+1
Переглянути файл
@@ -300,6 +300,7 @@ pub(super) fn gradle_step(
&["--console=plain", "--no-configuration-cache"],
&subdir(root, &g.dir),
);
step.args.extend(crate::gradle::no_isolated_projects(&step.cwd, &g.env));
step.args.extend(["--init-script".to_owned(), init.to_string_lossy().into_owned()]);
step.args.push(format!("-Popenidea.build.output={}", output_root.display()));
if let Some(file) = model_file {
+16
Переглянути файл
@@ -792,6 +792,22 @@ fn builds_gradle_projects_with_javac_and_only_what_changed() {
assert_eq!(error.path.as_deref(), Some(f.root.join("lib/src/main/java/l/L.java").as_path()));
}
#[test]
fn builds_gradle_projects_that_enable_isolated_projects() {
let Some(f) = Fixture::gradle(&[
(
"gradle.properties",
"org.gradle.daemon=false\norg.gradle.configuration-cache=true\norg.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n",
),
("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"),
]) else {
return;
};
let built = f.launch(false);
assert_eq!(built.failure, None, "{:?}\n{}", built.messages, build_output_tail(&f.events.lock().unwrap()));
assert!(f.out("t.app/classes/a/A.class").is_file());
}
#[test]
fn leaves_gradle_projects_with_other_compilers_to_gradle() {
let Some(f) = Fixture::gradle(&[
+40 -4
Переглянути файл
@@ -499,11 +499,9 @@ pub fn sync_gradle_model(
"-q".into(),
// The init script reports the evaluated projects, even when a build enables the configuration cache.
"-Dorg.gradle.configuration-cache=false".into(),
"--init-script".into(),
init_script.to_string_lossy().into_owned(),
"tasks".into(),
"--all".into(),
];
args.extend(gradle::no_isolated_projects(&root.join(&model.dir), &options.env));
args.extend(["--init-script".into(), init_script.to_string_lossy().into_owned(), "tasks".into(), "--all".into()]);
if options.offline {
args.push("--offline".into());
}
@@ -1208,4 +1206,42 @@ mod tests {
assert!(args.contains("-T1"), "args: {args}");
assert!(args.contains("maven-help-plugin:"), "args: {args}");
}
/// Needs `JAVA_HOME` and Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the search path).
#[test]
fn gradle_sync_lists_tasks_of_builds_that_enable_isolated_projects() {
let has_jdk = std::env::var_os("JAVA_HOME").is_some();
let gradle = std::env::var_os("OPENIDEA_TEST_GRADLE")
.map(std::path::PathBuf::from)
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()));
let Some(gradle) = gradle.filter(|_| has_jdk) else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return;
};
let temp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(temp.path()).unwrap();
let files = [
(
"gradle.properties",
"org.gradle.daemon=false\norg.gradle.configuration-cache=true\norg.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n",
),
("settings.gradle", "rootProject.name = 'root'\ninclude 'lib'\n"),
("build.gradle", ""),
("lib/build.gradle", "plugins { id 'java' }\n"),
];
for (rel, text) in files {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
let mut model = gradle::load(&root).unwrap();
model.command = gradle.to_string_lossy().into_owned();
let cache = root.join(".cache");
sync_gradle_model(&root, &cache, &model, &SyncOptions::default(), &CancellationToken::new(), &|_| {}).unwrap();
let loaded = crate::load(&root, &cache, None);
let build = &loaded.gradle[0];
assert_eq!(build.sync_error, None);
let lib = build.projects.iter().find(|p| p.path == ":lib").expect("the reported :lib project");
assert!(lib.tasks.iter().any(|t| t.name == "compileJava"), "{:?}", lib.tasks);
}
}
+45 -5
Переглянути файл
@@ -161,9 +161,8 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
&script,
format!(
r#"import org.gradle.util.GradleVersion
gradle.projectsEvaluated {{
def p = gradle.rootProject.project({})
{}
def register = {{ p ->
def artifact = {{ t ->
t.dependsOn 'war'
// Resolved here so the action holds no task or project (configuration cache).
@@ -180,9 +179,14 @@ gradle.projectsEvaluated {{
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaTomcatArtifact', artifact)
else p.tasks.create('openideaTomcatArtifact', artifact)
}}
// After the project's own `afterEvaluate` callbacks, as with `projectsEvaluated`; init scripts also
// run in included builds, which may have a project at the same path.
if (isolated) gradle.lifecycle.afterProject {{ p -> if (p.path == {path} && p.gradle.parent == null) p.afterEvaluate {{ register(p) }} }}
else gradle.projectsEvaluated {{ register(gradle.rootProject.project({path})) }}
"#,
groovy_literal(path),
groovy_literal(&manifest.to_string_lossy())
crate::gradle::ISOLATED_PROJECTS_SCRIPT,
groovy_literal(&manifest.to_string_lossy()),
path = groovy_literal(path),
),
)?;
let task = format!("{}:openideaTomcatArtifact", path.trim_end_matches(':'));
@@ -274,6 +278,42 @@ mod tests {
assert!(!crate::gradle::has_war_plugin("// plugins { war }"));
}
/// The WAR task's init script on a real Gradle, with and without Isolated Projects (#8261).
#[test]
fn gradle_war_artifact_builds_with_and_without_isolated_projects() {
let Some((gradle, version)) = crate::gradle::test_gradle() else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return;
};
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let builds = crate::gradle::write_test_builds(
&base,
// The build realizes tasks early and applies the WAR plugin in `afterEvaluate`.
"plugins { id 'java' }\ntasks.all {}\nafterEvaluate { apply plugin: 'war' }\n",
"plugins { java }\ntasks.all {}\nafterEvaluate { apply(plugin = \"war\") }\n",
&[("src/main/webapp/index.html", "war")],
);
for (root, isolated) in builds {
// Before Gradle 8.8 the script keeps reading the project from the root, as before.
if isolated && version < (8, 8) {
continue;
}
let cache = root.join("cache");
let mut model = crate::load(&root, &cache, None);
model.gradle[0].command = gradle.to_string_lossy().into_owned();
let id = artifacts(&root, &model).into_iter().find(|a| a.id.contains(":app")).expect("the app WAR").id;
for pass in if isolated { &["miss", "hit"][..] } else { &["run"][..] } {
let plan = build(&root, &model, &id, &cache).unwrap();
let out = crate::gradle::run_test_gradle(&root, &plan.cwd, &plan.command, &plan.args)
.unwrap_or_else(|e| panic!("{pass}:\n{e}"));
assert_eq!(out.contains("Reusing configuration cache."), *pass == "hit", "{out}");
let war = fs::read_to_string(cache.join("artifact-path.txt")).unwrap();
assert!(Path::new(&war).is_file() && war.ends_with(".war"), "{war}");
}
}
}
#[test]
fn gradle_manifest_paths_preserve_windows_characters() {
for path in [r"C:\工作 区\Tomcat's cache\artifact-path.txt", r"\\server\share\artifact-path.txt"] {
+2
Переглянути файл
@@ -467,6 +467,8 @@ pub enum LspRefreshKind {
FlutterOutline,
/// Spring bean markers of open documents may have changed.
SpringBeanMarkers,
/// Spring AOP markers of open documents may have changed.
SpringAopMarkers,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
+19 -3
Переглянути файл
@@ -170,8 +170,24 @@ pub const GRADLE_FILE_ENCODING_SCRIPT: &str = "\
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
allprojects {
each(tasks.withType(JavaExec)) { t -> t.defaultCharacterEncoding = 'UTF-8' }
// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there
// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is
// only injected, so a class compiled here reads it.
def isolated = false
// When that fails, the build is treated as one without Isolated Projects.
if (GradleVersion.current() >= GradleVersion.version('8.8')) try {
def features = new GroovyClassLoader(Gradle.classLoader).parseClass('''
abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin<org.gradle.api.invocation.Gradle> {
@javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures()
boolean active
void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) }
}''')
gradle.pluginManager.apply(features)
isolated = gradle.plugins.getPlugin(features).active
} catch (Throwable ignored) {}
def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) }
eachProject { p ->
each(p.tasks.withType(JavaExec)) { t -> t.defaultCharacterEncoding = 'UTF-8' }
}
";
@@ -622,7 +638,7 @@ mod tests {
#[test]
fn gradle_script_respects_the_builds_own_file_encoding() {
let s = GRADLE_FILE_ENCODING_SCRIPT;
assert!(s.contains("each(tasks.withType(JavaExec))"), "{s}");
assert!(s.contains("each(p.tasks.withType(JavaExec))"), "{s}");
assert!(s.contains("t.defaultCharacterEncoding = 'UTF-8'"), "{s}");
assert!(!s.contains("doFirst"), "the build must be able to override the default: {s}");
assert!(!s.contains("withType(Test)") && !s.contains("JavaCompile"), "{s}");
+90 -12
Переглянути файл
@@ -37,13 +37,16 @@ pub fn prepare(cmd: &mut Command) -> &mut Command {
cmd
}
/// cmd.exe drops an inherited variable longer than this outright, and batch files (`.cmd`,
/// `.bat`) always run through it.
#[cfg_attr(not(windows), allow(dead_code))]
const CMD_ENV_LIMIT: usize = 8191;
#[cfg(windows)]
fn compact_batch_path(cmd: &mut Command) {
use std::os::windows::ffi::OsStrExt;
use std::path::{Component, Prefix};
// Rust runs these files through cmd.exe, which drops inherited variables over this limit.
const CMD_ENV_LIMIT: usize = 8191;
// Rust runs these files through cmd.exe.
let extension = Path::new(cmd.get_program()).extension();
if !extension.is_some_and(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")) {
return;
@@ -52,25 +55,80 @@ fn compact_batch_path(cmd: &mut Command) {
Some((_, path)) => path.map(OsStr::to_owned),
None => std::env::var_os("PATH"),
};
let Some(path) = path.filter(|p| p.encode_wide().count() > CMD_ENV_LIMIT) else { return };
// The IDE includes possible locations of as-yet uninstalled tools. Prune paths that are
// missing now, keeping search precedence and leaving UNC and relative paths alone.
let dirs = std::env::split_paths(&path).filter(|dir| {
let Some(path) = path else { return };
// The IDE includes possible locations of as-yet uninstalled tools: drop the ones missing
// now, leaving UNC and relative paths alone.
let present = |dir: &Path| {
let local = dir.is_absolute()
&& matches!(dir.components().next(), Some(Component::Prefix(p))
if matches!(p.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_)));
!local
|| !std::fs::symlink_metadata(dir)
.is_err_and(|e| matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory))
});
if let Ok(compact) = std::env::join_paths(dirs)
&& compact.encode_wide().count() <= CMD_ENV_LIMIT
{
};
if let Some(compact) = compact_path_list(&path, CMD_ENV_LIMIT, present, short_path) {
cmd.env("PATH", compact);
}
}
/// The 8.3 form of `dir`, when the volume has one.
#[cfg(windows)]
fn short_path(dir: &Path) -> Option<std::path::PathBuf> {
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use windows_sys::Win32::Storage::FileSystem::GetShortPathNameW;
let wide: Vec<u16> = dir.as_os_str().encode_wide().chain(Some(0)).collect();
let mut buf = vec![0u16; wide.len()];
let len = u32::try_from(buf.len()).ok()?;
// SAFETY: both buffers are valid for their lengths and `wide` is NUL-terminated.
let written = unsafe { GetShortPathNameW(wide.as_ptr(), buf.as_mut_ptr(), len) } as usize;
// 0 is an error; a value of at least the buffer's length is the size a longer form needs.
if written == 0 || written >= buf.len() {
return None;
}
buf.truncate(written);
Some(OsString::from_wide(&buf).into())
}
/// `path` (a `PATH` list) made to fit `limit` UTF-16 units where it is longer: later
/// duplicates (without case on Windows) and directories `present` rejects are dropped, keeping
/// the search order; when that is still too long, directories take `shorten`'s form, longest
/// first, until it fits. `None` when `path` fits already or nothing got shorter.
#[cfg_attr(not(windows), allow(dead_code))]
fn compact_path_list(
path: &OsStr,
limit: usize,
present: impl Fn(&Path) -> bool,
shorten: impl Fn(&Path) -> Option<std::path::PathBuf>,
) -> Option<OsString> {
let width = |s: &OsStr| s.to_string_lossy().encode_utf16().count();
let original = width(path);
if original <= limit {
return None;
}
let mut seen = std::collections::HashSet::new();
let mut dirs: Vec<std::path::PathBuf> = std::env::split_paths(path)
.filter(|d| !d.as_os_str().is_empty() && seen.insert(path_entry_key(d)) && present(d))
.collect();
let mut joined = std::env::join_paths(&dirs).ok()?;
if width(&joined) > limit {
let mut longest: Vec<usize> = (0..dirs.len()).collect();
longest.sort_by_key(|&i| std::cmp::Reverse(width(dirs[i].as_os_str())));
let mut total = width(&joined);
for i in longest {
if total <= limit {
break;
}
if let Some(short) = shorten(&dirs[i]).filter(|s| width(s.as_os_str()) < width(dirs[i].as_os_str())) {
total -= width(dirs[i].as_os_str()) - width(short.as_os_str());
dirs[i] = short;
}
}
joined = std::env::join_paths(&dirs).ok()?;
}
(width(&joined) < original).then_some(joined)
}
/// Starts the child as the leader of its own process group on Unix, so [`kill_tree`] and
/// [`terminate_tree`] reach what it starts in turn (`gh` → `git`, `npm` → `node`, `mvnw` →
/// the JVM). A no-op elsewhere: on Windows the tree is found from the child's process id.
@@ -1295,6 +1353,26 @@ mod tests {
assert_eq!(session, pid, "the child leads its own session");
}
#[test]
fn compacts_a_path_too_long_for_cmd() {
let sep = if cfg!(windows) { ";" } else { ":" };
let join = |dirs: &[&str]| OsString::from(dirs.join(sep));
let long = |name: &str| format!("/tools/{}/{name}", "x".repeat(40));
let (a, b, c, gone) = (long("a"), long("b"), long("c"), long("gone"));
let present = |d: &Path| !d.ends_with("gone");
let never = |_: &Path| None;
// Fits already: left alone.
assert_eq!(compact_path_list(&join(&[&a, &b]), 200, present, never), None);
// Later duplicates and missing directories go, the order stays.
let path = join(&[&a, &gone, &b, &a, &format!("{b}/"), "", &c]);
assert_eq!(compact_path_list(&path, 160, present, never), Some(join(&[&a, &b, &c])));
// Still too long: the longest directories take their short form until it fits.
let shorten = |d: &Path| Some(std::path::PathBuf::from(format!("/S/{}", d.file_name()?.to_string_lossy())));
let path = join(&[&a, &format!("{b}-longer"), &c]);
assert_eq!(compact_path_list(&path, 120, present, shorten), Some(join(&[&a, "/S/b-longer", &c])));
assert_eq!(compact_path_list(&path, 60, present, shorten), Some(join(&["/S/a", "/S/b-longer", "/S/c"])));
}
#[test]
fn process_alive_tells_live_from_dead_pids() {
assert!(process_alive(std::process::id()));
+110 -1
Переглянути файл
@@ -9,7 +9,23 @@ const GRADLE_INIT: &str = r#"// Written by OpenIDEA for Run with Coverage.
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
allprojects { p ->
// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there
// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is
// only injected, so a class compiled here reads it.
def isolated = false
// When that fails, the build is treated as one without Isolated Projects.
if (GradleVersion.current() >= GradleVersion.version('8.8')) try {
def features = new GroovyClassLoader(Gradle.classLoader).parseClass('''
abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin<org.gradle.api.invocation.Gradle> {
@javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures()
boolean active
void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) }
}''')
gradle.pluginManager.apply(features)
isolated = gradle.plugins.getPlugin(features).active
} catch (Throwable ignored) {}
def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) }
eachProject { p ->
p.plugins.withId('java') {
p.apply plugin: 'jacoco'
each(p.tasks.withType(Test)) { t -> t.finalizedBy('jacocoTestReport') }
@@ -582,4 +598,97 @@ mod tests {
CoveragePrepared::Unsupported { .. }
));
}
/// The coverage init script on a real Gradle, with and without Isolated Projects (#8261).
/// Needs `JAVA_HOME` and Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the search path).
#[test]
fn gradle_init_script_configures_each_project() {
let gradle = std::env::var_os("JAVA_HOME").and_then(|_| {
std::env::var_os("OPENIDEA_TEST_GRADLE")
.map(std::path::PathBuf::from)
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()))
});
let Some(gradle) = gradle else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return;
};
let version = std::process::Command::new(&gradle).arg("--version").output().unwrap();
let version =
String::from_utf8_lossy(&version.stdout).lines().find_map(|l| l.strip_prefix("Gradle ").map(str::to_owned));
let mut parts = version
.expect("a `Gradle x.y` line")
.trim()
.split('.')
.map(|p| p.parse::<u32>().unwrap_or(0))
.collect::<Vec<_>>();
parts.resize(2, 0);
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let script = base.join("coverage.init.gradle");
std::fs::write(&script, GRADLE_INIT).unwrap();
for (name, props) in [
("plain", ""),
(
"isolated",
"org.gradle.configuration-cache=true\norg.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n",
),
] {
if name == "isolated" && (parts[0], parts[1]) < (8, 8) {
// Before Gradle 8.8 the script keeps reading every project, as the plain build checked.
continue;
}
let root = base.join(name);
for (rel, text) in [
("gradle.properties", format!("org.gradle.daemon=false\n{props}")),
("settings.gradle", "include 'lib'\n".to_owned()),
("build.gradle", String::new()),
(
"lib/build.gradle",
"plugins { id 'java' }\nrepositories { mavenCentral() }\n\
dependencies { testImplementation 'org.junit.jupiter:junit-jupiter:5.11.0'; \
testRuntimeOnly 'org.junit.platform:junit-platform-launcher' }\n\
test { useJUnitPlatform() }\n"
.to_owned(),
),
(
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static int one() { return 1; } }\n".to_owned(),
),
(
"lib/src/test/java/l/LTest.java",
"package l;\nclass LTest { @org.junit.jupiter.api.Test void one() { L.one(); } }\n".to_owned(),
),
] {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
let report = root.join("lib/build/reports/jacoco/test/jacocoTestReport.xml");
// With Isolated Projects the configuration cache is on: a miss, then a hit.
for pass in if name == "isolated" { &["miss", "hit"][..] } else { &["run"][..] } {
// Fresh test results and execution data, so each pass runs the tests under the agent.
for dir in ["lib/build/jacoco", "lib/build/test-results", "lib/build/reports"] {
let _ = std::fs::remove_dir_all(root.join(dir));
}
let out = std::process::Command::new(&gradle)
.args(["--console=plain", "--init-script"])
.arg(&script)
.arg(":lib:test")
.current_dir(&root)
.output()
.unwrap();
let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
assert!(out.status.success(), "{name} {pass}:\n{text}");
let xml =
std::fs::read_to_string(&report).unwrap_or_else(|_| panic!("{name} {pass}: no report\n{text}"));
assert_eq!(text.contains("Reusing configuration cache."), *pass == "hit", "{name} {pass}:\n{text}");
let method =
xml.split(r#"<method name="one" desc="()I""#).nth(1).and_then(|m| m.split("</method>").next());
assert!(
method.is_some_and(|m| m.contains(r#"<counter type="LINE" missed="0" covered="1"/>"#)),
"{name} {pass}: {xml}"
);
}
}
}
}
+304 -1
Переглянути файл
@@ -1433,6 +1433,83 @@ impl Pool {
r
}
/// Runs exactly one statement in a driver-enforced read-only session: a write (including one
/// in a `WITH` clause) fails in the database, whatever the statement text looks like. Drivers
/// without such a session are refused rather than guarded by a keyword check. SQL that
/// [`split`](crate::split::split) reads as more than one statement is refused here as well, so
/// a direct caller cannot hand a MySQL/PostgreSQL multi-statement batch to the session.
pub async fn execute_read_only(
&self,
sql: &str,
max_rows: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
let driver = self.driver();
let statements = crate::split::split(sql, driver);
if statements.len() != 1 {
return Err(IdeError::invalid(format!(
"read-only execution runs exactly one statement, but this SQL has {}",
statements.len()
)));
}
if self.transaction_read_only() {
// The pool runs every statement in a verified `BEGIN READ ONLY` transaction.
return self.execute_from(sql, 0, max_rows, cancel).await;
}
if !matches!(self, Pool::Sqlite(_) | Pool::Postgres(_) | Pool::Mysql(_) | Pool::Oracle(_)) {
return Err(read_only_unsupported(driver));
}
if driver == DbDriver::Mysql {
// The server runs executable comments and further statements that `split` reads as
// comments; the client cannot turn its multi-statement handling off.
crate::split::mysql_guard(sql)?;
}
if let Pool::Oracle(_) = self {
// Oracle commits a statement through `Held::command`, which would end the read-only
// transaction before the user's statement runs. It has its own non-committing path.
let started = Instant::now();
let mut conn = Held::acquire_own(self).await?;
let result = match &mut conn {
Held::Oracle(c) => crate::oracle::execute_read_only(c, sql, max_rows, cancel).await,
_ => unreachable!("acquired an Oracle connection"),
};
conn.discard().await;
return result.map(|fetched| query_result(sql, fetched, started));
}
// A dedicated connection keeps the transaction or PRAGMA off every pooled connection.
let mut conn = Held::acquire_own(self).await?;
if let Held::Sqlite(c) = &mut conn {
// A future dropped mid-session (a timeout, a shutdown) must close this connection
// instead of returning one with `PRAGMA query_only` still on to the pool.
c.close_on_drop();
}
if let Err(e) = open_read_only_session(&mut conn, driver, sql).await {
conn.discard().await;
return Err(e);
}
let result = match conn.execute_from(self, sql, 0, max_rows, cancel).await {
Ok(result) => result,
Err(e) => {
// A failed or cancelled statement must not return an open transaction or query_only.
conn.discard().await;
return Err(e);
}
};
match close_read_only_session(&mut conn, driver).await {
Ok(()) => {
if let Held::Sqlite(c) = &mut conn {
// The PRAGMA is off again: this connection may go back to the pool.
c.return_to_pool().await;
}
Ok(result)
}
Err(e) => {
conn.discard().await;
Err(e)
}
}
}
/// Runs `statements` in one transaction; each must change `expect_one`
/// row when flagged (table editor submits).
pub async fn transaction(&self, statements: &[(String, bool)]) -> IdeResult<u64> {
@@ -1530,6 +1607,161 @@ impl Pool {
}
}
fn driver_name(driver: DbDriver) -> &'static str {
driver.display_name()
}
pub(crate) fn read_only_unsupported(driver: DbDriver) -> IdeError {
IdeError::invalid(format!(
"{} has no read-only session: OpenIDEA refuses to run statements on it without one",
driver_name(driver)
))
}
/// Opens the driver's read-only session, then checks that the server took it.
async fn open_read_only_session(conn: &mut Held, driver: DbDriver, sql: &str) -> IdeResult<()> {
match driver {
DbDriver::Sqlite => {
conn.command("PRAGMA query_only = ON").await?;
if read_only_setting(conn, "PRAGMA query_only").await?.as_deref() != Some("1") {
return Err(IdeError::invalid("SQLite did not enter a read-only session: PRAGMA query_only is not 1"));
}
}
DbDriver::Postgres => {
conn.command("BEGIN READ ONLY").await?;
if read_only_setting(conn, "SHOW transaction_read_only").await?.as_deref() != Some("on") {
return Err(IdeError::invalid(
"PostgreSQL did not enter a read-only transaction: transaction_read_only is not on",
));
}
if let Held::Postgres(c) = conn {
// sqlx sends the statement as the UTF-8 bytes of the Rust string and decodes text
// results as UTF-8, but the server converts those bytes from `client_encoding`
// before parsing them, and the source's startup script can change that (and
// `standard_conforming_strings`) on every connection. Pin and verify both, as the
// MySQL path pins utf8mb4.
pg_read_only::pin_encoding(c).await.map_err(db_err)?;
// No transaction guard checks this dedicated session's statement, so let the
// server parse it as one command before the simple query protocol runs it.
pg_read_only::check_single_always(c, sql).await.map_err(db_err)?;
}
}
DbDriver::Mysql => {
// sqlx sends a statement as the UTF-8 bytes of the Rust string and decodes text
// results as UTF-8, but the server's parser reads those bytes as
// `character_set_client`. Pin that connection to utf8mb4 (over the source's
// `charset` and any startup script) and verify it: in an East-Asian multibyte
// charset an ASCII backslash or quote can be swallowed as the second byte of a
// character, so the server would split a statement differently than `split` does.
conn.command("SET NAMES utf8mb4").await?;
let (client, connection) = mysql_connection_charsets(conn).await?;
for (name, value) in
[("character_set_client", client.as_str()), ("character_set_connection", connection.as_str())]
{
if !mysql_charset_is_safe(value) {
return Err(IdeError::invalid(format!(
"this MySQL/MariaDB connection reads SQL as {value} ({name}): the server could read \
the statement's quotes or backslashes differently than the statement splitter, so \
a hidden second statement could run"
)));
}
}
// MySQL has no per-transaction flag to read back (`transaction_read_only` is the
// session default, which `START TRANSACTION READ ONLY` does not change). Set and
// verify the session default first, so a vendor that ignores the clause is refused;
// the statement boundary above is what keeps a second, overriding transaction out.
conn.command("SET SESSION TRANSACTION READ ONLY").await?;
if !mysql_session_read_only(conn).await? {
return Err(IdeError::invalid(
"MySQL/MariaDB did not take the read-only session: its transaction_read_only setting is off",
));
}
let mode = read_only_setting(conn, "SELECT @@SESSION.sql_mode").await?.unwrap_or_default();
if let Some(flag) = mysql_quote_mode_unsupported(&mode) {
return Err(IdeError::invalid(format!(
"this MySQL/MariaDB session sets {flag}: its quotes no longer read like the statement splitter's, \
so a hidden second statement could run"
)));
}
conn.command("START TRANSACTION READ ONLY").await?;
if !mysql_session_read_only(conn).await? {
return Err(IdeError::invalid(
"MySQL/MariaDB did not keep the read-only session: its transaction_read_only setting is off",
));
}
}
DbDriver::Oracle => unreachable!("Oracle read-only sessions run in oracle::execute_read_only"),
_ => return Err(read_only_unsupported(driver)),
}
Ok(())
}
/// The session's read-only default: `transaction_read_only` (MySQL 5.7+, MariaDB 11+), then
/// MariaDB's older `tx_read_only`. A server with neither has no read-only session to verify.
async fn mysql_session_read_only(conn: &mut Held) -> IdeResult<bool> {
for name in ["transaction_read_only", "tx_read_only"] {
let sql = format!("SELECT @@SESSION.{name}");
match read_only_setting(conn, &sql).await {
Ok(Some(value)) => {
return match value.trim().to_ascii_lowercase().as_str() {
"1" | "on" => Ok(true),
"0" | "off" => Ok(false),
other => Err(IdeError::invalid(format!("MySQL/MariaDB reported {name} as {other}"))),
};
}
Ok(None) => {}
Err(error) if error.message.contains("Unknown system variable") => {}
Err(error) => return Err(error),
}
}
Err(IdeError::invalid(
"this MySQL-compatible server has no transaction_read_only (or tx_read_only) setting, \
so its read-only session cannot be verified",
))
}
/// Whether a MySQL connection charset decodes every ASCII byte as itself, so the server reads a
/// statement the way [`split`](crate::split::split) and `mysql_guard` do. UTF-8 charsets, ASCII,
/// latin1 and binary qualify; East-Asian multibyte charsets (GBK, Big5, SJIS, CP932, GB18030,
/// EUC-KR…) can consume an ASCII byte as part of a multibyte character.
fn mysql_charset_is_safe(name: &str) -> bool {
matches!(name.trim().to_ascii_lowercase().as_str(), "utf8mb4" | "utf8mb3" | "utf8" | "ascii" | "latin1" | "binary")
}
/// The session's `character_set_client` and `character_set_connection`; `SET NAMES` sets both.
async fn mysql_connection_charsets(conn: &mut Held) -> IdeResult<(String, String)> {
let (_, rows, _, _, _) =
conn.fetch_rows("SELECT @@SESSION.character_set_client, @@SESSION.character_set_connection", 1).await?;
let row = rows
.into_iter()
.next()
.ok_or_else(|| IdeError::invalid("MySQL/MariaDB did not report its connection character set"))?;
let mut columns = row.into_iter();
Ok((columns.next().flatten().unwrap_or_default(), columns.next().flatten().unwrap_or_default()))
}
/// The sql_mode values that change how the server reads quotes; the statement splitter assumes
/// MySQL's defaults, so a session with either could split differently than the server parses.
fn mysql_quote_mode_unsupported(mode: &str) -> Option<&'static str> {
["NO_BACKSLASH_ESCAPES", "ANSI_QUOTES"]
.into_iter()
.find(|flag| mode.split(',').any(|value| value.trim().eq_ignore_ascii_case(flag)))
}
async fn read_only_setting(conn: &mut Held, sql: &str) -> IdeResult<Option<String>> {
let (_, rows, _, _, _) = conn.fetch_rows(sql, 1).await?;
Ok(rows.into_iter().next().and_then(|row| row.into_iter().next().flatten()))
}
/// Ends the read-only session a successful statement ran in.
async fn close_read_only_session(conn: &mut Held, driver: DbDriver) -> IdeResult<()> {
match driver {
DbDriver::Sqlite => conn.command("PRAGMA query_only = OFF").await,
DbDriver::Postgres | DbDriver::Mysql | DbDriver::Oracle => conn.command("ROLLBACK").await,
_ => Ok(()),
}
}
/// A connection of a pool, or one opened beside it that closes when dropped.
pub enum Lease<M: ManageConnection> {
Pooled(bb8::PooledConnection<'static, M>),
@@ -1654,7 +1886,7 @@ impl Held {
fn before_statement(&mut self, sql: &str) {
let control = sql.trim().trim_end_matches(';').trim().to_ascii_uppercase();
if let Held::Mysql(c) = self {
if matches!(control.as_str(), "BEGIN" | "START TRANSACTION") {
if control == "BEGIN" || control == "START TRANSACTION" || control.starts_with("START TRANSACTION ") {
c.in_transaction = true;
return;
}
@@ -2284,4 +2516,75 @@ mod tests {
assert_eq!(bytes_text(vec![0xCA, 0xFE], Cells::Display), "0xCAFE");
assert_eq!(bytes_text(vec![b'a', 0xFF], Cells::Text), "a\u{FFFD}");
}
#[tokio::test]
async fn read_only_execution_refuses_writes_and_leaves_the_pool_usable() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("read-only.db");
std::fs::File::create(&file).unwrap();
let source = DataSource { driver: DbDriver::Sqlite, file: Some(file.into()), ..Default::default() };
let pool = Pool::connect(&source, None, None).await.unwrap();
let cancel = CancellationToken::new();
pool.execute("CREATE TABLE t (x INTEGER)", 1, &cancel).await.unwrap();
let result = pool.execute_read_only("SELECT 1", 1, &cancel).await.unwrap();
assert_eq!(result.rows, vec![vec![Some("1".into())]]);
let refused = pool.execute_read_only("INSERT INTO t VALUES (1)", 10, &cancel).await.unwrap_err();
assert_eq!(refused.kind, ErrorKind::InvalidInput);
assert!(refused.message.to_lowercase().contains("readonly"), "{}", refused.message);
// The guarded statement changed nothing, and the PRAGMA did not stay on the pool.
pool.execute("INSERT INTO t VALUES (2)", 1, &cancel).await.unwrap();
let rows = pool.execute("SELECT x FROM t", 10, &cancel).await.unwrap().rows;
assert_eq!(rows, vec![vec![Some("2".into())]]);
}
#[test]
fn mysql_quote_modes_that_change_lexing_are_named() {
assert_eq!(mysql_quote_mode_unsupported("ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES"), None);
assert_eq!(mysql_quote_mode_unsupported("ANSI_QUOTES,STRICT_TRANS_TABLES"), Some("ANSI_QUOTES"));
assert_eq!(mysql_quote_mode_unsupported("no_backslash_escapes"), Some("NO_BACKSLASH_ESCAPES"));
assert_eq!(mysql_quote_mode_unsupported(""), None);
}
#[test]
fn mysql_connection_charsets_that_can_swallow_ascii_are_refused() {
for safe in ["utf8mb4", "utf8mb3", "utf8", "ascii", "latin1", "binary", "UTF8MB4", " utf8mb4 "] {
assert!(mysql_charset_is_safe(safe), "{safe}");
}
for unsafe_charset in ["gbk", "big5", "sjis", "cp932", "gb18030", "euckr", "ujis", ""] {
assert!(!mysql_charset_is_safe(unsafe_charset), "{unsafe_charset}");
}
}
#[tokio::test]
async fn read_only_execution_refuses_a_second_statement() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("read-only-statements.db");
std::fs::File::create(&file).unwrap();
let source = DataSource { driver: DbDriver::Sqlite, file: Some(file.into()), ..Default::default() };
let pool = Pool::connect(&source, None, None).await.unwrap();
let cancel = CancellationToken::new();
for sql in
["SELECT 1; SELECT 2", "SELECT 1; START TRANSACTION READ WRITE; DELETE FROM t", "SELECT 1; DELETE FROM t"]
{
let refused = pool.execute_read_only(sql, 1, &cancel).await.unwrap_err();
assert_eq!(refused.kind, ErrorKind::InvalidInput, "{sql}");
assert!(refused.message.contains("exactly one statement"), "{sql}: {}", refused.message);
}
// One statement with a trailing `;` (and comments) is still one statement.
let result = pool.execute_read_only("SELECT 1; -- done", 1, &cancel).await.unwrap();
assert_eq!(result.rows, vec![vec![Some("1".into())]]);
}
#[test]
fn drivers_without_a_read_only_session_are_refused() {
for driver in [DbDriver::SqlServer, DbDriver::Clickhouse, DbDriver::Snowflake, DbDriver::Jdbc] {
let error = read_only_unsupported(driver);
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert!(error.message.contains(driver_name(driver)), "{}", error.message);
assert!(error.message.contains("no read-only session"), "{}", error.message);
}
}
}
+68 -3
Переглянути файл
@@ -2,7 +2,7 @@
use super::{Context, Held, PgConnection, PgHandle, PgReadOnly, db_err};
use ide_core::{IdeError, IdeResult};
use sqlx::{Executor, SqlSafeStr};
use sqlx::{Executor, Row, SqlSafeStr};
// Take the first snapshot before user SQL, fixing the transaction characteristics on this backend.
pub(super) const BEGIN: &str = "BEGIN READ ONLY; SELECT 1";
@@ -110,11 +110,64 @@ pub(super) fn startup(statements: &[String]) -> Result<(Vec<String>, Vec<String>
// validates that the text denotes a single command, including under the server's quoting rules.
pub(super) async fn check_single(conn: &mut PgConnection, sql: &str) -> Result<(), sqlx::Error> {
if sql.contains(';') {
conn.prepare(sqlx::AssertSqlSafe(sql.to_owned()).into_sql_str()).await?;
check_single_always(conn, sql).await?;
}
Ok(())
}
/// Prepares `sql` whatever it contains, so the server parses it as one command with its own
/// lexer before the simple query protocol runs it. The dedicated read-only connection has no
/// transaction guard; a difference between the splitter's lexing and the server's (an encoding,
/// a newline or an escape rule) then becomes a parse error instead of a hidden second statement.
pub(super) async fn check_single_always(conn: &mut PgConnection, sql: &str) -> Result<(), sqlx::Error> {
conn.prepare(sqlx::AssertSqlSafe(sql.to_owned()).into_sql_str()).await?;
Ok(())
}
/// Whether the server reports a client encoding that reads the statement's UTF-8 bytes as UTF-8
/// (it spells UTF-8 `UTF8`, and some servers `UNICODE`).
pub(super) fn utf8_client_encoding(name: &str) -> bool {
matches!(name.trim().to_ascii_uppercase().as_str(), "UTF8" | "UNICODE")
}
/// Pins the settings the statement splitter assumes and verifies the server took them. A
/// PostgreSQL server converts the statement text from `client_encoding` before parsing it, so a
/// multibyte client encoding could end a string at a different quote than `split` did; with
/// `standard_conforming_strings` off, a plain `'…'` literal takes backslash escapes `split` does
/// not read. A startup script can set either on every connection, so both are pinned per session.
pub(super) async fn pin_encoding(conn: &mut PgConnection) -> Result<(), sqlx::Error> {
// `SET LOCAL`: both callers are inside the read-only transaction, so the source's own
// session settings come back when it ends.
sqlx::raw_sql("SET LOCAL client_encoding TO 'UTF8'").execute(&mut *conn).await?;
let encoding = pg_show(conn, "SHOW client_encoding").await?;
if !utf8_client_encoding(&encoding) {
return Err(sqlx::Error::Configuration(
format!(
"PostgreSQL reports client_encoding {encoding}, not UTF8: the server could read the statement's \
quotes or escapes differently than the statement splitter, so a hidden second statement could run"
)
.into(),
));
}
sqlx::raw_sql("SET LOCAL standard_conforming_strings TO on").execute(&mut *conn).await?;
let conforming = pg_show(conn, "SHOW standard_conforming_strings").await?;
if !conforming.trim().eq_ignore_ascii_case("on") {
return Err(sqlx::Error::Configuration(
format!(
"PostgreSQL reports standard_conforming_strings {conforming}, not on: the server could read a \
string's backslash differently than the statement splitter, so a hidden second statement could run"
)
.into(),
));
}
Ok(())
}
async fn pg_show(conn: &mut PgConnection, sql: &'static str) -> Result<String, sqlx::Error> {
let row = sqlx::raw_sql(sql).fetch_one(conn).await?;
row.try_get(0)
}
impl PgHandle {
pub(super) async fn start_read_only(&mut self) -> IdeResult<()> {
self.in_transaction = true;
@@ -125,6 +178,8 @@ impl PgHandle {
check_single(self, sql).await.map_err(db_err)?;
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut **self).await.map_err(db_err)?;
}
// After the startup settings: one of them may have changed either setting.
pin_encoding(self).await.map_err(db_err)?;
self.apply_local_path().await
}
.await;
@@ -220,7 +275,17 @@ impl Held {
#[cfg(test)]
mod tests {
use super::validate;
use super::{utf8_client_encoding, validate};
#[test]
fn only_utf8_spellings_pass_the_client_encoding_check() {
for name in ["UTF8", "utf8", "Unicode", " UNICODE "] {
assert!(utf8_client_encoding(name), "{name}");
}
for name in ["GBK", "SJIS", "BIG5", "LATIN1", "SQL_ASCII", ""] {
assert!(!utf8_client_encoding(name), "{name}");
}
}
#[test]
fn names_transaction_control_and_accepts_quoted_text() {
+21
Переглянути файл
@@ -1992,6 +1992,27 @@ impl DbManager {
self.execute_from(id, statement, 0, max_rows, cancel, None).await
}
/// Runs `statement` in a driver-enforced read-only session (see [`Pool::execute_read_only`]).
/// Exactly one statement is required: SQL that splits into several is refused at the
/// connection layer, so a direct caller cannot smuggle in a second one. Not recorded in the
/// query history: it runs outside the console, only after the caller confirmed the exact
/// statement. `id` is one data source id; callers that expose this to agents must also require
/// one unqualified id and a source that is not plugin-owned.
pub async fn execute_read_only_query(
&self,
id: &str,
statement: &str,
max_rows: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
// Refuse a driver without a read-only session before opening (and connecting) its pool.
let source = self.source(id)?;
if !matches!(source.driver, DbDriver::Sqlite | DbDriver::Postgres | DbDriver::Mysql | DbDriver::Oracle) {
return Err(conn::read_only_unsupported(source.driver));
}
self.pool(id).await?.execute_read_only(statement, max_rows, cancel).await
}
/// Refuses transaction control anywhere in a guarded console script before running its first statement.
pub async fn validate_script(&self, id: &str, statements: &[split::SqlStatement]) -> IdeResult<()> {
self.validate_console_script(id, statements, None).await
+95 -2
Переглянути файл
@@ -315,8 +315,10 @@ fn open(state: &State) -> Result<OracleHandle, OracleError> {
Ok(OracleHandle { conn: Some(conn), context })
}
/// Runs `f` with the connection on the blocking pool. Cancelling drops the
/// connection instead of returning it (its statement keeps running server-side).
/// Runs `f` with the connection on the blocking pool. Cancelling stops the wait and drops the
/// connection instead of returning it, but only when the blocking call ends: the driver has no
/// break API, so the statement keeps running server-side until it finishes, and closing the
/// connection then rolls its transaction back.
async fn with_conn<T>(
c: &mut OracleConnection,
cancel: &CancellationToken,
@@ -367,6 +369,53 @@ pub(crate) async fn run(
with_conn(c, cancel, move |conn| statements(conn, &state, &sql, skip, max, mode)).await
}
/// Runs one statement in a verified read-only transaction on its own connection. Auto-commit is
/// off whatever the source's mode: [`statement`] must not commit the transaction away, and the
/// transaction is always rolled back (a dropped connection rolls it back server-side too).
pub(crate) async fn execute_read_only(
c: &mut OracleConnection,
sql: &str,
max: usize,
cancel: &CancellationToken,
) -> IdeResult<Fetched> {
let sql = sql.to_owned();
with_conn(c, cancel, move |conn| {
// `SET TRANSACTION READ ONLY` must be the first statement of its transaction; a startup
// script may have left one open.
conn.rollback().map_err(|e| oracle_err(&e))?;
statement(conn, "SET TRANSACTION READ ONLY", 0, 0, Cells::Text, false)?;
verify_read_only(conn)?;
// The user's statement is the only other statement in the transaction; `split` is not
// used here, so a `;` cannot smuggle in a second one.
let result = statement(conn, &sql, 0, max, Cells::Display, false);
let rollback = conn.rollback().map_err(|e| oracle_err(&e));
match (result, rollback) {
(Ok(fetched), Ok(())) => Ok(fetched),
(Err(error), _) => Err(error),
(Ok(_), Err(error)) => Err(error),
}
})
.await
}
/// Proves the server took `SET TRANSACTION READ ONLY`: a locking read is refused in a read-only
/// transaction (`ORA-01456`). `NOWAIT` keeps the probe from waiting on another session's DUAL
/// lock if the transaction did not take; no row is locked when it did.
fn verify_read_only(conn: &mut oracledb::Connection) -> IdeResult<()> {
match conn.query_row("SELECT 1 FROM DUAL FOR UPDATE NOWAIT", &[]) {
Ok(_) => Err(IdeError::invalid("Oracle did not enter a read-only transaction: a locking read succeeded")),
Err(e) if read_only_violation(&e) => Ok(()),
Err(e) => Err(IdeError::new(
ErrorKind::PermissionDenied,
format!("Oracle did not confirm the read-only transaction: {}", oracle_err(&e).message),
)),
}
}
fn read_only_violation(e: &oracledb::Error) -> bool {
matches!(e.kind(), oracledb::ErrorKind::DbError(db) if db.code() as u32 == 1456)
}
/// The table editor's edits in one transaction.
pub(crate) async fn transaction(c: &mut OracleConnection, statements: &[(String, bool)]) -> IdeResult<u64> {
if c.state.read_only {
@@ -1028,6 +1077,50 @@ mod tests {
drop(raw);
}
/// The read-only session `execute_read_only` opens: a write and `EXPLAIN PLAN` (which writes
/// `PLAN_TABLE`) are refused by the database, and no change is left behind. Skipped unless
/// `OPENIDEA_ORACLE_TEST` names a live server.
#[tokio::test]
async fn a_read_only_session_refuses_writes_and_leaves_no_change() {
let Some(spec) = std::env::var("OPENIDEA_ORACLE_TEST").ok().filter(|s| !s.is_empty()) else { return };
let (source, password) = live_source(&spec);
let secrets = vec![source.user.clone(), source.host.clone(), source.database.clone()];
let pool = crate::conn::Pool::connect(&source, Some(&password), None).await.expect("connect");
let c = CancellationToken::new();
let table = format!("openidea_ro_{}", uuid::Uuid::new_v4().simple());
let _ = drop_if_present(&pool, &format!("table {table}")).await;
pool.rows(&format!("create table {table} (id number)"), 0).await.expect("create table");
pool.rows(&format!("insert into {table} values (1)"), 0).await.expect("insert a row");
let selected =
pool.execute_read_only(&format!("select count(*) from {table}"), 1, &c).await.expect("a query runs");
assert_eq!(selected.rows.first().and_then(|r| r.first().cloned().flatten()).as_deref(), Some("1"));
let write = pool
.execute_read_only(&format!("insert into {table} values (2)"), 1, &c)
.await
.expect_err("a write is refused in the read-only transaction");
assert!(
write.message.contains("1456") || write.message.to_ascii_lowercase().contains("read only"),
"{}",
write.message
);
let explain = pool
.execute_read_only("explain plan for select 1 from dual", 1, &c)
.await
.expect_err("EXPLAIN PLAN writes PLAN_TABLE, so the read-only transaction refuses it");
assert!(
explain.message.contains("1456") || explain.message.to_ascii_lowercase().contains("read only"),
"{}",
explain.message
);
let rows = pool.rows(&format!("select count(*) from {table}"), 1).await.expect("count after the refusals");
assert_eq!(rows.first().and_then(|r| r.first().cloned().flatten()).as_deref(), Some("1"));
let _ = drop_if_present(&pool, &format!("table {table}")).await;
pass("read-only", "a write and EXPLAIN PLAN were refused; the table kept its one row", &secrets);
}
/// An account whose only verifier is `10G` (see `DBA_USERS.PASSWORD_VERSIONS`):
/// the thin driver speaks 11G and later verifiers, so the server rejects even
/// the correct password with ORA-01017 until the account is reset
+29
Переглянути файл
@@ -31,6 +31,20 @@ pub enum DbDriver {
}
impl DbDriver {
/// The driver's name in messages and tool output.
pub fn display_name(self) -> &'static str {
match self {
DbDriver::Sqlite => "SQLite",
DbDriver::Postgres => "PostgreSQL",
DbDriver::Mysql => "MySQL",
DbDriver::SqlServer => "SQL Server",
DbDriver::Clickhouse => "ClickHouse",
DbDriver::Oracle => "Oracle",
DbDriver::Snowflake => "Snowflake",
DbDriver::Jdbc => "JDBC",
}
}
pub fn default_port(self) -> Option<u16> {
match self {
DbDriver::Sqlite | DbDriver::Jdbc => None,
@@ -766,10 +780,16 @@ fn read(path: &Path) -> IdeResult<Vec<DataSource>> {
}
fn write(path: &Path, sources: &[DataSource]) -> IdeResult<()> {
let mut ids = HashSet::new();
for s in sources {
if s.id.is_empty() || s.name.trim().is_empty() {
return Err(IdeError::invalid("every data source needs an id and a name"));
}
// A connection target resolves an id to the first source with it; duplicates make that
// ambiguous (and a crafted file must not redirect a console or a tool to another entry).
if !ids.insert(s.id.as_str()) {
return Err(IdeError::invalid(format!("duplicate data source id '{}'", s.id)));
}
}
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
@@ -983,6 +1003,15 @@ mod tests {
assert_eq!(load(tmp.path()).unwrap(), vec![s]);
}
#[test]
fn saving_refuses_duplicate_ids() {
let tmp = tempfile::tempdir().unwrap();
let source = DataSource { id: "a".into(), name: "one".into(), ..Default::default() };
let duplicate = vec![source.clone(), DataSource { name: "two".into(), ..source }];
let error = save(tmp.path(), &duplicate).unwrap_err();
assert!(error.message.contains("duplicate data source id 'a'"), "{}", error.message);
}
#[test]
fn visibility_change_preserves_patterns_unavailable_names_and_other_scopes() {
let mut introspection = DbIntrospection {
+214 -4
Переглянути файл
@@ -7,6 +7,7 @@
//! Offsets are UTF-16 code units, like everything on the IPC boundary.
use crate::DbDriver;
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -316,9 +317,7 @@ fn split_with(text: &str, driver: DbDriver, mut delimiter: String) -> (Vec<SqlSt
package = false;
}
// MySQL reads `5--1` as a subtraction.
'-' if next == Some('-')
&& (!mysql || chars.get(i + 2).is_none_or(|&(_, c)| c == ' ' || c.is_ascii_control())) =>
{
'-' if next == Some('-') && (!mysql || mysql_dash_comment(chars.get(i + 2).map(|c| c.1))) => {
state = State::LineComment;
i += 1;
}
@@ -452,7 +451,9 @@ fn split_with(text: &str, driver: DbDriver, mut delimiter: String) -> (Vec<SqlSt
}
}
State::LineComment => {
if c == '\n' {
// PostgreSQL ends a `--` comment at `\r` as well as `\n` (`scan.l`:
// `non_newline [^\n\r]`); MySQL and SQLite read a bare `\r` as comment text.
if c == '\n' || (postgres && c == '\r') {
state = State::Code;
}
}
@@ -469,6 +470,128 @@ fn split_with(text: &str, driver: DbDriver, mut delimiter: String) -> (Vec<SqlSt
(out, delimiter)
}
/// MySQL starts a `--` line comment only when the character after it is an ASCII space or an
/// ASCII control character: the server checks the next byte with `my_isspace`/`my_iscntrl`.
/// A Unicode space (U+00A0, U+2000…, U+3000…) is an identifier character to the server, so it
/// must not start a comment here either. Both [`split`] and [`mysql_guard`] use this rule.
fn mysql_dash_comment(next: Option<char>) -> bool {
next.is_none_or(|c| c == ' ' || c.is_ascii_control())
}
/// Whether `/*!` or `/*M!`, whose contents a MySQL/MariaDB server runs as SQL, starts at `i`.
fn executable_comment_start(chars: &[char], i: usize) -> bool {
chars.get(i) == Some(&'/')
&& chars.get(i + 1) == Some(&'*')
&& (chars.get(i + 2) == Some(&'!')
|| (matches!(chars.get(i + 2), Some('M' | 'm')) && chars.get(i + 3) == Some(&'!')))
}
/// Refuses what a MySQL/MariaDB server runs but [`split`] reads as a comment or a literal:
/// executable comments (`/*! … */`, `/*M! … */`), whose contents the server tokenizes as SQL,
/// and `INTO OUTFILE` / `INTO DUMPFILE`, which write a file on the server. The client cannot
/// switch the server's multi-statement handling off, so a statement handed to a MySQL/MariaDB
/// read-only session must pass this first (with the default quote modes, see
/// `mysql_quote_mode_unsupported` in `conn`).
///
/// Executable comments are refused wherever they appear outside a string or a quoted identifier,
/// even inside a genuine comment: the conservative refusal cannot be bypassed if the comment
/// rules of this guard and the server ever diverge.
pub fn mysql_guard(sql: &str) -> IdeResult<()> {
let chars: Vec<char> = sql.chars().collect();
let mut state = State::Code;
// The last word outside quotes and comments, so `INTO /* … */ OUTFILE` is one clause.
let mut last = String::new();
let mut i = 0;
while i < chars.len() {
let c = chars[i];
let next = chars.get(i + 1).copied();
if !matches!(state, State::Single | State::Double | State::Backtick) && executable_comment_start(&chars, i) {
return Err(IdeError::invalid(
"MySQL executable comments (/*! … */ and /*M! … */) are not allowed here: \
the server runs their contents as SQL",
));
}
match state {
State::Code => match c {
'\'' => state = State::Single,
'"' => state = State::Double,
'`' => state = State::Backtick,
'#' => state = State::LineComment,
'-' if next == Some('-') && mysql_dash_comment(chars.get(i + 2).copied()) => {
state = State::LineComment;
i += 1;
}
'/' if next == Some('*') => {
state = State::BlockComment;
i += 1;
}
c if c.is_alphanumeric() || c == '_' || c == '$' => {
let start = i;
while chars.get(i).is_some_and(|c| c.is_alphanumeric() || *c == '_' || *c == '$') {
i += 1;
}
let word: String = chars[start..i].iter().collect::<String>().to_ascii_uppercase();
if matches!(word.as_str(), "OUTFILE" | "DUMPFILE") && last == "INTO" {
return Err(IdeError::invalid(
"MySQL INTO OUTFILE / INTO DUMPFILE is not allowed here: it writes a file on the server",
));
}
last = word;
continue;
}
c if c.is_whitespace() => {}
_ => last.clear(),
},
State::Single => {
if c == '\\' {
i += 1;
} else if c == '\'' {
if next == Some('\'') {
i += 1;
} else {
state = State::Code;
}
}
}
State::Double => {
if c == '\\' {
i += 1;
} else if c == '"' {
if next == Some('"') {
i += 1;
} else {
state = State::Code;
}
}
}
State::Backtick => {
if c == '`' {
if next == Some('`') {
i += 1;
} else {
state = State::Code;
}
}
}
State::LineComment => {
if c == '\n' {
state = State::Code;
}
}
State::BlockComment => {
if c == '*' && next == Some('/') {
state = State::Code;
i += 1;
}
}
// MySQL quotes identifiers only with backticks.
State::Bracket => unreachable!("MySQL has no bracketed identifiers"),
}
i += 1;
}
Ok(())
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Unit {
Sql,
@@ -777,6 +900,82 @@ fn utf16_slice(text: &str, from: u32, to: u32) -> &str {
mod tests {
use super::*;
#[test]
fn mysql_executable_comments_are_refused_outside_literals() {
for sql in [
"SELECT 1 /*!50000 , 2 */",
"/*! START TRANSACTION READ WRITE; DELETE FROM t; */ SELECT 1",
"SELECT 1 /*M!100000 , 2 */",
"select 1 /*m! , 2 */",
// Also inside a genuine comment: the conservative refusal cannot be bypassed by a
// future difference between the guard's comment rules and the server's.
"SELECT 1 -- /*! hidden in a comment */",
"SELECT 1 # /*! hidden in a comment */",
"SELECT 1 /* /*! inside a block comment */",
] {
let error = mysql_guard(sql).unwrap_err();
assert!(error.message.contains("executable comments"), "{sql}: {}", error.message);
}
// The same text inside a literal or a quoted identifier is data, not code.
for sql in [
"SELECT '/*! DELETE FROM t */'",
"SELECT \"/*M! x */\", `/*! y */` FROM t",
"SELECT 'it''s /*! fine */'",
"SELECT 'a\\' /*! still text */'",
] {
mysql_guard(sql).unwrap_or_else(|e| panic!("{sql}: {}", e.message));
}
}
#[test]
fn mysql_dash_comment_uses_mysqls_ascii_rule_like_the_splitter() {
// U+00A0 (NO-BREAK SPACE) and other Unicode spaces do not start a `--` comment on the
// server: `--` is two minus signs and the executable comment that follows is code.
for sql in [
"SELECT 1 --\u{00a0}/*! x */",
"SELECT 1 --\u{00a0}/*! FROM (SELECT 1 AS \u{00a0}) d; START TRANSACTION READ WRITE; DELETE FROM users; */",
"SELECT 1 --\u{00a0}/*! FROM (SELECT 1 AS \u{00a0}) d INTO OUTFILE '/tmp/x' */",
"SELECT 1 --\u{2003}/*M! DELETE FROM users */",
] {
let error = mysql_guard(sql).unwrap_err();
assert!(error.message.contains("executable comments"), "{sql}: {}", error.message);
}
// An ASCII space, tab or control character after `--` is a comment, as before.
for sql in ["SELECT 1 -- ordinary comment\n+ 1", "SELECT 1 --\tcomment\n+ 1", "SELECT 1 --\n+ 1"] {
mysql_guard(sql).unwrap_or_else(|e| panic!("{sql}: {}", e.message));
}
// `split` applies the same rule: the text after `--` is code (and the `;` there splits),
// so the guard is the layer that refuses the executable comment.
assert_eq!(
texts("SELECT 5 --\u{00a0} 1; SELECT 2", DbDriver::Mysql),
vec!["SELECT 5 --\u{00a0} 1", "SELECT 2"]
);
assert_eq!(texts("SELECT 5 -- 1; SELECT 2", DbDriver::Mysql), vec!["SELECT 5 -- 1; SELECT 2"]);
}
#[test]
fn mysql_into_outfile_is_refused_outside_literals_and_comments() {
for sql in [
"SELECT * FROM t INTO OUTFILE '/tmp/x'",
"SELECT * FROM t INTO DUMPFILE '/tmp/x'",
"SELECT * FROM t INTO/**/OUTFILE '/tmp/x'",
"SELECT * FROM t INTO /* c */\n OUTFILE '/tmp/x'",
"select * from t into outfile '/tmp/x'",
] {
let error = mysql_guard(sql).unwrap_err();
assert!(error.message.contains("INTO OUTFILE"), "{sql}: {}", error.message);
}
for sql in [
"SELECT 'INTO OUTFILE /tmp/x'",
"SELECT 1 AS outfile, 2 AS dumpfile FROM t",
"SELECT 1 /* INTO OUTFILE '/tmp/x' */",
"SELECT 1 -- INTO OUTFILE '/tmp/x'",
"SELECT @outfile FROM t",
] {
mysql_guard(sql).unwrap_or_else(|e| panic!("{sql}: {}", e.message));
}
}
#[test]
fn clickhouse_session_settings_split_after_comments_and_quoted_values() {
let set = "# leading ;\n/* outer /* nested ; */ tail ; */ SET log_comment='a;b', max_threads=1";
@@ -852,6 +1051,17 @@ mod tests {
);
}
#[test]
fn postgres_line_comments_end_at_a_carriage_return_like_the_server() {
// `scan.l` reads `\r` as a newline, so the `;` after it ends the statement; MySQL and
// SQLite keep a bare `\r` inside the comment.
let sql = "SELECT 1 --\r; SELECT 2";
assert_eq!(texts(sql, DbDriver::Postgres), vec!["SELECT 1 --", "SELECT 2"]);
assert_eq!(texts(sql, DbDriver::Mysql), vec![sql]);
assert_eq!(texts(sql, DbDriver::Sqlite), vec![sql]);
assert_eq!(texts("SELECT 1 --\r\n; SELECT 2", DbDriver::Postgres), vec!["SELECT 1 --", "SELECT 2"]);
}
#[test]
fn mysql_double_quoted_strings_and_dashes() {
let sql = r#"SELECT "say \"hi; DELETE FROM b; \"", 'a''b;', "c"";", `d``;`"#;
+112 -1
Переглянути файл
@@ -2,7 +2,7 @@
//! `OPENIDEA_TEST_MYSQL=host:port:user:password` names a throwaway server.
use ide_core::{CancellationToken, IdeResult};
use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbOptions, DbRowEdit};
use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbOptions, DbProperty, DbRowEdit};
const SCHEMAS: [&str; 2] = ["oi_bin_meta", "oi_数据"];
@@ -13,6 +13,14 @@ fn server() -> Option<(String, u16, String, String)> {
}
async fn manager(tmp: &tempfile::TempDir, startup_script: &str) -> Option<DbManager> {
manager_with_properties(tmp, startup_script, Vec::new()).await
}
async fn manager_with_properties(
tmp: &tempfile::TempDir,
startup_script: &str,
properties: Vec<DbProperty>,
) -> Option<DbManager> {
let (host, port, user, password) = server()?;
let root = tmp.path().to_path_buf();
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
@@ -24,6 +32,7 @@ async fn manager(tmp: &tempfile::TempDir, startup_script: &str) -> Option<DbMana
host,
port: Some(port),
user,
properties,
options: DbOptions { startup_script: startup_script.into(), ..Default::default() },
..Default::default()
}])
@@ -435,3 +444,105 @@ async fn table_grants_list_table_privileges() -> IdeResult<()> {
}
Ok(())
}
/// The MySQL/MariaDB read-only session: a query runs; writes, executable comments and
/// `INTO OUTFILE` are refused. Skipped without `OPENIDEA_TEST_MYSQL`.
#[tokio::test]
async fn the_read_only_session_refuses_writes_and_server_side_escapes() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
let c = CancellationToken::new();
let table = format!("openidea_ro_{}", uuid::Uuid::new_v4().simple());
for stmt in [
format!("DROP TABLE IF EXISTS {table}"),
format!("CREATE TABLE {table} (id INT PRIMARY KEY)"),
format!("INSERT INTO {table} VALUES (1)"),
] {
db.execute("m", &stmt, 1, &c).await?;
}
let rows = db.execute_read_only_query("m", &format!("SELECT count(*) FROM {table}"), 1, &c).await?;
assert_eq!(rows.rows, vec![vec![Some("1".into())]]);
let write = db
.execute_read_only_query("m", &format!("INSERT INTO {table} VALUES (2)"), 1, &c)
.await
.expect_err("the read-only transaction refuses a write");
assert!(
write.message.to_ascii_lowercase().contains("read only") || write.message.contains("1792"),
"{}",
write.message
);
let comment = db
.execute_read_only_query("m", "SELECT 1 /*! , 2 */", 1, &c)
.await
.expect_err("an executable comment is refused before the server runs it");
assert!(comment.message.contains("executable comment"), "{}", comment.message);
let outfile = db
.execute_read_only_query("m", &format!("SELECT * FROM {table} INTO OUTFILE '/tmp/openidea-ro'"), 1, &c)
.await
.expect_err("INTO OUTFILE is refused");
assert!(outfile.message.contains("INTO OUTFILE"), "{}", outfile.message);
// `--` followed by a non-ASCII space is two minus signs to the server, not a comment; the
// guard must read it the same way instead of hiding the executable comment behind it.
for payload in [
"SELECT 1 --\u{00a0}/*! x */".to_owned(),
format!(
"SELECT 1 --\u{00a0}/*! FROM (SELECT 1 AS \u{00a0}) d; START TRANSACTION READ WRITE; \
DELETE FROM {table}; */"
),
"SELECT 1 --\u{00a0}/*! FROM (SELECT 1 AS \u{00a0}) d INTO OUTFILE '/tmp/openidea-ro' */".to_owned(),
] {
let error = db
.execute_read_only_query("m", &payload, 1, &c)
.await
.expect_err("the executable comment is refused before the server runs it");
assert!(error.message.contains("executable comment"), "{payload}: {}", error.message);
}
let rows = db.execute("m", &format!("SELECT count(*) FROM {table}"), 1, &c).await?;
assert_eq!(rows.rows, vec![vec![Some("1".into())]], "nothing else was written");
db.execute("m", &format!("DROP TABLE {table}"), 1, &c).await?;
Ok(())
}
/// A source configured with an unsafe connection charset (`charset=gbk`) cannot make the server
/// read a statement differently than the client: the read-only connection is pinned to utf8mb4,
/// so an ASCII backslash is never swallowed as the second byte of a GBK character. Skipped
/// without `OPENIDEA_TEST_MYSQL`.
#[tokio::test]
async fn the_read_only_connection_is_pinned_to_utf8mb4_whatever_the_source_charset() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) =
manager_with_properties(&tmp, "", vec![DbProperty { name: "charset".into(), value: "gbk".into() }]).await
else {
return Ok(());
};
let c = CancellationToken::new();
let charsets = db
.execute_read_only_query(
"m",
"SELECT @@SESSION.character_set_client, @@SESSION.character_set_connection",
1,
&c,
)
.await?;
assert_eq!(charsets.rows, vec![vec![Some("utf8mb4".into()), Some("utf8mb4".into())]]);
let table = format!("openidea_charset_{}", uuid::Uuid::new_v4().simple());
for stmt in [
format!("DROP TABLE IF EXISTS {table}"),
format!("CREATE TABLE {table} (id INT)"),
format!("INSERT INTO {table} VALUES (1)"),
] {
db.execute("m", &stmt, 1, &c).await?;
}
// Read as GBK, the `\` would be consumed as the second byte of a character, the string would
// end early and the tail would run as two more statements.
let payload = format!("SELECT '中\\' ; START TRANSACTION READ WRITE; DELETE FROM {table}; -- '");
db.execute_read_only_query("m", &payload, 1, &c).await?;
let rows = db.execute("m", &format!("SELECT count(*) FROM {table}"), 1, &c).await?;
assert_eq!(rows.rows, vec![vec![Some("1".into())]], "no hidden statement ran");
db.execute("m", &format!("DROP TABLE {table}"), 1, &c).await?;
Ok(())
}
+84
Переглянути файл
@@ -234,6 +234,90 @@ async fn postgres_read_only_is_checked_before_and_after_startup_sql() -> IdeResu
Ok(())
}
/// A data-changing statement hidden in a CTE is not a query: the read-only session refuses it
/// in the database, whatever the statement text looks like, and the table keeps its rows.
#[tokio::test]
async fn a_write_hidden_in_a_cte_is_refused_by_the_read_only_session() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
let table = format!("public.oi_cte_{}", uuid::Uuid::new_v4().simple());
for stmt in [
format!("CREATE TABLE {table} (id INT PRIMARY KEY, name TEXT)"),
format!("INSERT INTO {table} VALUES (1, 'kept')"),
] {
db.execute("p", &stmt, 10, &c).await?;
}
let statement = format!("WITH d AS (DELETE FROM {table} RETURNING *) SELECT * FROM d");
let error = db
.execute_read_only_query("p", &statement, 10, &c)
.await
.expect_err("the read-only transaction must refuse a DELETE in a CTE");
assert!(error.message.contains("25006"), "{}", error.message);
let rows = db.execute("p", &format!("SELECT id, name FROM {table} ORDER BY id"), 10, &c).await?;
assert_eq!(rows.rows, vec![vec![Some("1".into()), Some("kept".into())]]);
db.execute("p", &format!("DROP TABLE {table}"), 10, &c).await?;
Ok(())
}
/// PostgreSQL's scanner ends a `--` comment at `\r` as well as `\n`; the splitter must agree, so
/// a bare CR cannot hide `COMMIT; DELETE …` from the one-statement check. The hidden statements
/// would otherwise run on the dedicated `BEGIN READ ONLY` connection.
#[tokio::test]
async fn a_carriage_return_cannot_hide_a_second_statement() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
let table = format!("public.oi_cr_{}", uuid::Uuid::new_v4().simple());
for stmt in [format!("CREATE TABLE {table} (id INT PRIMARY KEY)"), format!("INSERT INTO {table} VALUES (1)")] {
db.execute("p", &stmt, 10, &c).await?;
}
let payload = format!("SELECT 1 --\r; COMMIT; DELETE FROM {table}; --");
let error = db.execute_read_only_query("p", &payload, 10, &c).await.expect_err("the hidden DELETE must not run");
assert!(error.message.contains("exactly one statement"), "{}", error.message);
let rows = db.execute("p", &format!("SELECT count(*) FROM {table}"), 10, &c).await?;
assert_eq!(rows.rows, vec![vec![Some("1".into())]]);
db.execute("p", &format!("DROP TABLE {table}"), 10, &c).await?;
Ok(())
}
/// A startup script can change the connection's `client_encoding`; the read-only session pins it
/// to UTF-8 anyway, so the server reads the statement's bytes exactly as the splitter did.
#[tokio::test]
async fn a_startup_script_cannot_change_the_read_only_sessions_encoding() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
let table = format!("public.oi_gbk_{}", uuid::Uuid::new_v4().simple());
for stmt in [
format!("CREATE TABLE {table} (id INT PRIMARY KEY, name TEXT)"),
format!("INSERT INTO {table} VALUES (1, 'kept')"),
] {
db.execute("p", &stmt, 10, &c).await?;
}
let mut sources = db.sources()?;
let mut source = sources[0].clone();
source.id = "gbk".into();
source.name = "GBK startup".into();
source.read_only = true;
source.options.startup_script = "SET client_encoding TO 'GBK'".into();
sources.push(source);
db.save_sources(sources).await?;
db.set_password("gbk", server().map(|(.., password)| password), false).await?;
let encoding = db.execute_read_only_query("gbk", "SELECT current_setting('client_encoding')", 1, &c).await?;
assert_eq!(encoding.rows, vec![vec![Some("UTF8".into())]]);
// In GBK the backslash before the quote is a trail byte of the preceding character, so the
// server would end the E-string early and run the hidden `COMMIT; DELETE …`.
let payload = format!("SELECT E'中\\' ; COMMIT; DELETE FROM {table}; -- '");
let result = db.execute_read_only_query("gbk", &payload, 1, &c).await?;
assert_eq!(result.rows.len(), 1, "{:?}", result.rows);
let rows = db.execute("p", &format!("SELECT id, name FROM {table}"), 10, &c).await?;
assert_eq!(rows.rows, vec![vec![Some("1".into()), Some("kept".into())]]);
db.execute("p", &format!("DROP TABLE {table}"), 10, &c).await?;
Ok(())
}
#[tokio::test]
async fn active_schema_context_drives_the_executing_connection() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
+55 -1
Переглянути файл
@@ -1,10 +1,11 @@
//! Introspection, queries and table edits against a real SQLite file.
use ide_core::{CancellationToken, IdeResult};
use ide_core::{CancellationToken, IdeResult, error::ErrorKind};
use ide_db::{
CellValue, DataSource, DbDriver, DbKeyKind, DbManager, DbOptions, DbProperty, DbRowEdit, DbSchemaSelection,
DbTableKind, DbVisibilityChange, QueryResult, SortKey,
};
use std::time::Duration;
async fn setup() -> (tempfile::TempDir, DbManager) {
let tmp = tempfile::tempdir().unwrap();
@@ -527,3 +528,56 @@ async fn data_sources_edited_on_disk_close_their_connections() -> IdeResult<()>
assert!(!db.reconcile_sources().await);
Ok(())
}
/// A read-only query whose future is dropped or cancelled mid-flight must not leave
/// `PRAGMA query_only` on a pooled connection: a later write through the pool still works.
#[tokio::test]
async fn a_dropped_or_cancelled_read_only_query_leaves_the_pool_writable() -> IdeResult<()> {
let (_tmp, db) = setup().await;
let pool = db.pool("s1").await?;
// CPU-bound and touches no table, so it holds no file lock while it runs. Large enough that
// it cannot finish within the 50 ms before the abort, even on a fast machine.
let slow = "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 5000000) \
SELECT count(*) FROM c";
let spawn = |cancel: CancellationToken| {
let pool = pool.clone();
tokio::spawn(async move { pool.execute_read_only(slow, 1, &cancel).await })
};
// Dropped mid-query, as a timeout used to drop it.
let handle = spawn(CancellationToken::new());
tokio::time::sleep(Duration::from_millis(50)).await;
handle.abort();
let _ = handle.await;
// Cancelled mid-query, as a cancelled MCP request does.
let cancel = CancellationToken::new();
let handle = spawn(cancel.clone());
tokio::time::sleep(Duration::from_millis(50)).await;
cancel.cancel();
let error = handle.await.unwrap().expect_err("the cancelled query returns an error");
assert_eq!(error.kind, ErrorKind::Cancelled);
// Let either worker finish: a dropped session's connection must close, not return with
// query_only still on. Take every connection the pool has (4 pool + 4 console sessions) and
// read the PRAGMA, so a poisoned slot cannot hide in the unchecked rest.
tokio::time::sleep(Duration::from_millis(1500)).await;
let c = CancellationToken::new();
let mut held = Vec::new();
for _ in 0..8 {
let mut conn = ide_db::Held::acquire(&pool).await?;
let rows = conn.execute(&pool, "PRAGMA query_only", 1, &c).await?.rows;
assert_eq!(rows, vec![vec![Some("0".into())]], "a pooled connection kept query_only");
held.push(conn);
}
drop(held);
// A pool slot that kept query_only would answer SQLITE_READONLY, intermittently.
for n in 0..20 {
let sql = format!("INSERT INTO users (name) VALUES ('after{n}')");
pool.execute(&sql, 1, &c).await?;
}
let rows = pool.execute("SELECT count(*) FROM users WHERE name LIKE 'after%'", 1, &c).await?.rows;
assert_eq!(rows, vec![vec![Some("20".into())]]);
Ok(())
}
+22 -1
Переглянути файл
@@ -187,6 +187,7 @@ pub const EVENT_KINDS: &[&str] = &[
"problems-changed",
"project-closed",
"watched-files-changed",
"project-tree-expanded",
];
impl std::fmt::Display for ActivationEvent {
@@ -483,7 +484,8 @@ impl Manifest {
{
self.needs_api(&format!("`{event}`"), 18)?;
}
if matches!(event, ActivationEvent::Event(kind) if matches!(kind.as_str(), "run-started" | "run-output")) {
if matches!(event, ActivationEvent::Event(kind) if matches!(kind.as_str(), "run-started" | "run-output" | "project-tree-expanded"))
{
self.needs_api(&format!("`{event}`"), 21)?;
}
if !seen.insert(event) {
@@ -705,6 +707,10 @@ mod tests {
);
assert!(ActivationEvent::parse("on-event:document-changed").is_ok());
assert!(ActivationEvent::parse("on-event:websocket-ready").is_ok());
assert_eq!(
ActivationEvent::parse("on-event:project-tree-expanded"),
Ok(ActivationEvent::Event("project-tree-expanded".into()))
);
let err = ActivationEvent::parse("on-event:keystroke").unwrap_err();
assert!(err.contains("unknown event kind") && err.contains("action-performed"), "{err}");
assert!(ActivationEvent::parse("on-event:scheduled").is_err(), "declared with on-schedule");
@@ -1126,6 +1132,21 @@ mod net_ask_api_tests {
}
}
#[test]
fn project_tree_expanded_requires_api_1_21() {
for engine in ["^1.20", "^1.21"] {
let manifest = format!(
"id = 'test'\nname = 'Test'\nversion = '0.1.0'\nwasm = 'plugin.wasm'\nengines.openidea = '{engine}'\nactivation = [\"on-event:project-tree-expanded\"]\n"
);
let parsed = Manifest::parse(&manifest);
if engine == "^1.21" {
parsed.unwrap();
} else {
assert!(parsed.unwrap_err().contains("new in plugin API 1.21"), "{engine}");
}
}
}
#[test]
fn doc_files_require_api_1_18_and_relative_paths() {
for field in ["description-file", "change-notes-file"] {
+728
Переглянути файл
@@ -0,0 +1,728 @@
//! Database tools: the project's data sources, their schemas and objects, and read-only SQL.
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
use ide_core::error::ErrorKind;
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_db::{DataSource, DbDriver, DbObjectKind, DbTableKind, SchemaObjects, split};
use serde::Serialize;
use serde_json::{Value, json};
use std::future::Future;
use std::time::Duration;
const DEFAULT_MAX_ROWS: usize = 100;
const MAX_ROWS: usize = 1000;
/// UTF-16 units a cell keeps; the rest is reported in `truncated`.
const MAX_CELL_UNITS: usize = 4096;
const QUERY_TIMEOUT: Duration = Duration::from_secs(30);
/// Catalog reads can be slower than a query on a big schema; they do not run the user's SQL.
const METADATA_TIMEOUT: Duration = Duration::from_secs(60);
/// How long a cancelled or timed-out task gets to run its rollback / reset before the tool returns.
const STOP_GRACE: Duration = Duration::from_secs(5);
pub fn tools() -> Vec<Tool> {
vec![
list_database_connections(),
list_database_schemas(),
list_schema_objects(),
get_database_object_description(),
execute_sql_query(),
]
}
/// The connection a tool may use. The id must be exactly one data source's id: `DbManager`
/// resolves `<id>:<database>` by prefix and takes the first matching entry, so a colon or a
/// duplicate id could reach an entry other than the one checked here (a plugin-owned source and
/// its credentials, for example). Plugin-owned sources stay out of these tools entirely.
fn connection(call: &Call, id: &str) -> IdeResult<DataSource> {
if id.contains(':') {
return Err(IdeError::invalid(
"connectionId must be one id from list_database_connections, without a `:database` part",
));
}
let mut matches = call.project().db.sources()?.into_iter().filter(|source| source.id == id);
let Some(source) = matches.next() else {
return Err(IdeError::not_found(format!("no data source {id}")));
};
if matches.next().is_some() {
return Err(IdeError::invalid(format!(
"more than one data source has the id {id}; rename or remove one in the Database tool window"
)));
}
if source.plugin_owner.is_some() {
return Err(IdeError::not_found(format!("no data source {id}")));
}
source.resolved()
}
/// The `database` value a tool may show: an Oracle Database field can hold a TNS descriptor,
/// which embeds the host and port.
fn database_field(source: &DataSource) -> String {
let database = source.database.trim();
if source.driver == DbDriver::Oracle && (database.starts_with('(') || database.contains('=')) {
return String::new();
}
source.database.clone()
}
/// Replaces every ASCII-case-insensitive occurrence of `needle` in `haystack`. ASCII case folding
/// keeps byte lengths, so an offset found in the lowered copy is a valid boundary of the original.
fn replace_ascii_case_insensitive(haystack: &mut String, needle: &str, replacement: &str) {
let lowered = needle.to_ascii_lowercase();
let mut from = 0;
loop {
let Some(at) = haystack[from..].to_ascii_lowercase().find(&lowered) else { return };
let start = from + at;
haystack.replace_range(start..start + needle.len(), replacement);
from = start + replacement.len();
}
}
/// Replaces the data source's URL, host and user in an error before it reaches the agent: driver
/// and tunnel errors quote them (auth failures name the user, tunnel failures the host), in
/// whatever case the server reports (Oracle upper-cases user names). Percent-encoded forms are
/// redacted too, and the plain forms are matched case-insensitively.
fn redact_error(mut error: IdeError, source: &DataSource) -> IdeError {
let mut secrets = vec![source.url.trim().to_owned(), source.host.trim().to_owned(), source.user.trim().to_owned()];
for value in [source.host.trim(), source.user.trim()] {
if !value.is_empty() {
secrets.push(percent_encode(value));
}
}
for secret in secrets {
// Every configured value, however short: the tool text promises the user and host never
// appear, and a one- or two-character name is still a name.
if !secret.is_empty() {
replace_ascii_case_insensitive(&mut error.message, &secret, "<redacted>");
}
}
error
}
fn percent_encode(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for byte in value.bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
out.push(byte as char);
} else {
out.push_str(&format!("%{byte:02X}"));
}
}
out
}
/// Runs a catalog read with the request's cancellation and a time limit. The `DbManager`
/// metadata methods take no token; dropping their future closes the connection they were using.
async fn bounded<T>(call: &Call, deadline: Duration, task: impl Future<Output = IdeResult<T>>) -> IdeResult<T> {
tokio::select! {
biased;
() = call.cancel.cancelled() => Err(IdeError::cancelled()),
result = tokio::time::timeout(deadline, task) => match result {
Ok(result) => result,
Err(_) => Err(IdeError::new(
ErrorKind::TimedOut,
format!("the database did not answer within {} seconds", deadline.as_secs()),
)),
},
}
}
/// Runs a read-only query until it finishes, the request is cancelled, or `deadline` passes. On
/// either stop the driver's token is cancelled and its cleanup (rollback, reset, close) is
/// awaited, instead of dropping the future and leaving a driver's work running.
async fn until_stopped<T>(
deadline: Duration,
cancel: &CancellationToken,
token: &CancellationToken,
task: impl Future<Output = IdeResult<T>>,
) -> IdeResult<T> {
tokio::pin!(task);
tokio::select! {
biased;
result = &mut task => result,
() = cancel.cancelled() => {
token.cancel();
let _ = tokio::time::timeout(STOP_GRACE, &mut task).await;
Err(IdeError::cancelled())
}
() = tokio::time::sleep(deadline) => {
token.cancel();
let _ = tokio::time::timeout(STOP_GRACE, &mut task).await;
Err(IdeError::new(
ErrorKind::TimedOut,
format!("the statement did not finish within {} seconds", deadline.as_secs()),
))
}
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ConnectionInfo {
id: String,
name: String,
driver: DbDriver,
database: String,
read_only: bool,
global: bool,
}
fn list_database_connections() -> Tool {
Tool::new(
"list_database_connections",
"Lists the project's database connections (data sources): `id`, `name`, `driver`, `database`,
`readOnly` and `global`. Needs a trusted project; in Restricted Mode the call is refused.
Use a connection's `id` as `connectionId` in the other database tools.
`database` is the source's configured database; it is empty when none is configured, and a source
configured only by a URL is not read here, so its URL does not appear. Global data sources are
stored app-wide, are listed in every project and carry `\"global\": true`.
Never returns passwords, secrets, URLs, hosts or user names.",
|call| async move {
call.project.require_trust()?;
let connections: Vec<_> = call
.project()
.db
.sources()?
.into_iter()
.filter(|source| source.plugin_owner.is_none())
.map(|source| {
let database = database_field(&source);
ConnectionInfo {
id: source.id,
name: source.name,
driver: source.driver,
database,
read_only: source.read_only,
global: source.global,
}
})
.collect();
Output::json(json!({ "connections": connections }))
},
)
}
fn list_database_schemas() -> Tool {
Tool::new(
"list_database_schemas",
"Lists the schemas a database connection exposes (its databases on MySQL and Oracle).
Returns `connectionId`, the configured `database`, and `schemas`. Needs a trusted project; in
Restricted Mode the call is refused.",
|call| async move {
call.project.require_trust()?;
let connection_id = call.str("connectionId")?;
let source = connection(&call, &connection_id)?;
let schemas = bounded(&call, METADATA_TIMEOUT, call.project().db.schemas(&connection_id))
.await
.map_err(|e| redact_error(e, &source))?;
Output::json(json!({
"connectionId": connection_id,
"database": database_field(&source),
"schemas": schemas,
}))
},
)
.param(Param::required("connectionId", ParamType::String, "Data source id from `list_database_connections`"))
}
fn list_schema_objects() -> Tool {
Tool::new(
"list_schema_objects",
"Lists a schema's tables, views, materialized views, routines (functions and procedures), packages, sequences
and other objects, as `{ kind, name }`; table-like objects and routines also carry `comment`, `arguments` and
`returns` when the database has them.
Pass `kind` to filter (case-insensitive): `table`, `view`, `materializedView`, `function`, `procedure`, `package`,
`sequence`, `routine` (functions and procedures), or another object kind the database reports. An unknown kind
returns an empty list. Needs a trusted project; in Restricted Mode the call is refused.",
|call| async move {
call.project.require_trust()?;
let connection_id = call.str("connectionId")?;
let schema = call.str("schema")?;
let kind = call.opt_str("kind")?;
let source = connection(&call, &connection_id)?;
let db = &call.project().db;
let tables = bounded(&call, METADATA_TIMEOUT, db.tables(&connection_id, &schema))
.await
.map_err(|e| redact_error(e, &source))?;
let objects = bounded(&call, METADATA_TIMEOUT, db.schema_objects(&connection_id, &schema))
.await
.map_err(|e| redact_error(e, &source))?;
let objects = schema_objects(tables, objects, kind.as_deref());
Output::json(json!({
"connectionId": connection_id,
"schema": schema,
"objects": objects,
}))
},
)
.param(Param::required("connectionId", ParamType::String, "Data source id from `list_database_connections`"))
.param(Param::required("schema", ParamType::String, "Schema name from `list_database_schemas`"))
.param(Param::optional(
"kind",
ParamType::String,
"Only objects of this kind: table, view, materializedView, function, procedure, package, sequence, routine",
))
}
fn schema_objects(tables: Vec<ide_db::TableInfo>, objects: SchemaObjects, wanted: Option<&str>) -> Vec<Value> {
let mut out = Vec::new();
for table in tables {
let kind = match table.kind {
DbTableKind::Table => "table",
DbTableKind::View => "view",
DbTableKind::MaterializedView => "materializedView",
};
if !kind_matches(wanted, kind) {
continue;
}
let mut object = json!({ "kind": kind, "name": table.name });
if let Some(comment) = table.comment {
object["comment"] = json!(comment);
}
out.push(object);
}
for routine in objects.routines {
let kind = if routine.kind == DbObjectKind::Procedure { "procedure" } else { "function" };
if !kind_matches(wanted, kind) {
continue;
}
let mut object = json!({ "kind": kind, "name": routine.name });
if !routine.arguments.is_empty() {
object["arguments"] = json!(routine.arguments);
}
if let Some(returns) = routine.returns {
object["returns"] = json!(returns);
}
out.push(object);
}
for package in objects.packages {
if kind_matches(wanted, "package") {
out.push(json!({ "kind": "package", "name": package.name }));
}
}
for sequence in objects.sequences {
if kind_matches(wanted, "sequence") {
out.push(json!({ "kind": "sequence", "name": sequence.name }));
}
}
for object in objects.others {
if kind_matches(wanted, &object.kind) {
out.push(json!({ "kind": object.kind, "name": object.name }));
}
}
out
}
fn kind_matches(wanted: Option<&str>, kind: &str) -> bool {
wanted.is_none_or(|wanted| {
wanted.eq_ignore_ascii_case(kind)
|| (wanted.eq_ignore_ascii_case("routine") && matches!(kind, "function" | "procedure"))
})
}
fn get_database_object_description() -> Tool {
Tool::new(
"get_database_object_description",
"Describes a table, view or materialized view: columns (type, nullability, default, primary key and comment),
indexes, foreign keys, triggers and the object's comment, plus the owner, tablespace, access method,
storage options and partitioning when the database reports them.
Describing routines, packages and sequences is not supported yet. Needs a trusted project; in
Restricted Mode the call is refused.",
|call| async move {
call.project.require_trust()?;
let connection_id = call.str("connectionId")?;
let schema = call.str("schema")?;
let object_name = call.str("objectName")?;
if let Some(kind) = call.opt_str("kind")?
&& !is_table_like_kind(&kind)
{
return Err(description_unsupported(&kind));
}
let source = connection(&call, &connection_id)?;
let db = &call.project().db;
let details = bounded(&call, METADATA_TIMEOUT, db.table_details(&connection_id, &schema, &object_name))
.await
.map_err(|e| redact_error(e, &source))?;
if details.columns.is_empty() {
let objects = bounded(&call, METADATA_TIMEOUT, db.schema_objects(&connection_id, &schema))
.await
.map_err(|e| redact_error(e, &source))?;
if let Some(kind) = schema_object_kind(&objects, &object_name) {
return Err(description_unsupported(kind));
}
return Err(IdeError::not_found(format!("{schema}.{object_name}")));
}
Output::json(json!({
"connectionId": connection_id,
"schema": schema,
"objectName": object_name,
"details": details,
}))
},
)
.param(Param::required("connectionId", ParamType::String, "Data source id from `list_database_connections`"))
.param(Param::required("schema", ParamType::String, "Schema name from `list_database_schemas`"))
.param(Param::required("objectName", ParamType::String, "Table, view or materialized view name"))
.param(Param::optional(
"kind",
ParamType::String,
"Object kind from `list_schema_objects`; only table, view and materializedView are described",
))
}
fn is_table_like_kind(kind: &str) -> bool {
["table", "view", "materializedView"].iter().any(|known| kind.eq_ignore_ascii_case(known))
}
fn schema_object_kind<'a>(objects: &'a SchemaObjects, name: &str) -> Option<&'a str> {
if objects.routines.iter().any(|routine| routine.name == name) {
return Some("routine");
}
if objects.packages.iter().any(|package| package.name == name) {
return Some("package");
}
if objects.sequences.iter().any(|sequence| sequence.name == name) {
return Some("sequence");
}
objects.others.iter().find(|object| object.name == name).map(|object| object.kind.as_str())
}
fn description_unsupported(kind: &str) -> IdeError {
IdeError::invalid(format!(
"describing a {kind} is not supported yet; this tool describes tables, views and materialized views only"
))
}
fn execute_sql_query() -> Tool {
Tool::new(
"execute_sql_query",
"Runs one read-only SQL statement (SELECT, WITH or EXPLAIN) against a data source after the user confirms
the exact statement. It runs in a driver-enforced read-only session on SQLite, PostgreSQL, MySQL/MariaDB and
Oracle; other drivers are refused. Multiple statements, writes and DDL are refused. On Oracle, EXPLAIN is
refused (EXPLAIN PLAN writes PLAN_TABLE). On MySQL/MariaDB, executable comments (`/*! … */`, `/*M! … */`) and
INTO OUTFILE/INTO DUMPFILE are refused, and the connection is pinned to utf8mb4 so the server reads the
statement exactly as the splitter did. MySQL/MariaDB and MySQL-compatible servers are supported only when
they accept `SET NAMES utf8mb4` and report a read-only transaction (`transaction_read_only` or
`tx_read_only`); otherwise this tool refuses. On PostgreSQL, the connection is pinned to `client_encoding`
UTF8 with `standard_conforming_strings = on`, and the server parses the statement as one command before it
runs, so a difference from the splitter's lexing is refused rather than executed. The metadata tools are
unaffected. \"Read-only\" means no
changes to tables, views and schema through the statement; functions with server-side side effects (for
example PostgreSQL lo_export, Oracle UTL_FILE, MySQL LOAD_FILE) are outside that guarantee. Use a database
account with read-only privileges for agent access: the IDE's read-only session is defense in depth, not a
full sandbox.
Returns at most `maxRows` rows (default 100, clamped to 1000), each cell cut to 4096 UTF-16 units. The query
is cancelled after 30 seconds, with up to 5 seconds more to roll back and close. The result and errors never
include the data source URL, host or user.",
execute_query,
)
.write()
.param(Param::required("connectionId", ParamType::String, "Data source id from `list_database_connections`"))
.param(Param::required(
"sql",
ParamType::String,
"One read-only statement: SELECT, WITH or EXPLAIN; leading SQL comments are allowed",
))
.param(Param::optional(
"maxRows",
ParamType::Integer,
"Rows to return at most (default 100, clamped to 1..=1000)",
))
}
async fn execute_query(call: Call) -> IdeResult<Output> {
let connection_id = call.str("connectionId")?;
let sql = call.str("sql")?;
let max_rows = match call.opt_i64("maxRows")? {
Some(rows) => rows.clamp(1, MAX_ROWS as i64) as usize,
None => DEFAULT_MAX_ROWS,
};
let source = connection(&call, &connection_id)?;
if !matches!(source.driver, DbDriver::Sqlite | DbDriver::Postgres | DbDriver::Mysql | DbDriver::Oracle) {
return Err(IdeError::invalid(format!(
"{} has no read-only session; execute_sql_query runs on SQLite, PostgreSQL, MySQL/MariaDB and Oracle only",
source.driver.display_name()
)));
}
if source.driver == DbDriver::Mysql {
// The server executes these even though `split` reads them as comments or literals.
split::mysql_guard(&sql)?;
}
let statements = split::split(&sql, source.driver);
let statement = match statements.as_slice() {
[] => return Err(IdeError::invalid("the SQL is empty")),
[statement] => statement,
_ => {
return Err(IdeError::invalid(format!(
"exactly one statement is allowed, but the SQL has {}",
statements.len()
)));
}
};
match leading_keyword(&statement.text, source.driver) {
Some(keyword) if matches!(keyword.as_str(), "SELECT" | "WITH" | "EXPLAIN") => {
if source.driver == DbDriver::Oracle && keyword == "EXPLAIN" {
return Err(IdeError::invalid("EXPLAIN is not allowed on Oracle: EXPLAIN PLAN writes PLAN_TABLE"));
}
}
Some(keyword) => {
return Err(IdeError::invalid(format!(
"{keyword} is not allowed: execute_sql_query runs SELECT, WITH and EXPLAIN statements only"
)));
}
None => {
return Err(IdeError::invalid("execute_sql_query runs SELECT, WITH and EXPLAIN statements only"));
}
}
let database = database_field(&source);
let database = if database.is_empty() { "(default)" } else { database.as_str() };
let detail = format!("Driver: {}\nDatabase: {database}\nSQL:\n{}", source.driver.display_name(), statement.text);
call.confirm(&format!("SQL on {}", source.name), Some(detail)).await?;
let token = call.cancel.child_token();
let work = call.project().db.execute_read_only_query(&connection_id, &statement.text, max_rows, &token);
let mut result =
until_stopped(QUERY_TIMEOUT, &call.cancel, &token, work).await.map_err(|e| redact_error(e, &source))?;
result.cap_cells(MAX_CELL_UNITS);
let row_count = result.rows.len();
Output::json(json!({
"connectionId": connection_id,
"statement": result.statement,
"columns": result.columns,
"rows": result.rows,
"rowCount": row_count,
"hasMore": result.has_more,
"truncated": result.truncated,
"elapsedMs": result.elapsed_ms,
"affected": result.affected,
}))
}
/// The first keyword of `sql`, past leading whitespace and SQL comments, uppercased.
fn leading_keyword(sql: &str, driver: DbDriver) -> Option<String> {
let mut text = sql;
loop {
text = text.trim_start();
if let Some(comment) = text.strip_prefix("--") {
// PostgreSQL ends a line comment at `\r` as well as `\n` (`scan.l`), as `split` does;
// the other drivers keep a bare `\r` in the comment.
let end = comment
.char_indices()
.find(|&(_, c)| c == '\n' || (driver == DbDriver::Postgres && c == '\r'))
.map_or(comment.len(), |(at, _)| at);
text = &comment[end..];
} else if let Some(comment) = text.strip_prefix('#') {
text = comment.split_once('\n').map_or("", |(_, rest)| rest);
} else if let Some(comment) = text.strip_prefix("/*") {
text = after_block_comment(comment);
} else {
let end = text.find(|c: char| !(c.is_alphanumeric() || matches!(c, '_' | '$'))).unwrap_or(text.len());
return (end > 0).then(|| text[..end].to_ascii_uppercase());
}
}
}
/// The text after a `/*` comment, past nested block comments (`/* /* */ */`).
fn after_block_comment(mut text: &str) -> &str {
let mut depth = 1usize;
while let Some(at) = text.find(['/', '*']) {
text = &text[at..];
if let Some(rest) = text.strip_prefix("/*") {
depth += 1;
text = rest;
} else if let Some(rest) = text.strip_prefix("*/") {
depth -= 1;
text = rest;
if depth == 0 {
return text;
}
} else {
text = &text[1..];
}
}
""
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exposes_exactly_the_five_database_tools() {
let names: Vec<_> = tools().into_iter().map(|tool| tool.metadata.name).collect();
assert_eq!(
names,
[
"list_database_connections",
"list_database_schemas",
"list_schema_objects",
"get_database_object_description",
"execute_sql_query",
]
);
}
#[test]
fn only_execute_sql_query_is_not_read_only() {
for tool in tools() {
assert_eq!(tool.metadata.read_only, tool.metadata.name != "execute_sql_query", "{}", tool.metadata.name);
}
}
#[test]
fn execute_sql_query_requires_a_connection_and_a_statement() {
let tool = tools().into_iter().find(|tool| tool.metadata.name == "execute_sql_query").unwrap();
let required = tool.metadata.input_schema["required"].as_array().unwrap();
for name in ["connectionId", "sql"] {
assert!(required.iter().any(|value| value == name), "{name}");
assert_eq!(tool.metadata.input_schema["properties"][name]["type"], "string", "{name}");
}
}
#[test]
fn accepts_select_with_and_explain_past_comments() {
for sql in [
"SELECT 1",
"-- note\nSELECT 1",
"/* outer /* nested */ comment */ WITH x AS (SELECT 1) SELECT * FROM x",
" \n\t EXPLAIN SELECT 1",
] {
assert!(
matches!(leading_keyword(sql, DbDriver::Postgres).as_deref(), Some("SELECT" | "WITH" | "EXPLAIN")),
"{sql}"
);
}
}
/// PostgreSQL ends a leading `--` comment at `\r` too, like the fixed splitter.
#[test]
fn a_carriage_return_ends_a_postgres_leading_comment() {
assert_eq!(leading_keyword("-- note\rSELECT 1", DbDriver::Postgres).as_deref(), Some("SELECT"));
for driver in [DbDriver::Mysql, DbDriver::Sqlite, DbDriver::Oracle, DbDriver::SqlServer] {
assert_eq!(leading_keyword("-- note\rSELECT 1", driver), None, "{driver:?}");
}
}
#[test]
fn refuses_other_leading_keywords() {
for sql in [
"INSERT INTO t VALUES (1)",
"UPDATE t SET x = 1",
"DELETE FROM t",
"CREATE TABLE t (x INT)",
"CALL p()",
"COPY t FROM stdin",
"PRAGMA query_only = ON",
"# comment\nUPDATE t SET x = 1",
] {
let keyword = leading_keyword(sql, DbDriver::Postgres);
assert!(!matches!(keyword.as_deref(), Some("SELECT" | "WITH" | "EXPLAIN")), "{sql}: {keyword:?}");
}
}
#[test]
fn errors_hide_the_url_host_and_user() {
let source = DataSource {
driver: DbDriver::Postgres,
host: "db.example.invalid".into(),
user: "[email protected]".into(),
url_only: true,
url: "postgres://alice%40example.com:[email protected]:5432/app".into(),
..Default::default()
};
for message in [
"[28P01] password authentication failed for user \"[email protected]\"".to_owned(),
"connection to server at db.example.invalid (10.0.0.5), port 5432 failed".to_owned(),
"user alice%40example.com cannot log in".to_owned(),
"ALICE%40EXAMPLE.COM cannot log in".to_owned(),
"Alice%40Example.com cannot log in".to_owned(),
"DB.EXAMPLE.INVALID refused the connection".to_owned(),
"could not open postgres://alice%40example.com:[email protected]:5432/app".to_owned(),
] {
let error = redact_error(IdeError::invalid(message.clone()), &source);
let lower = error.message.to_ascii_lowercase();
for secret in ["alice", "db.example.invalid", "pw@db"] {
assert!(!lower.contains(secret), "{message} -> {}", error.message);
}
}
// However short: a one- or two-character name is still a configured name.
let short = DataSource { host: "q".into(), user: "ab".into(), ..Default::default() };
let error =
redact_error(IdeError::invalid("password authentication failed for user \"ab\" at q".to_owned()), &short);
assert!(!error.message.to_ascii_lowercase().contains("ab"), "{}", error.message);
assert!(!error.message.contains('q'), "{}", error.message);
assert!(error.message.contains("<redacted>"), "{}", error.message);
}
#[test]
fn an_oracle_tns_descriptor_is_not_shown_as_the_database() {
let mut source = DataSource {
driver: DbDriver::Oracle,
database: "(DESCRIPTION=(HOST=db.local))".into(),
..Default::default()
};
assert_eq!(database_field(&source), "");
source.database = "PROD=(DESCRIPTION=(HOST=db.local))".into();
assert_eq!(database_field(&source), "");
source.database = "ORCLPDB1".into();
assert_eq!(database_field(&source), "ORCLPDB1");
}
#[tokio::test]
async fn a_deadline_cancels_the_task_and_awaits_its_cleanup() {
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
let cancel = CancellationToken::new();
let token = cancel.child_token();
let cleaned = Arc::new(AtomicBool::new(false));
let task = {
let (token, cleaned) = (token.clone(), cleaned.clone());
async move {
token.cancelled().await;
cleaned.store(true, Ordering::SeqCst);
Err::<(), _>(IdeError::cancelled())
}
};
let error = until_stopped(Duration::from_millis(20), &cancel, &token, task).await.unwrap_err();
assert_eq!(error.kind, ErrorKind::TimedOut);
assert!(cleaned.load(Ordering::SeqCst), "the task's cleanup ran before the timeout returned");
}
#[tokio::test]
async fn cancelling_the_request_cancels_the_task() {
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
let cancel = CancellationToken::new();
let token = cancel.child_token();
let cleaned = Arc::new(AtomicBool::new(false));
let task = {
let (token, cleaned) = (token.clone(), cleaned.clone());
async move {
token.cancelled().await;
cleaned.store(true, Ordering::SeqCst);
Err::<(), _>(IdeError::cancelled())
}
};
let canceller = cancel.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(20)).await;
canceller.cancel();
});
let error = until_stopped(Duration::from_secs(30), &cancel, &token, task).await.unwrap_err();
assert_eq!(error.kind, ErrorKind::Cancelled);
assert!(cleaned.load(Ordering::SeqCst), "the task's cleanup ran before the call returned");
}
#[test]
fn kind_filter_is_case_insensitive_and_routine_covers_functions_and_procedures() {
assert!(kind_matches(None, "table"));
assert!(kind_matches(Some("materializedview"), "materializedView"));
assert!(kind_matches(Some("ROUTINE"), "function"));
assert!(kind_matches(Some("routine"), "procedure"));
assert!(!kind_matches(Some("routine"), "table"));
assert!(!kind_matches(Some("stage"), "table"));
}
}
+2
Переглянути файл
@@ -2,6 +2,7 @@
mod automations;
mod background;
mod check;
mod database;
mod debug;
mod devcontainer;
mod edit;
@@ -55,6 +56,7 @@ fn tools(local_desktop: bool) -> Vec<tool::Tool> {
tools.extend(run::tools());
tools.extend(vcs::tools());
tools.extend(http::tools());
tools.extend(database::tools());
if local_desktop {
tools.extend(devcontainer::tools());
}
+3 -2
Переглянути файл
@@ -8,6 +8,7 @@ use ide_text::LineEnding;
use ide_workspace::settings::SettingsScope;
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, FileDefaults, HistoryEntry};
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// Opens a read-only virtual document (see `lsp_virtual_document`) as an
/// editor buffer, so syntax features and language-server requests work in it.
@@ -165,7 +166,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
items
}
None if snap.large && !matches!(snap.language.as_str(), "markdown" | "mdx") => Vec::new(),
None => syntax(),
None => Arc::unwrap_or_clone(syntax()),
})
})
.await
@@ -186,7 +187,7 @@ pub async fn doc_folding(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
if snap.large {
return Ok(Vec::new());
}
let mut folds = project.syntax.folding(doc, &snap.language, snap.version, &snap.text);
let mut folds = Arc::unwrap_or_clone(project.syntax.folding(doc, &snap.language, snap.version, &snap.text));
if let Some(plugins) = crate::plugins::editor_providers_for(crate::plugins::ProviderKind::Folding) {
let d = ide_plugin::ProviderDocument {
path: project.documents.identity(doc)?.0,
+89 -9
Переглянути файл
@@ -697,16 +697,12 @@ fn without_generated_helpers(locations: Vec<Location>) -> Vec<Location> {
/// Gutter markers of plugin `line-markers` providers for an open document.
#[command(trust = trusted)]
pub async fn plugin_line_markers(
host: &Host,
window: &str,
doc: DocId,
) -> IdeResult<Vec<crate::plugins::LineMarkerInfo>> {
pub async fn plugin_line_markers(host: &Host, window: &str, doc: DocId) -> IdeResult<crate::plugins::LineMarkers> {
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::LineMarkers) else {
return Ok(Vec::new());
return Ok(Default::default());
};
let markers = plugin_call(move || plugins.provide_line_markers(&d)).await.unwrap_or_default();
Ok(markers
let (markers, late) = plugin_call(move || plugins.provide_line_markers(&d)).await.unwrap_or_default();
let markers = markers
.into_iter()
.map(|(plugin_id, m)| crate::plugins::LineMarkerInfo {
plugin_id,
@@ -715,7 +711,25 @@ pub async fn plugin_line_markers(
tooltip: m.tooltip,
target: m.target.map(|l| Location { path: l.path.into(), range: l.range, uri: None }),
})
.collect())
.collect();
Ok(crate::plugins::LineMarkers { markers, late })
}
/// The languages whose plugin line markers a save of `path` can change: those a plugin declares for
/// `line-markers` along with the file's language (`"*"` for every language). Does not load plugin
/// code. By path, not document: closing a tab saves it and then closes its document.
#[command(trust = trusted)]
pub async fn plugin_line_marker_languages(
host: &Host,
window: &str,
path: std::path::PathBuf,
) -> IdeResult<Vec<String>> {
let Some(plugins) = editor_providers(ProviderKind::LineMarkers) else {
return Ok(Vec::new());
};
let project = host.project(window)?;
let language = blocking(move || Ok(project.documents.language_of(&path, None).language.0)).await?;
Ok(plugins.line_marker_languages_with(&language))
}
/// Where other files import the document's file (Find Usages on a file, a Vue component's
@@ -776,6 +790,26 @@ pub async fn lsp_spring_bean_markers(
result
}
/// The document's Spring AOP markers (advised methods with their advices, advice methods with
/// the methods they advise); `None` when no server attached to it provides them. Cancel with
/// `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_spring_aop_markers(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
) -> IdeResult<Option<Vec<SpringAopMarker>>> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = tokio::select! {
result = lsp.spring_aop_markers(doc, cancel.clone()) => result,
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
};
host.end_request(request);
result
}
/// Go to Source Definition (vtsls): the JavaScript implementation of the symbol at `pos`
/// instead of its `.d.ts`. Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
@@ -1780,6 +1814,48 @@ pub async fn lsp_hierarchy_refactor(
.await
}
/// What can move at `pos` and where it can go (java-analyzer's `moveInfo`).
#[command(trust = trusted)]
pub async fn lsp_move_info(host: &Host, window: &str, request: RequestId, doc: DocId, pos: Pos) -> IdeResult<MoveInfo> {
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = project.lsp.java_move_info(doc, pos, cancel).await;
host.end_request(request);
result
}
/// Checks the chosen move and computes its edit (java-analyzer's `move`).
#[command(trust = trusted)]
pub async fn lsp_move_edit(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
pos: Pos,
destination: MoveChoice,
) -> IdeResult<ServerRefactored> {
let project = host.project(window)?;
let documents = project.documents.clone();
let version = blocking(move || documents.version(doc)).await?;
let cancel = host.begin_request(request);
let result = project.lsp.java_move_refactor(doc, pos, destination, cancel).await;
host.end_request(request);
let mut refactored = result?;
blocking(move || {
if project.documents.version(doc)? != version {
return Err(ide_core::IdeError::new(
ide_core::error::ErrorKind::OutOfSync,
"document changed while computing the refactoring; request it again",
));
}
if let Some(edit) = &mut refactored.edit {
project.documents.prepare_workspace_edit(edit)?;
}
Ok(refactored)
})
.await
}
#[command(trust = trusted)]
pub async fn lsp_signature_info(
host: &Host,
@@ -3752,10 +3828,13 @@ ide_command::domain!(
lsp_gotos,
lsp_hierarchy_members,
lsp_hierarchy_refactor,
lsp_move_info,
lsp_move_edit,
lsp_hover,
lsp_implementation_locations,
lsp_file_references,
lsp_spring_bean_markers,
lsp_spring_aop_markers,
lsp_switch_source_header,
lsp_source_definition,
lsp_open_typescript_file,
@@ -3791,6 +3870,7 @@ ide_command::domain!(
plugin_color_presentations,
plugin_formatters,
plugin_language_visuals,
plugin_line_marker_languages,
plugin_line_markers,
prepare_workspace_edit,
redo_workspace_edit,
+32 -3
Переглянути файл
@@ -33,8 +33,35 @@ pub async fn scaffold_options(
/// The programs a generator needs for `values`, and whether they are installed.
#[command(trust = always)]
pub async fn scaffold_requirements(generator: String, values: Values) -> IdeResult<Vec<Requirement>> {
blocking(move || ide_scaffold::requirements(&generator, &values)).await
pub async fn scaffold_requirements(host: &Host, generator: String, values: Values) -> IdeResult<Vec<Requirement>> {
let configured = configured_goroot(host);
blocking(move || {
let goroot = goroot(configured, &generator, &values);
ide_scaffold::requirements(&generator, &values, goroot.as_deref())
})
.await
}
/// The GOROOT chosen in the global settings (those of new projects).
fn configured_goroot(host: &Host) -> Option<PathBuf> {
host.global_settings.read_effective(|s| ide_sdk::apply::absolute_setting_path(&s.languages.go.goroot))
}
/// The Go a generator that needs `go` runs: the GOROOT chosen in Settings; else `go` from `PATH`,
/// where a version manager picks it for the target folder; else, with no `go` on `PATH` (an app
/// started from the Dock or Finder), the first Go install found on this machine, as listed in
/// Settings › Languages › Go. Blocking: detection runs `go version`.
fn goroot(configured: Option<PathBuf>, generator: &str, values: &Values) -> Option<PathBuf> {
configured.or_else(|| {
if !ide_scaffold::needs_program(generator, values, "go") {
return None;
}
let path = ide_core::process::host_var_os("PATH").unwrap_or_default();
if ide_core::process::find_executable("go", &path).is_some() {
return None;
}
ide_sdk::detect(ide_sdk::SdkKind::Go, None).into_iter().find_map(|sdk| sdk.home.map(IpcPath::into_path_buf))
})
}
/// Whether a project named `name` cannot be created in `location`: something other than an
@@ -61,8 +88,10 @@ pub async fn scaffold_create(
) -> IdeResult<IpcPath> {
// Trusted because the user just created it; a failed or cancelled run leaves no files behind.
let cancel = host.begin_request(request);
let configured = configured_goroot(host);
let result = blocking(move || {
ide_scaffold::create(&req, &cancel, &|e| {
let goroot = goroot(configured, &req.generator, &req.values);
ide_scaffold::create(&req, goroot.as_deref(), &cancel, &|e| {
let _ = on_event.send(e);
})
})
+54 -16
Переглянути файл
@@ -148,9 +148,10 @@ pub async fn svn_upgrade(
version: String,
) -> IdeResult<()> {
let project = host.project(window)?;
let cancel = host.begin_request(request);
project.require_trust()?;
let cancel = host.begin_project_request(window, request);
let result = blocking(move || {
with_working_copy(&project, Some(&repo), |wc| wc.upgrade(&version, &cancel))?;
with_working_copy(&project, Some(&repo), |wc| wc.upgrade(&repo, &version, &cancel))?;
project.vcs_changed();
Ok(())
})
@@ -844,6 +845,11 @@ pub struct SvnIncomingPath {
/// The file in the working copy, for a path under the working copy's URL.
pub local: Option<String>,
pub kind: String,
/// The repository path it was copied from (`svn copy`, or the new half of a move).
#[serde(default)]
pub copy_from: Option<String>,
#[serde(default)]
pub copy_from_revision: Option<u32>,
}
/// The Incoming tab's revisions of every Subversion working copy, and the working copies that
@@ -877,6 +883,8 @@ fn incoming_revision(root: &str, r: ide_svn::IncomingRevision) -> SvnIncomingRev
path: p.path,
local: p.local.map(|l| l.display().to_string()),
kind: p.kind,
copy_from_revision: p.copy_from.as_ref().map(|(_, r)| u32::try_from(*r).unwrap_or(u32::MAX)),
copy_from: p.copy_from.map(|(path, _)| path),
})
.collect(),
}
@@ -895,7 +903,7 @@ pub async fn svn_revisions_between(
) -> IdeResult<Vec<SvnIncomingRevision>> {
let project = host.project(window)?;
project.require_trust()?;
let cancel = host.begin_request(request);
let cancel = host.begin_project_request(window, request);
let result = blocking(move || {
with_working_copy(&project, Some(&repo), |wc| {
let root = wc.root().display().to_string();
@@ -908,23 +916,42 @@ pub async fn svn_revisions_between(
result
}
/// Incoming: for each Subversion working copy, the revisions committed to its URL after its
/// BASE revision, from BASE+1 to HEAD, as IntelliJ's Incoming tab lists them.
/// Incoming: for each Subversion working copy, the revisions the server has that it does not, as
/// IntelliJ's Incoming tab lists them. The working copies are read side by side, so one whose
/// server does not answer does not hold up the others. `quiet` (the tab reading by itself, not a
/// Refresh) asks for no login: a working copy that needs one shows the error instead.
#[command(trust = trusted)]
pub async fn svn_incoming_revisions(
host: &Host,
window: &str,
request: ide_core::RequestId,
quiet: bool,
) -> IdeResult<SvnIncomingRevisions> {
let project = host.project(window)?;
project.require_trust()?;
let cancel = host.begin_request(request);
let cancel = host.begin_project_request(window, request);
let result = blocking(move || {
let backends = project.backends();
let read = |wc: &WorkingCopy| {
if quiet { ide_svn::quietly(|| wc.incoming_revisions(&cancel)) } else { wc.incoming_revisions(&cancel) }
};
let results: Vec<(String, IdeResult<Vec<ide_svn::IncomingRevision>>)> = std::thread::scope(|scope| {
let running: Vec<_> = backends
.iter()
.filter_map(|backend| as_svn(backend.as_ref()))
.map(|wc| (wc.root().display().to_string(), scope.spawn(|| read(wc))))
.collect();
running
.into_iter()
.map(|(root, handle)| {
let result = handle.join().unwrap_or_else(|_| Err(ide_core::IdeError::internal("svn read failed")));
(root, result)
})
.collect()
});
let mut out = SvnIncomingRevisions::default();
for backend in project.backends() {
let Some(wc) = as_svn(backend.as_ref()) else { continue };
let root = wc.root().display().to_string();
match wc.incoming_revisions(&cancel) {
for (root, result) in results {
match result {
Ok(found) => out.revisions.extend(found.into_iter().map(|r| incoming_revision(&root, r))),
Err(e) if cancel.is_cancelled() => return Err(e),
Err(e) => out.errors.push(SvnWorkingCopyError { root, message: e.message }),
@@ -938,24 +965,33 @@ pub async fn svn_incoming_revisions(
result
}
/// Reads metadata for one Subversion working copy (`repo = Some`) or all Subversion working copies in the project.
/// Reads metadata for one Subversion working copy (`repo = Some`) or all Subversion working copies in the project,
/// with their switched folders; `request` stops the scan for those.
#[command(trust = trusted)]
pub async fn svn_working_copy_info(
host: &Host,
window: &str,
request: ide_core::RequestId,
repo: Option<PathBuf>,
) -> IdeResult<Vec<SvnWorkingCopyInfo>> {
let project = host.project(window)?;
project.require_trust()?;
blocking(move || {
let cancel = host.begin_project_request(window, request);
let result = blocking(move || {
if let Some(path) = repo.as_deref() {
return with_working_copy(&project, Some(path), |wc| Ok(vec![wc.working_copy_info_for(path)?.into()]));
return with_working_copy(&project, Some(path), |wc| {
Ok(vec![SvnWorkingCopyInfo {
formats: wc.supported_formats(),
..wc.working_copy_info_for(path)?.into()
}])
});
}
let mut infos: Vec<SvnWorkingCopyInfo> = Vec::new();
for backend in project.backends() {
if let Some(wc) = as_svn(backend.as_ref()) {
// One working copy that cannot be read shows its error; the others still show.
match wc.working_copy_infos() {
match wc.working_copy_infos(&cancel) {
Err(e) if cancel.is_cancelled() => return Err(e),
Ok(found) => {
let formats = wc.supported_formats();
infos.extend(
@@ -975,7 +1011,9 @@ pub async fn svn_working_copy_info(
mark_externals(&mut infos);
Ok(infos)
})
.await
.await;
host.end_request(request);
result
}
/// A working copy root inside another listed working copy is an external of it: svn checks
@@ -1245,7 +1283,7 @@ pub async fn svn_update_options(
on_output: crate::ops::Channel<String>,
) -> IdeResult<SvnUpdateResult> {
let project = host.project(window)?;
let cancel = host.begin_request(request);
let cancel = host.begin_project_request(window, request);
let result = blocking(move || {
let report = |line: String| {
let _ = on_output.send(line);
+14 -2
Переглянути файл
@@ -74,11 +74,13 @@ pub(crate) fn apply_output_rate(host: &Host, window: &str) {
}
/// Tools › Start SSH Session: a login shell on SSH configuration `id`, opened by the
/// built-in client with the configuration's saved password, key or agent.
/// built-in client with the configuration's saved password, key or agent. With `cwd` (Remote
/// Host › Start SSH Session in Directory) the shell starts in that remote folder.
pub async fn spawn_ssh(
host: &Host,
window: &str,
id: &str,
cwd: Option<&str>,
cols: u16,
rows: u16,
on_output: Emit<String>,
@@ -93,7 +95,7 @@ pub async fn spawn_ssh(
let out = feed.clone();
let process = session
.spawn(
"",
&ssh_shell_command(cwd),
Some(size),
Box::new(move |chunk| match chunk {
ide_ssh::Output::Stdout(data) | ide_ssh::Output::Stderr(data) => out.output(data),
@@ -134,6 +136,16 @@ pub async fn spawn_ssh(
)
}
/// The exec command of an SSH terminal: empty for the account's shell, or a `cd` into `cwd` that
/// then replaces itself with the login shell. A `cd` that fails prints its error and leaves the
/// shell in the home folder.
fn ssh_shell_command(cwd: Option<&str>) -> String {
match cwd.map(str::trim).filter(|d| !d.is_empty()) {
None => String::new(),
Some(dir) => format!("cd -- {}; exec \"${{SHELL:-/bin/sh}}\" -l", ide_ssh::shell::tilde_quote(dir)),
}
}
enum SshInput {
Data(Vec<u8>),
Resize(u16, u16),
+34 -5
Переглянути файл
@@ -367,6 +367,18 @@ pub struct UpdateReport {
pub from_revision: Option<String>,
#[serde(default)]
pub to_revision: Option<String>,
/// Externals the update fetched, each with its own revision.
#[serde(default)]
pub externals: Vec<ExternalUpdateReport>,
}
/// The files of an external an update fetched: another repository, at its own revision.
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExternalUpdateReport {
pub root: PathBuf,
pub items: Vec<UpdatedItemReport>,
pub to_revision: Option<String>,
}
/// One file or folder of an [`UpdateReport`]: `action` is svn's four status columns as it
@@ -376,6 +388,18 @@ pub struct UpdateReport {
pub struct UpdatedItemReport {
pub path: PathBuf,
pub action: String,
/// Its path in the repository (`/trunk/src/a.txt`), when known.
#[serde(default)]
pub repo_path: Option<String>,
/// Its own revision before the update, when not the working copy's (`from_revision`).
#[serde(default)]
pub from_revision: Option<String>,
}
impl From<ide_vcs::UpdatedItem> for UpdatedItemReport {
fn from(i: ide_vcs::UpdatedItem) -> Self {
Self { path: i.path, action: i.action, repo_path: i.repo_path, from_revision: i.from_revision }
}
}
#[derive(Serialize, Deserialize, Type)]
@@ -2040,13 +2064,18 @@ pub async fn vcs_remote(
b.update(paths, &cancel, &out).map(|summary| {
Some(RemoteOpReport::Update(UpdateReport {
updated_files: u32::try_from(summary.changed).unwrap_or(u32::MAX),
items: summary
.items
.into_iter()
.map(|i| UpdatedItemReport { path: i.path, action: i.action })
.collect(),
items: summary.items.into_iter().map(Into::into).collect(),
from_revision: summary.from_revision,
to_revision: summary.to_revision,
externals: summary
.externals
.into_iter()
.map(|e| ExternalUpdateReport {
root: e.root,
items: e.items.into_iter().map(Into::into).collect(),
to_revision: e.to_revision,
})
.collect(),
}))
})
})
+56
Переглянути файл
@@ -314,6 +314,16 @@ const DEFAULT_STREAM_BUFFER: usize = 256 << 10;
const DEFAULT_STREAM_MAX_TOTAL: usize = 32 << 20;
/// Most processes one plugin keeps running at once.
const MAX_PROCESSES: usize = 8;
/// Pending `events.schedule` timers per plugin.
const MAX_TIMERS: usize = 16;
/// A pending `events.schedule` timer: fires `id` in window `client` at `due`.
#[derive(Clone, Debug)]
pub(super) struct Timer {
pub id: String,
pub due: Instant,
pub client: Option<String>,
}
/// Most output one stream of a handle holds until the plugin reads it.
const MAX_PENDING: usize = 1 << 20;
/// Most files `find-files` walks before giving up.
@@ -810,6 +820,8 @@ pub(super) struct Shared {
pub subscriptions: Mutex<super::event_paths::Subscriptions>,
/// Paths outside their project that plugins watch (kept across idle reclaim).
pub(super) external_watches: super::external_watch::ExternalWatches,
/// plugin → its pending `events.schedule` timers (kept across idle reclaim).
pub(super) timers: Mutex<HashMap<String, Vec<Timer>>>,
/// plugin → files it shows problems for, withdrawn when it stops.
diagnostics: Mutex<HashMap<String, BTreeSet<PathBuf>>>,
project_generations: Mutex<HashMap<PathBuf, u64>>,
@@ -918,6 +930,7 @@ impl Shared {
closed_clients: Mutex::default(),
subscriptions: Mutex::default(),
external_watches: Default::default(),
timers: Mutex::default(),
diagnostics: Mutex::default(),
project_generations: Mutex::default(),
log_tabs: Mutex::default(),
@@ -1064,6 +1077,9 @@ impl Shared {
self.prompts.lock().retain(|_, entry| entry.client != client);
drop(closed);
self.contexts.lock().retain(|(scope, ..), _| scope.as_deref() != Some(client));
for timers in self.timers.lock().values_mut() {
timers.retain(|t| t.client.as_deref() != Some(client));
}
self.loopbacks.read().forget_window(client);
self.window_status.lock().retain(|(window, ..), _| window != client);
self.view_badges.lock().retain(|(window, ..), _| window != client);
@@ -1120,6 +1136,24 @@ impl Shared {
.retain(|(p, w), _| plugin.is_some_and(|plugin| plugin != p) || window.is_some_and(|window| window != w));
}
/// Removes the timers due at `now`: (plugin, window, id), earliest first.
pub(super) fn take_due_timers(&self, now: Instant) -> Vec<(String, Option<String>, String)> {
let mut due = Vec::new();
let mut all = self.timers.lock();
for (plugin, timers) in all.iter_mut() {
timers.retain(|t| {
if t.due > now {
return true;
}
due.push((t.due, plugin.clone(), t.client.clone(), t.id.clone()));
false
});
}
all.retain(|_, timers| !timers.is_empty());
due.sort_by_key(|(at, ..)| *at);
due.into_iter().map(|(_, plugin, client, id)| (plugin, client, id)).collect()
}
pub fn client_closed(&self, client: &str) -> bool {
self.closed_clients.lock().contains(client)
}
@@ -1224,6 +1258,7 @@ impl Shared {
}
if subscriptions {
self.external_watches.remove_plugin(plugin);
self.timers.lock().remove(plugin);
}
if subscriptions && self.subscriptions.lock().remove(plugin) {
self.sink.emit(None, PluginEvent::SubscriptionsChanged);
@@ -3825,6 +3860,27 @@ impl HostApi for PluginApi {
self.shared.sink.emit(None, PluginEvent::SubscriptionsChanged);
}
}
fn schedule(&self, client: Option<&str>, id: &str, after: Duration) -> Result<(), HostError> {
if client.is_some_and(|c| self.shared.client_closed(c)) {
return Err(HostError::Cancelled);
}
let mut timers = self.shared.timers.lock();
let mine = timers.entry(self.id().to_owned()).or_default();
mine.retain(|t| t.id != id);
if mine.len() >= MAX_TIMERS {
return Err(HostError::Invalid(format!("at most {MAX_TIMERS} timers may be pending: cancel one first")));
}
mine.push(Timer { id: id.to_owned(), due: Instant::now() + after, client: client.map(str::to_owned) });
Ok(())
}
fn cancel_schedule(&self, id: &str) {
let mut timers = self.shared.timers.lock();
if let Some(mine) = timers.get_mut(self.id()) {
mine.retain(|t| t.id != id);
}
}
fn start_process(&self, cmd: ProcessCommand, cwd: Option<&Path>, client: Option<&str>) -> Result<u64, HostError> {
self.start_process_stream(cmd, cwd, client, None)
}
+2 -1
Переглянути файл
@@ -480,7 +480,8 @@ mod tests {
#[test]
fn every_runtime_event_has_a_matching_manifest_activation() {
for kind in ide_plugin::EventKind::ALL {
if kind != ide_plugin::EventKind::Scheduled {
// `on-schedule` and `events.schedule` timers activate the plugin themselves.
if !matches!(kind, ide_plugin::EventKind::Scheduled | ide_plugin::EventKind::Timer) {
assert!(ide_extension::EVENT_KINDS.contains(&kind.name()));
}
}
+32 -1
Переглянути файл
@@ -2144,6 +2144,10 @@ impl PluginHost {
pub fn project_closed(&self, root: &Path, window: &str) {
self.shared.close_project_generation(root);
self.shared.external_watches.remove_project(root);
// Timers set for the window's project don't outlive it.
for timers in self.shared.timers.lock().values_mut() {
timers.retain(|t| t.client.as_deref() != Some(window));
}
self.withdraw_project_run_targets(root);
self.shared.run_configurations.write().retain(|(_, r), _| r != root);
@@ -2359,6 +2363,28 @@ impl PluginHost {
}
}
/// Queues the `events.schedule` timers due at `now` for their plugin and window.
fn queue_due_timers(&self, now: Instant) {
let due = self.shared.take_due_timers(now);
if due.is_empty() {
return;
}
let mut queues = self.queues.lock();
for (plugin, client, id) in due {
if client.as_deref().is_some_and(|c| self.shared.client_closed(c)) {
continue;
}
let queue = queues.entry((plugin, client)).or_insert_with(|| EventQueue {
since: now,
last_event: now,
events: Vec::new(),
files_source: None,
});
queue.last_event = now;
queue.events.push(WorkbenchEvent::Timer(id));
}
}
pub fn post_events(&self, client: Option<&str>, events: Vec<WorkbenchEvent>) {
self.post_events_from(client, events, None);
}
@@ -2446,6 +2472,7 @@ impl PluginHost {
| WorkbenchEvent::RunExited(_)
| WorkbenchEvent::TerminalExited(_)
| WorkbenchEvent::ContentTabAction(_)
| WorkbenchEvent::Timer(_)
)
{
remaining -= 1;
@@ -2470,6 +2497,7 @@ impl PluginHost {
pub fn flush_events_at(&self, now: Instant) {
self.reload_changed_links();
self.queue_watched_changes(now);
self.queue_due_timers(now);
let running: BTreeSet<String> = self
.plugins
.read()
@@ -2494,7 +2522,9 @@ impl PluginHost {
let (id, _client) = key;
let running = running.contains(id);
let has_files = q.events.iter().any(|e| matches!(e, WorkbenchEvent::FilesChanged(_)));
let has_scheduled = q.events.iter().any(|e| matches!(e, WorkbenchEvent::Scheduled));
// Due now: a timer was set for this moment, an `on-schedule` period elapsed.
let has_scheduled =
q.events.iter().any(|e| matches!(e, WorkbenchEvent::Scheduled | WorkbenchEvent::Timer(_)));
// Already debounced by the watcher, like project file changes.
let has_watched = q.events.iter().any(|e| matches!(e, WorkbenchEvent::WatchedFilesChanged(_)));
let debounce = debounces.get(id).copied();
@@ -2680,6 +2710,7 @@ impl PluginHost {
| EventKind::RunExited
| EventKind::TerminalExited
| EventKind::ContentTabAction
| EventKind::Timer
)
})
{
+74 -13
Переглянути файл
@@ -128,6 +128,29 @@ impl Providers {
out
}
/// Each plugin's languages declared for `kind`, in declaration order.
fn languages_by_plugin(&self, kind: ProviderKind) -> Vec<(String, Vec<String>)> {
let mut out: Vec<(String, Vec<String>)> = Vec::new();
for (_, plugin, kinds, languages) in self.items.read().iter() {
if !kinds.contains(&kind) {
continue;
}
let at = match out.iter().position(|(id, _)| id == plugin) {
Some(at) => at,
None => {
out.push((plugin.clone(), Vec::new()));
out.len() - 1
}
};
for language in languages {
if !out[at].1.contains(language) {
out[at].1.push(language.clone());
}
}
}
out
}
/// One coherent declaration snapshot, preserving the first match per plugin.
fn matching<T: FromIterator<(String, u64)>>(&self, kind: ProviderKind, language: &str) -> T {
let items = self.items.read();
@@ -301,6 +324,11 @@ use std::collections::BTreeSet;
use std::sync::Weak;
use std::time::{Duration, Instant};
fn usable_provider(p: &LoadedPlugin) -> bool {
let m = p.meta.lock();
matches!(m.status, PluginStatus::Active | PluginStatus::Inactive) && m.pending.is_empty()
}
/// What the plugins answered for completion in the editor.
#[derive(Debug, Default)]
pub(crate) struct EditorCompletion {
@@ -342,13 +370,29 @@ impl PluginHost {
.plugins_for(kind, language)
.into_iter()
.filter_map(|id| self.get(&id).ok())
.filter(|p| {
let m = p.meta.lock();
matches!(m.status, PluginStatus::Active | PluginStatus::Inactive) && m.pending.is_empty()
})
.filter(|p| usable_provider(p))
.collect()
}
/// The languages a usable plugin declares for `line-markers` along with `language` (`"*"` for
/// every language), without loading any plugin: a saved file of `language` can change the
/// markers of the files of these languages.
pub fn line_marker_languages_with(&self, language: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for (id, languages) in self.providers.languages_by_plugin(ProviderKind::LineMarkers) {
let covers = languages.iter().any(|l| l == "*" || l == language);
if !covers || !self.get(&id).is_ok_and(|p| usable_provider(&p)) {
continue;
}
for l in languages {
if !out.contains(&l) {
out.push(l);
}
}
}
out
}
/// Edit-path calls (soft / hard deadline) to every usable plugin that
/// declares `kind` for `language`, in plugin order, leaving out those that
/// failed or were late. Each plugin runs on its own thread, so the calls
@@ -399,6 +443,14 @@ impl PluginHost {
plugins: Vec<Arc<LoadedPlugin>>,
f: impl FnOnce(&mut Runtime, Duration) -> Result<R, CallError> + Clone + Send + 'static,
) -> Vec<(Arc<LoadedPlugin>, R)> {
self.edit_calls_plugins_late(plugins, f).0
}
/// [`Self::edit_calls_plugins`], plus the ids of the plugins whose call was dropped as late.
fn edit_calls_plugins_late<R: Send + 'static>(
&self,
plugins: Vec<Arc<LoadedPlugin>>,
f: impl FnOnce(&mut Runtime, Duration) -> Result<R, CallError> + Clone + Send + 'static,
) -> (Vec<(Arc<LoadedPlugin>, R)>, Vec<String>) {
let (soft, hard) = (self.limits.edit_soft, self.limits.edit_hard);
let queued: Vec<_> = plugins
.into_iter()
@@ -413,13 +465,18 @@ impl PluginHost {
Some((plugin, actor, started, call))
})
.collect();
queued
let mut late = Vec::new();
let answers = queued
.into_iter()
.filter_map(|(plugin, actor, started, call)| {
let result = call.and_then(Pending::wait);
if matches!(result, Err(ActorError::SoftTimeout)) {
late.push(plugin.id().to_owned());
}
self.finish_provider_call(&plugin, &actor, started, result).map(|r| (plugin, r))
})
.collect()
.collect();
(answers, late)
}
fn edit_calls_cancellable<R: Send + 'static>(
@@ -663,14 +720,18 @@ impl PluginHost {
})
}
pub fn provide_line_markers(&self, doc: &ProviderDocument) -> Vec<(String, LineMarker)> {
/// The markers by plugin id, and the ids of the plugins too late to answer: they gave no
/// answer, not "no markers".
pub fn provide_line_markers(&self, doc: &ProviderDocument) -> (Vec<(String, LineMarker)>, Vec<String>) {
let d = Arc::new(doc.clone());
self.edit_calls(ProviderKind::LineMarkers, &doc.language, move |rt, timeout| {
rt.provide_line_markers(&d, timeout)
})
.into_iter()
.flat_map(|(p, markers)| markers.into_iter().map(move |m| (p.id().to_owned(), m)))
.collect()
let plugins = self.provider_plugins(ProviderKind::LineMarkers, &doc.language);
let (answers, late) =
self.edit_calls_plugins_late(plugins, move |rt, timeout| rt.provide_line_markers(&d, timeout));
let markers = answers
.into_iter()
.flat_map(|(p, markers)| markers.into_iter().map(move |m| (p.id().to_owned(), m)))
.collect();
(markers, late)
}
pub fn provide_semantic_tokens(&self, doc: &ProviderDocument) -> Vec<SemanticToken> {
+10
Переглянути файл
@@ -550,6 +550,16 @@ pub struct LineMarkerInfo {
pub target: Option<ide_core::Location>,
}
/// The answer of the `line-markers` providers for a document.
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct LineMarkers {
pub markers: Vec<LineMarkerInfo>,
/// Plugins whose call ran past the edit-path budget and was dropped: they gave no answer,
/// so the editor keeps the markers it shows from them.
pub late: Vec<String>,
}
/// A plugin's before-commit check to run (`[[contributes.commitChecks]]`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+1 -1
Переглянути файл
@@ -202,7 +202,7 @@ pub async fn move_symbols(
let problems: Vec<RefactoringProblem> = moved
.warnings
.into_iter()
.map(|message| RefactoringProblem { severity: ProblemSeverity::Warning, message })
.map(|message| RefactoringProblem { severity: ProblemSeverity::Warning, message, location: None })
.collect();
// The token names the warnings shown: others that appear meanwhile are asked about again.
let mut hasher = std::hash::DefaultHasher::new();
+5 -1
Переглянути файл
@@ -225,7 +225,11 @@ pub async fn change_signature(
let problems: Vec<RefactoringProblem> = changed
.warnings
.iter()
.map(|message| RefactoringProblem { severity: ProblemSeverity::Warning, message: message.clone() })
.map(|message| RefactoringProblem {
severity: ProblemSeverity::Warning,
message: message.clone(),
location: None,
})
.collect();
if !problems.is_empty() && confirmation.as_deref() != Some(CONFIRMATION) {
return Ok(ServerRefactored { problems, edit: None, confirmation: Some(CONFIRMATION.into()) });
+1
Переглянути файл
@@ -57,6 +57,7 @@ mod plugin_semantic_tokens;
mod plugin_server_commands;
mod plugin_symbols;
mod plugin_syntax_decorations;
mod plugin_timers;
mod plugin_view_badge;
mod plugin_watch_paths;
mod plugin_workbench;
+477
Переглянути файл
@@ -3,6 +3,7 @@ use crate::common;
use ide_core::{
CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, Severity, TextChange, event::McpUiRequest,
};
use ide_db::{DataSource, DbDriver};
use ide_host::mcp::{BackgroundProjects, FileProblems, FocusedEditor, Registry};
use ide_host::{Host, HostConfig};
use ide_mcp::ToolRegistry;
@@ -3144,3 +3145,479 @@ async fn automation_tools_enforce_trust_mandatory_confirm_even_in_brave_mode_and
assert_eq!(del_res["deletedId"], imported_id);
assert!(h.host.automations.get(&imported_id).is_none());
}
/// The project's SQLite data source `db`: `users` with 150 rows and a foreign key to itself,
/// the `users_name` unique index and the `named` view.
async fn sqlite_fixture(h: &Harness) {
std::fs::File::create(h.root.join("data.sqlite")).unwrap();
let db = h.host.project("main").unwrap().db.clone();
db.save_sources(vec![DataSource {
id: "db".into(),
name: "Test DB".into(),
driver: DbDriver::Sqlite,
file: Some(h.root.join("data.sqlite").into()),
..Default::default()
}])
.await
.unwrap();
let c = CancellationToken::new();
for stmt in [
"CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, manager_id INTEGER REFERENCES users(id))",
"CREATE UNIQUE INDEX users_name ON users(name)",
"CREATE VIEW named AS SELECT name FROM users",
] {
db.execute("db", stmt, 100, &c).await.unwrap();
}
let rows: Vec<String> = (1..=150).map(|id| format!("({id}, 'user{id:03}')")).collect();
db.execute("db", &format!("INSERT INTO users (id, name) VALUES {}", rows.join(", ")), 100, &c).await.unwrap();
}
/// Writes `.openidea/data-sources.toml` as a crafted repository might: `save_sources` rejects
/// duplicate ids, so a test of the tool boundary needs the file itself.
fn write_sources_file(root: &Path, sources: &[DataSource]) {
let tables: Vec<toml::Value> = sources
.iter()
.map(|source| {
let mut value = toml::Value::try_from(source).unwrap();
value.as_table_mut().unwrap().remove("global");
value
})
.collect();
let doc = toml::Value::Table(toml::map::Map::from_iter([("data-source".to_owned(), toml::Value::Array(tables))]));
std::fs::create_dir_all(root.join(".openidea")).unwrap();
std::fs::write(root.join(".openidea/data-sources.toml"), toml::to_string_pretty(&doc).unwrap()).unwrap();
}
/// Runs `name` in the project's window and allows the confirmation it asks there; the window
/// must be ready (`h.host.mcp_requests.set_ready("main", true)`).
async fn confirmed(h: &Harness, name: &str, args: Value) -> String {
h.events.lock().unwrap().clear();
let call = h.call(name, args);
let allow = async {
let id = h.request().await;
h.host.mcp_requests.answer("main", id, true, None).unwrap();
};
let (result, ()) = tokio::join!(call, allow);
result
}
/// Like [`confirmed`], for a call that must fail after the confirmation.
async fn confirmed_error(h: &Harness, name: &str, args: Value) -> String {
h.events.lock().unwrap().clear();
let call = h.error(name, args);
let allow = async {
let id = h.request().await;
h.host.mcp_requests.answer("main", id, true, None).unwrap();
};
let (result, ()) = tokio::join!(call, allow);
result
}
#[tokio::test(flavor = "multi_thread")]
async fn database_connections_are_listed_without_urls_hosts_or_credentials() {
let h = Harness::new();
sqlite_fixture(&h).await;
assert!(!h.host.project("main").unwrap().is_trusted(), "the metadata tools need a trusted project");
let refused = h.error("list_database_connections", json!({})).await;
assert!(refused.contains("Restricted Mode"), "{refused}");
h.trust().await;
let raw = h.call("list_database_connections", json!({})).await;
let listed: Value = serde_json::from_str(&raw).unwrap();
assert_eq!(
listed["connections"],
json!([{ "id": "db", "name": "Test DB", "driver": "sqlite", "database": "", "readOnly": false, "global": false }])
);
for key in ["url", "host", "user", "password"] {
assert!(!raw.contains(&format!("\"{key}\"")), "`{key}` in {raw}");
}
// A URL-only source's URL, host and user never reach the agent either.
let db = h.host.project("main").unwrap().db.clone();
let mut sources = db.sources().unwrap();
sources.push(DataSource {
id: "remote".into(),
name: "Remote".into(),
driver: DbDriver::Postgres,
url_only: true,
url: "postgres://db.example.invalid:5432/app".into(),
..Default::default()
});
db.save_sources(sources).await.unwrap();
let raw = h.call("list_database_connections", json!({})).await;
assert!(raw.contains("\"remote\""), "{raw}");
for secret in ["db.example.invalid", "5432", "app"] {
assert!(!raw.contains(secret), "`{secret}` in {raw}");
}
}
/// Global data sources are stored app-wide and listed in every project; the list marks them.
#[tokio::test(flavor = "multi_thread")]
async fn global_data_sources_are_listed_with_a_global_flag() {
let h = Harness::new();
sqlite_fixture(&h).await;
ide_db::source::save_global(
&h.host.data_dir,
&[DataSource {
id: "shared".into(),
name: "Shared".into(),
driver: DbDriver::Sqlite,
file: Some(h.root.join("data.sqlite").into()),
..Default::default()
}],
)
.unwrap();
h.trust().await;
let listed: Value = serde_json::from_str(&h.call("list_database_connections", json!({})).await).unwrap();
let connections = listed["connections"].as_array().unwrap();
let project = connections.iter().find(|c| c["id"] == "db").expect("the project source");
assert_eq!(project["global"], false, "{listed}");
let global = connections.iter().find(|c| c["id"] == "shared").expect("the global source");
assert_eq!(global["global"], true, "{listed}");
}
#[tokio::test(flavor = "multi_thread")]
async fn database_schemas_and_objects_are_listed_in_a_trusted_project() {
let h = Harness::new();
sqlite_fixture(&h).await;
for (name, args) in [
("list_database_schemas", json!({"connectionId": "db"})),
("list_schema_objects", json!({"connectionId": "db", "schema": "main"})),
] {
let refused = h.error(name, args).await;
assert!(refused.contains("Restricted Mode"), "{name}: {refused}");
}
h.trust().await;
let schemas = h.json("list_database_schemas", json!({"connectionId": "db"})).await;
assert_eq!(schemas["connectionId"], "db");
assert_eq!(schemas["schemas"], json!(["main"]));
// Tables and views are objects; the unique index is not.
let all = h.json("list_schema_objects", json!({"connectionId": "db", "schema": "main"})).await;
assert_eq!(all["objects"], json!([{"kind": "view", "name": "named"}, {"kind": "table", "name": "users"}]), "{all}");
assert!(!all.to_string().contains("users_name"), "{all}");
let views = h.json("list_schema_objects", json!({"connectionId": "db", "schema": "main", "kind": "view"})).await;
assert_eq!(views["objects"], json!([{"kind": "view", "name": "named"}]), "{views}");
}
#[tokio::test(flavor = "multi_thread")]
async fn database_object_description_reads_columns_indexes_and_foreign_keys() {
let h = Harness::new();
sqlite_fixture(&h).await;
let args = json!({"connectionId": "db", "schema": "main", "objectName": "users"});
let refused = h.error("get_database_object_description", args.clone()).await;
assert!(refused.contains("Restricted Mode"), "{refused}");
h.trust().await;
let described = h.json("get_database_object_description", args).await;
assert_eq!(
(&described["connectionId"], &described["schema"], &described["objectName"]),
(&json!("db"), &json!("main"), &json!("users"))
);
let details = &described["details"];
let columns = details["columns"].as_array().unwrap();
let names: Vec<&str> = columns.iter().map(|c| c["name"].as_str().unwrap()).collect();
assert_eq!(names, ["id", "name", "manager_id"]);
assert_eq!(columns[0]["primaryKey"], true);
assert_eq!(columns[1]["nullable"], false);
let index = details["indexes"].as_array().unwrap().iter().find(|i| i["name"] == "users_name").expect("users_name");
assert_eq!(index["unique"], true);
assert_eq!(index["columns"], json!(["name"]));
let keys = details["foreignKeys"].as_array().unwrap();
assert_eq!(keys.len(), 1, "{described}");
assert_eq!(keys[0]["columns"], json!(["manager_id"]));
assert_eq!(keys[0]["refSchema"], "main");
assert_eq!(keys[0]["refTable"], "users");
assert_eq!(keys[0]["refColumns"], json!(["id"]));
}
#[tokio::test(flavor = "multi_thread")]
async fn execute_sql_query_is_a_write_tool_that_needs_trust() {
let h = Harness::new();
sqlite_fixture(&h).await;
let untrusted = Registry::new(h.host.clone()).tools(&h.root).unwrap();
for name in
["list_database_connections", "list_database_schemas", "list_schema_objects", "get_database_object_description"]
{
assert!(untrusted.iter().any(|t| t.name == name && t.read_only), "{name} is a read tool");
}
assert!(untrusted.iter().all(|t| t.name != "execute_sql_query"), "a write tool is hidden until trust");
// The metadata tools are still listed, but their calls need trust too, not only the write tool.
for (name, args) in [
("list_database_connections", json!({})),
("list_database_schemas", json!({"connectionId": "db"})),
("list_schema_objects", json!({"connectionId": "db", "schema": "main"})),
("get_database_object_description", json!({"connectionId": "db", "schema": "main", "objectName": "users"})),
] {
let message = h.error(name, args).await;
assert!(message.contains("Restricted Mode"), "{name}: {message}");
}
// Calling it directly is refused too, not only hidden from the list.
let refused = Registry::new(h.host.clone()).call(
&h.root,
"execute_sql_query",
&json!({"connectionId": "db", "sql": "SELECT 1"}).to_string(),
CancellationToken::new(),
);
let message = match refused.expect_err("a write tool is refused in Restricted Mode") {
ide_mcp::ToolCallError::Failed(message) | ide_mcp::ToolCallError::UnknownTool(message) => message,
};
assert!(message.contains("Restricted Mode"), "{message}");
h.trust().await;
let trusted = Registry::new(h.host.clone()).tools(&h.root).unwrap();
let tool = trusted.iter().find(|t| t.name == "execute_sql_query").expect("offered once trusted");
assert!(!tool.read_only);
}
#[tokio::test(flavor = "multi_thread")]
async fn execute_sql_query_pages_rows_and_cuts_long_cells() {
let h = Harness::new();
sqlite_fixture(&h).await;
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
let page: Value = serde_json::from_str(
&confirmed(
&h,
"execute_sql_query",
json!({"connectionId": "db", "sql": "SELECT id, name FROM users ORDER BY id", "maxRows": 10}),
)
.await,
)
.unwrap();
assert_eq!(page["rowCount"], 10, "{page}");
assert_eq!(page["rows"].as_array().unwrap().len(), 10);
assert_eq!(page["hasMore"], true);
assert_eq!(page["rows"][0], json!(["1", "user001"]));
// The dialog showed the exact statement, not the raw arguments or a truncated form.
let detail = h
.events
.lock()
.unwrap()
.iter()
.find_map(|(_, event)| match event {
IdeEvent::McpRequest { request: McpUiRequest::Confirm { detail, .. }, .. } => {
Some(detail.clone().unwrap_or_default())
}
_ => None,
})
.expect("a confirmation was asked");
assert!(detail.contains("SQL:\nSELECT id, name FROM users ORDER BY id"), "{detail}");
assert!(detail.contains("Driver: SQLite"), "{detail}");
let columns: Vec<&str> = page["columns"].as_array().unwrap().iter().map(|c| c["name"].as_str().unwrap()).collect();
assert_eq!(columns, ["id", "name"]);
// Without `maxRows` the result stops at the default of 100, and says more rows exist.
let default: Value = serde_json::from_str(
&confirmed(&h, "execute_sql_query", json!({"connectionId": "db", "sql": "SELECT id FROM users ORDER BY id"}))
.await,
)
.unwrap();
assert_eq!(default["rowCount"], 100, "{default}");
assert_eq!(default["rows"].as_array().unwrap().len(), 100);
assert_eq!(default["hasMore"], true);
// A cell longer than 4096 UTF-16 units is cut and reported in `truncated`.
let sql = format!("SELECT '{}' AS long", "x".repeat(5000));
let long: Value =
serde_json::from_str(&confirmed(&h, "execute_sql_query", json!({"connectionId": "db", "sql": sql})).await)
.unwrap();
assert_eq!(long["rows"][0][0].as_str().unwrap().chars().count(), 4096);
let truncated = long["truncated"].as_array().unwrap();
assert_eq!(truncated.len(), 1, "{long}");
assert_eq!(truncated[0]["length"], 5000);
assert_eq!((&truncated[0]["row"], &truncated[0]["column"]), (&json!(0), &json!(0)));
}
#[tokio::test(flavor = "multi_thread")]
async fn execute_sql_query_refuses_several_statements_and_writes_before_asking() {
let h = Harness::new();
sqlite_fixture(&h).await;
h.trust().await;
let several = h.error("execute_sql_query", json!({"connectionId": "db", "sql": "SELECT 1; SELECT 2"})).await;
assert!(several.contains("exactly one statement"), "{several}");
let write = h.error("execute_sql_query", json!({"connectionId": "db", "sql": "DELETE FROM users"})).await;
assert!(write.contains("DELETE is not allowed"), "{write}");
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
let count = h
.host
.project("main")
.unwrap()
.db
.execute("db", "SELECT count(*) FROM users", 1, &CancellationToken::new())
.await
.unwrap();
assert_eq!(count.rows, vec![vec![Some("150".into())]]);
}
#[tokio::test(flavor = "multi_thread")]
async fn execute_sql_query_refuses_a_driver_without_a_read_only_session_before_asking() {
let h = Harness::new();
let db = h.host.project("main").unwrap().db.clone();
db.save_sources(vec![DataSource {
id: "mssql".into(),
name: "SQL Server".into(),
driver: DbDriver::SqlServer,
host: "127.0.0.1".into(),
port: Some(1),
user: "sa".into(),
..Default::default()
}])
.await
.unwrap();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
h.events.lock().unwrap().clear();
// The refusal happens before a connection is opened, so no server is needed.
let error = h.error("execute_sql_query", json!({"connectionId": "mssql", "sql": "SELECT 1"})).await;
assert!(error.contains("SQL Server has no read-only session"), "{error}");
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
}
/// A statement that passes the `SELECT`/`WITH` allowlist but writes through a CTE is refused by the
/// driver-enforced read-only session (`PRAGMA query_only`), not by the keyword check. Unlike the
/// gated PostgreSQL test, this runs everywhere SQLite does.
#[tokio::test(flavor = "multi_thread")]
async fn execute_sql_query_refuses_a_cte_write_through_the_read_only_session() {
let h = Harness::new();
sqlite_fixture(&h).await;
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
let error = confirmed_error(
&h,
"execute_sql_query",
json!({"connectionId": "db", "sql": "WITH d AS (SELECT 1) DELETE FROM users"}),
)
.await;
assert!(error.to_ascii_lowercase().contains("readonly"), "{error}");
let count = h
.host
.project("main")
.unwrap()
.db
.execute("db", "SELECT count(*) FROM users", 1, &CancellationToken::new())
.await
.unwrap();
assert_eq!(count.rows, vec![vec![Some("150".into())]], "the session refused the write before it ran");
}
#[tokio::test(flavor = "multi_thread")]
async fn execute_sql_query_can_be_denied_without_changing_the_database() {
let h = Harness::new();
sqlite_fixture(&h).await;
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
let denied =
h.error("execute_sql_query", json!({"connectionId": "db", "sql": "SELECT name FROM users ORDER BY id"}));
let deny = async {
let id = h.request().await;
h.host.mcp_requests.answer("main", id, false, None).unwrap();
};
let (error, ()) = tokio::join!(denied, deny);
assert!(error.contains("denied by the user"), "{error}");
let count = h
.host
.project("main")
.unwrap()
.db
.execute("db", "SELECT count(*) FROM users", 1, &CancellationToken::new())
.await
.unwrap();
assert_eq!(count.rows, vec![vec![Some("150".into())]]);
}
/// A crafted project file cannot route a tool to a plugin-owned source: its id is refused when
/// plugin-owned, a `:database` suffix is refused, and two entries with one id are refused.
#[tokio::test(flavor = "multi_thread")]
async fn database_tools_refuse_plugin_and_ambiguous_connection_ids() {
let h = Harness::new();
sqlite_fixture(&h).await;
h.trust().await;
let file: ide_core::IpcPath = h.root.join("data.sqlite").into();
let plugin = |id: &str| DataSource {
id: id.into(),
name: "Plugin source".into(),
driver: DbDriver::Sqlite,
file: Some(file.clone()),
plugin_owner: Some("sample".into()),
plugin_source_id: Some("owned".into()),
..Default::default()
};
let user = |id: &str| DataSource {
id: id.into(),
name: "User source".into(),
driver: DbDriver::Sqlite,
file: Some(file.clone()),
..Default::default()
};
write_sources_file(
&h.root,
&[
plugin("plugin-owned"),
user("plugin-owned:database"),
// The plugin entry first: `DbManager` takes the first matching prefix.
plugin("dup"),
user("dup"),
],
);
let colon = h.error("list_database_schemas", json!({"connectionId": "plugin-owned:database"})).await;
assert!(colon.contains("without a `:database` part"), "{colon}");
let owned = h.error("list_database_schemas", json!({"connectionId": "plugin-owned"})).await;
assert!(owned.contains("no data source plugin-owned"), "{owned}");
let duplicate = h.error("list_database_schemas", json!({"connectionId": "dup"})).await;
assert!(duplicate.contains("more than one data source"), "{duplicate}");
// `list_database_connections` keeps its own filter: only the user entries appear.
let listed: Value = serde_json::from_str(&h.call("list_database_connections", json!({})).await).unwrap();
let ids: Vec<&str> = listed["connections"].as_array().unwrap().iter().map(|c| c["id"].as_str().unwrap()).collect();
assert!(!ids.contains(&"plugin-owned"), "{listed}");
}
/// Driver and tunnel errors can name the user or the host; no database tool may pass them on.
#[tokio::test(flavor = "multi_thread")]
async fn database_tool_errors_hide_the_user_host_and_url() {
let h = Harness::new();
let db = h.host.project("main").unwrap().db.clone();
db.save_sources(vec![DataSource {
id: "remote".into(),
name: "Remote".into(),
driver: DbDriver::Postgres,
user: "alice".into(),
host: "127.0.0.1".into(),
url_only: true,
url: "postgres://alice:[email protected]:1/app".into(),
..Default::default()
}])
.await
.unwrap();
let assert_hidden = |text: &str| {
for secret in ["alice", "127.0.0.1", "postgres://"] {
assert!(!text.contains(secret), "`{secret}` in {text}");
}
};
h.trust().await;
let listed = h.call("list_database_connections", json!({})).await;
assert_hidden(&listed);
let schemas = h.error("list_database_schemas", json!({"connectionId": "remote"})).await;
assert_hidden(&schemas);
h.host.mcp_requests.set_ready("main", true);
let query = confirmed_error(&h, "execute_sql_query", json!({"connectionId": "remote", "sql": "SELECT 1"})).await;
assert_hidden(&query);
}
#[tokio::test(flavor = "multi_thread")]
async fn execute_sql_query_still_answers_a_select_on_a_read_only_data_source() {
let h = Harness::new();
sqlite_fixture(&h).await;
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
// The data source's own read-only setting is respected: queries still run, and it is listed as such.
let db = h.host.project("main").unwrap().db.clone();
let mut sources = db.sources().unwrap();
sources.iter_mut().find(|s| s.id == "db").unwrap().read_only = true;
db.save_sources(sources).await.unwrap();
let listed: Value = serde_json::from_str(&h.call("list_database_connections", json!({})).await).unwrap();
assert_eq!(listed["connections"][0]["readOnly"], true, "{listed}");
let result: Value = serde_json::from_str(
&confirmed(&h, "execute_sql_query", json!({"connectionId": "db", "sql": "SELECT count(*) AS n FROM users"}))
.await,
)
.unwrap();
assert_eq!(result["rows"], json!([["150"]]), "{result}");
}
+80
Переглянути файл
@@ -0,0 +1,80 @@
//! `events.schedule` (API 1.21): one-shot timers a plugin sets for itself, fired in the
//! window that set them, replaced by id, cancelled, and dropped with the window.
use ide_host::plugins::{Consent, PluginHost};
use ide_plugin::{Invocation, Limits};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
const ID: &str = "timers";
fn fixture() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/timers")
}
struct Setup {
_tmp: tempfile::TempDir,
host: PluginHost,
}
fn setup() -> Setup {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let host = PluginHost::new(base.join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap();
host.load_all();
host.startup_finished();
host.install_from_dir(&fixture(), &Consent::all()).unwrap();
Setup { _tmp: tmp, host }
}
impl Setup {
fn run(&self, command: &str, arg: &str) -> Result<Option<String>, String> {
let inv = Invocation { client: Some("main".into()), ..Default::default() };
self.host.run_command(ID, command, Some(arg), inv).map_err(|e| e.message)
}
/// Delivers what is due `after` from now, then what the plugin received.
fn fired_after(&self, after: Duration) -> Vec<String> {
self.host.flush_events_at(Instant::now() + after);
assert!(self.host.wait_events(Duration::from_secs(10)));
let stored = self.run("fired", "").unwrap();
stored.map(|s| serde_json::from_str(&s).unwrap()).unwrap_or_default()
}
}
#[test]
fn a_timer_fires_once_when_due_and_the_same_id_replaces_it() {
let s = setup();
s.run("schedule", "retry 300").unwrap();
s.run("schedule", "later 300").unwrap();
s.run("schedule", "later 60000").unwrap();
assert!(s.fired_after(Duration::ZERO).is_empty(), "nothing is due yet");
assert_eq!(s.fired_after(Duration::from_secs(2)), ["retry"]);
assert_eq!(s.fired_after(Duration::from_secs(2)), ["retry"], "a timer fires once");
assert_eq!(s.fired_after(Duration::from_secs(61)), ["retry", "later"]);
}
#[test]
fn cancelled_timers_and_those_of_a_closed_window_never_fire() {
let s = setup();
s.run("schedule", "cancelled 300").unwrap();
s.run("cancel", "cancelled").unwrap();
s.run("cancel", "unknown").unwrap();
s.run("schedule", "closed 300").unwrap();
s.host.forget_client("main");
s.host.reopen_client("main");
assert!(s.fired_after(Duration::from_secs(2)).is_empty());
}
#[test]
fn schedule_checks_its_bounds() {
let s = setup();
for arg in ["x 249", "x 86400001", " 1000"] {
assert!(s.run("schedule", arg).unwrap_err().contains("timer"), "{arg}");
}
for i in 0..16 {
s.run("schedule", &format!("t{i} 1000")).unwrap();
}
assert!(s.run("schedule", "t16 1000").unwrap_err().contains("at most 16"));
s.run("schedule", "t0 2000").unwrap();
}
+27 -1
Переглянути файл
@@ -91,6 +91,7 @@ async fn ssh_session_opens_a_shell_with_the_saved_password() {
&host,
"main",
"box",
None,
100,
30,
Arc::new(move |s| {
@@ -116,7 +117,7 @@ async fn ssh_session_opens_a_shell_with_the_saved_password() {
assert!(!host.terminals.contains(info.id));
// Closing the tab hangs up a running shell.
let info = ide_host::ops::term::spawn_ssh(&host, "main", "box", 80, 24, Arc::new(|_| {})).await.unwrap();
let info = ide_host::ops::term::spawn_ssh(&host, "main", "box", None, 80, 24, Arc::new(|_| {})).await.unwrap();
host.terminals.kill(info.id).unwrap();
let code = loop {
match events.recv_timeout(Duration::from_secs(10)).expect("exit event") {
@@ -128,6 +129,31 @@ async fn ssh_session_opens_a_shell_with_the_saved_password() {
host.shutdown().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn ssh_session_in_a_directory_starts_the_login_shell_there() {
let tmp = tempfile::tempdir().unwrap();
let (host, _events) = host_with_ssh_box(tmp.path(), Arc::new(|cmd| (format!("ran: {cmd}\n"), 0))).await;
let (tx, output) = mpsc::channel();
let tx = Mutex::new(tx);
ide_host::ops::term::spawn_ssh(
&host,
"main",
"box",
Some("~/my app's"),
80,
24,
Arc::new(move |s| {
let _ = tx.lock().unwrap().send(s);
}),
)
.await
.unwrap();
// The server answers the PTY request ("pty 80x24") first, in its own packet on Linux.
let out = read_until(&output, "-l\n");
assert!(out.contains(r#"ran: cd -- ~/'my app'\''s'; exec "${SHELL:-/bin/sh}" -l"#), "{out:?}");
host.shutdown().await;
}
/// Reads what a connection to the local end of a Docker tunnel gets back.
async fn dial(port: u16) -> std::io::Result<String> {
use tokio::io::AsyncReadExt;
+92 -5
Переглянути файл
@@ -1306,7 +1306,7 @@ async fn incoming_wc_info_branch_layout_compare_switch_and_restricted_mode() {
assert!(incoming[0].time_ms > 0.0);
// 2. svn_working_copy_info returns info for all SVN roots in the project.
let infos = svn::svn_working_copy_info(&host, "main", None).await.unwrap();
let infos = svn::svn_working_copy_info(&host, "main", ide_core::RequestId::next(), None).await.unwrap();
assert_eq!(infos.len(), 1);
assert_eq!(infos[0].url, trunk_url);
assert_eq!(infos[0].repository_root, fx.url);
@@ -1347,7 +1347,10 @@ async fn incoming_wc_info_branch_layout_compare_switch_and_restricted_mode() {
.await
.unwrap();
assert!(reached.is_some());
assert_eq!(svn::svn_working_copy_info(&host, "main", None).await.unwrap()[0].url, feat_url);
assert_eq!(
svn::svn_working_copy_info(&host, "main", ide_core::RequestId::next(), None).await.unwrap()[0].url,
feat_url
);
std::fs::write(wc1.join("branch.txt"), "branch\n").unwrap();
fx.svn(&wc1, &["add", "-q", "branch.txt"]);
@@ -1390,7 +1393,7 @@ async fn incoming_wc_info_branch_layout_compare_switch_and_restricted_mode() {
)
.await
.unwrap();
let all_infos = svn::svn_working_copy_info(&host, "main", None).await.unwrap();
let all_infos = svn::svn_working_copy_info(&host, "main", ide_core::RequestId::next(), None).await.unwrap();
assert!(
all_infos.iter().any(|i| i.root == sub_dir.display().to_string() && i.is_switched),
"expected switched descendant in wc info: {all_infos:?}"
@@ -1402,7 +1405,7 @@ async fn incoming_wc_info_branch_layout_compare_switch_and_restricted_mode() {
untrusted_host.open_project("restricted", &untrusted_wc).unwrap();
for err in [
svn::svn_incoming(&untrusted_host, "restricted", ide_core::RequestId::next(), None).await.unwrap_err(),
svn::svn_working_copy_info(&untrusted_host, "restricted", None).await.unwrap_err(),
svn::svn_working_copy_info(&untrusted_host, "restricted", ide_core::RequestId::next(), None).await.unwrap_err(),
svn::svn_branch_layout(&untrusted_host, "restricted", ide_core::RequestId::next(), None).await.unwrap_err(),
svn::svn_compare_with_url(&untrusted_host, "restricted", ide_core::RequestId::next(), None, trunk_url, None)
.await
@@ -1419,6 +1422,29 @@ async fn incoming_wc_info_branch_layout_compare_switch_and_restricted_mode() {
)
.await
.unwrap_err(),
// The Subversion tool window's commands (review of #8212, M11).
svn::svn_incoming_revisions(&untrusted_host, "restricted", ide_core::RequestId::next(), true)
.await
.unwrap_err(),
svn::svn_revisions_between(
&untrusted_host,
"restricted",
ide_core::RequestId::next(),
untrusted_wc.clone(),
1,
2,
)
.await
.unwrap_err(),
svn::svn_upgrade(
&untrusted_host,
"restricted",
ide_core::RequestId::next(),
untrusted_wc.clone(),
"1.8".into(),
)
.await
.unwrap_err(),
] {
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable, "{err:?}");
}
@@ -1690,7 +1716,7 @@ async fn incoming_revisions_of_two_working_copies() {
host.trust.decide(&project_root, true, false).unwrap();
let project = host.open_project("main", &project_root).unwrap();
until("both working copies", || project.backends().len() == 2).await;
let incoming = || svn::svn_incoming_revisions(&host, "main", ide_core::RequestId::next());
let incoming = || svn::svn_incoming_revisions(&host, "main", ide_core::RequestId::next(), false);
let found = incoming().await.unwrap();
assert!(found.errors.is_empty(), "{:?}", found.errors);
for name in ["boot", "antd"] {
@@ -1712,3 +1738,64 @@ async fn incoming_revisions_of_two_working_copies() {
let antd = project_root.join("antd").display().to_string();
assert_eq!(roots, [(antd.clone(), 4), (antd, 3)]);
}
/// Review of #8212, H5: Incoming reads under the project's requests, so taking the project's
/// trust back stops an svn still waiting on the server.
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn restricted_mode_stops_an_incoming_read() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
let real = which("svn").unwrap();
let started = fx.base.join("started");
// `svn status -u` (Incoming's server read) hangs; everything else is the real svn.
let svn = script(
&fx.base,
"slow-svn",
&format!(
"#!/bin/sh\ncase \"$*\" in *status*-u*) touch '{}'; exec sleep 60;; esac\nexec '{}' \"$@\"\n",
started.display(),
real.display()
),
);
std::fs::create_dir(root.join(".openidea")).unwrap();
std::fs::write(
root.join(".openidea/settings.toml"),
format!("[vcs.svn]\nexecutable = {:?}\n", svn.to_string_lossy()),
)
.unwrap();
let (host, _project) = open(&fx.base, &root).await;
let host = Arc::new(host);
let read = tokio::spawn({
let host = host.clone();
async move { svn::svn_incoming_revisions(&host, "main", ide_core::RequestId::next(), true).await }
});
until("svn status -u", || started.exists()).await;
let at = std::time::Instant::now();
host.set_project_trust(&root, false, false).await.unwrap();
let result = tokio::time::timeout(Duration::from_secs(20), read).await.expect("the read stopped").unwrap();
assert!(at.elapsed() < Duration::from_secs(20));
assert!(result.is_err(), "{result:?}");
}
/// Review of #8212, H1: a project inside a larger checkout cannot change the checkout's format.
#[tokio::test]
async fn a_project_inside_a_checkout_cannot_change_its_format() {
let Some(fx) = fixture() else { return };
let outer = fx.checkout("outer");
std::fs::create_dir(outer.join("sub")).unwrap();
std::fs::write(outer.join("sub/x.txt"), "x\n").unwrap();
fx.svn(&outer, &["add", "-q", "sub"]);
fx.svn(&outer, &["commit", "-q", "-m", "add a folder"]);
let sub = outer.join("sub");
let (host, _project) = open(&fx.base, &sub).await;
let infos =
svn::svn_working_copy_info(&host, "main", ide_core::RequestId::next(), Some(sub.clone())).await.unwrap();
let newest = infos[0].formats.last().cloned().expect("the formats this svn writes");
// `.svn/wc.db`'s SQLite user version: the format (no `svn info --show-item wc-format` before 1.10).
let format = || std::fs::read(outer.join(".svn/wc.db")).unwrap()[60..64].to_vec();
let before = format();
let err = svn::svn_upgrade(&host, "main", ide_core::RequestId::next(), sub, newest).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput, "{err:?}");
assert_eq!(format(), before);
}
+4 -5
Переглянути файл
@@ -342,11 +342,10 @@ async fn a_server_edit_may_version_files_the_editor_never_opened() {
ops::lsp::lsp_execute_command(&host, "main", info.id, command)
};
// A created file takes the system line separator (CRLF on Windows).
let read = |name: &str| std::fs::read_to_string(root.join(name)).unwrap().replace("\r\n", "\n");
run("gopls.add_test", json!({})).await.unwrap();
assert_eq!(
std::fs::read_to_string(root.join("add_test.go")).unwrap(),
"package x_test\n\nimport \"testing\"\n\nfunc TestAdd(t *testing.T) {}\n"
);
assert_eq!(read("add_test.go"), "package x_test\n\nimport \"testing\"\n\nfunc TestAdd(t *testing.T) {}\n");
// The open file must still be at the version the server names: an edit made before the
// user typed is refused.
@@ -371,6 +370,6 @@ async fn a_server_edit_may_version_files_the_editor_never_opened() {
ops::doc::doc_snapshot(&host, "main", info.id).await.unwrap().text,
"package x\n\n// Add returns the sum.\nfunc Add(a, b int) int { return a + b }\n\n// more\n"
);
assert_eq!(std::fs::read_to_string(root.join("two.go")).unwrap(), "package x\n\nfunc Two() int { return 2 }\n");
assert_eq!(read("two.go"), "package x\n\nfunc Two() int { return 2 }\n");
accept.abort();
}
+130 -4
Переглянути файл
@@ -3465,7 +3465,13 @@ fn official_license_header_reports_fixes_and_scans() {
#[test]
fn official_mybatis_navigates_between_interface_and_xml() {
let f = fixture(Limits::default());
assert!(f.host.line_marker_languages_with("java").is_empty());
f.install(&official("mybatis"));
// One plugin's two declarations: a saved Kotlin file can change the XML's markers too.
let mut languages = f.host.line_marker_languages_with("kotlin");
languages.sort();
assert_eq!(languages, ["java", "kotlin", "xml"]);
assert!(f.host.line_marker_languages_with("markdown").is_empty());
let java_path = f.project.join("src/main/java/com/acme/UserMapper.java");
let xml_path = f.project.join("src/main/resources/mapper/UserMapper.xml");
std::fs::create_dir_all(java_path.parent().unwrap()).unwrap();
@@ -3493,7 +3499,7 @@ fn official_mybatis_navigates_between_interface_and_xml() {
// skipped. The editor asks again; so does this.
let deadline = Instant::now() + Duration::from_secs(10);
let markers = loop {
let markers = f.host.provide_line_markers(&jdoc);
let markers = f.host.provide_line_markers(&jdoc).0;
if !markers.is_empty() || Instant::now() > deadline {
break markers;
}
@@ -3524,7 +3530,7 @@ fn official_mybatis_navigates_between_interface_and_xml() {
let mut times = Vec::new();
for _ in 0..20 {
let started = Instant::now();
assert_eq!(f.host.provide_line_markers(&jdoc).len(), 1);
assert_eq!(f.host.provide_line_markers(&jdoc).0.len(), 1);
times.push(started.elapsed());
}
times.sort();
@@ -6575,8 +6581,8 @@ fn marker_providers_preserve_names_and_package_paths() {
version: 1,
text: "marker-icons\nordinary\ncustom\nlegacy".into(),
};
assert!(eventually(|| f.host.provide_line_markers(&doc).len() == 4));
let markers = f.host.provide_line_markers(&doc);
assert!(eventually(|| f.host.provide_line_markers(&doc).0.len() == 4));
let markers = f.host.provide_line_markers(&doc).0;
assert_eq!(
markers.iter().map(|(_, m)| m.icon.as_deref().unwrap()).collect::<Vec<_>>(),
["run", "database", "icons/very-long-resource-marker-icon.svg", "overriding"]
@@ -8826,3 +8832,123 @@ fn custom_editor_toolbar_installs_and_validates_manifest() {
.contains("[[contributes.commands]]")
);
}
/// `misbehave` as `id`, a `line-markers` provider for `text`; with `spin`, also its `spin`
/// command, which keeps its instance busy until cancelled.
fn install_marker_provider(f: &Fixture, tmp: &Path, id: &str, spin: bool) {
let pkg = tmp.join(id);
copy_dir(&misbehave_pkg(), &pkg);
let command = if spin { "[[contributes.commands]]\nid = \"spin\"\ntitle = \"spin\"\n" } else { "" };
std::fs::write(
pkg.join("plugin.toml"),
format!(
"id = \"{id}\"\nname = \"{id}\"\nversion = \"0.0.1\"\nengines.openidea = \"^1.0\"\n\
wasm = \"dist/plugin.wasm\"\nactivation = [\"on-language:text\"]\n{command}\
[[contributes.providers]]\nkinds = [\"line-markers\"]\nlanguages = [\"text\"]\n"
),
)
.unwrap();
f.install(&pkg);
}
fn markers_doc(f: &Fixture) -> ide_plugin::ProviderDocument {
ide_plugin::ProviderDocument {
path: f.project.join("markers.txt"),
language: "text".into(),
version: 1,
text: "marker-icons\nordinary\ncustom\nlegacy".into(),
}
}
/// A call dropped by the edit-path budget is reported by plugin, not answered as "no markers";
/// a disabled plugin is not asked, so it is not reported.
#[test]
fn line_markers_report_the_plugins_too_late_to_answer() {
let f = fixture(Limits { edit_soft: Duration::ZERO, ..Limits::default() });
let tmp = tempfile::tempdir().unwrap();
install_marker_provider(&f, tmp.path(), "late-a", false);
install_marker_provider(&f, tmp.path(), "late-b", false);
let (markers, mut late) = f.host.provide_line_markers(&markers_doc(&f));
late.sort();
assert!(markers.is_empty());
assert_eq!(late, ["late-a", "late-b"]);
f.host.set_enabled("late-a", false).unwrap();
assert_eq!(f.host.provide_line_markers(&markers_doc(&f)), (Vec::new(), vec!["late-b".to_owned()]));
}
/// A call queued behind a busy instance past the budget is reported as late; the plugins that
/// answered in time keep their markers.
#[test]
fn line_markers_too_late_from_one_provider_keep_the_others() {
// A budget no runner misses, so only the call queued behind `spin` is late.
let f = fixture(Limits {
edit_soft: Duration::from_secs(1),
edit_hard: Duration::from_secs(30),
timeout: Duration::from_secs(60),
fuel: u64::MAX,
..Limits::default()
});
let tmp = tempfile::tempdir().unwrap();
install_marker_provider(&f, tmp.path(), "busy", true);
install_marker_provider(&f, tmp.path(), "on-time", false);
let doc = markers_doc(&f);
assert!(eventually(|| f.host.provide_line_markers(&doc).0.len() == 8));
std::thread::scope(|scope| {
scope.spawn(|| f.run("busy", "spin", None));
// Answered in time until `spin` runs; late from then on.
let mut answer = (Vec::new(), Vec::new());
let late_seen = eventually(|| {
answer = f.host.provide_line_markers(&doc);
!answer.1.is_empty()
});
f.host.cancel("busy");
assert!(late_seen, "never late: {answer:?}");
let (markers, late) = answer;
assert_eq!(late, ["busy"]);
assert_eq!(markers.len(), 4);
assert!(markers.iter().all(|(id, _)| id == "on-time"));
});
}
/// A disabled plugin's languages don't make a save ask for line markers again.
#[test]
fn line_marker_languages_leave_out_disabled_plugins() {
let f = fixture(Limits::default());
f.install(&official("mybatis"));
assert_eq!(f.host.line_marker_languages_with("xml").len(), 3);
f.host.set_enabled("openidea.mybatis", false).unwrap();
assert!(f.host.line_marker_languages_with("xml").is_empty());
}
/// Another plugin's languages don't count: only one plugin declaring both links two files.
#[test]
fn line_marker_languages_come_from_the_plugins_covering_the_saved_language() {
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
let install = |id: &str, languages: &str| {
let pkg = tmp.path().join(id);
copy_dir(&misbehave_pkg(), &pkg);
std::fs::write(
pkg.join("plugin.toml"),
format!(
"id = \"{id}\"\nname = \"{id}\"\nversion = \"0.0.1\"\nengines.openidea = \"^1.0\"\n\
wasm = \"dist/plugin.wasm\"\nactivation = [\"on-language:text\"]\n\
[[contributes.providers]]\nkinds = [\"line-markers\"]\nlanguages = {languages}\n"
),
)
.unwrap();
f.install(&pkg);
};
install("text-markers", r#"["text"]"#);
install("md-markers", r#"["markdown"]"#);
// Another plugin's languages don't come along.
assert_eq!(f.host.line_marker_languages_with("text"), ["text"]);
assert_eq!(f.host.line_marker_languages_with("markdown"), ["markdown"]);
assert!(f.host.line_marker_languages_with("java").is_empty());
install("any-markers", r#"["*"]"#);
// `any-markers` covers every language, so every save reaches its editors.
let mut languages = f.host.line_marker_languages_with("text");
languages.sort();
assert_eq!(languages, ["*", "text"]);
assert_eq!(f.host.line_marker_languages_with("java"), ["*"]);
}
+48 -3
Переглянути файл
@@ -174,9 +174,9 @@ pub async fn check_connection(proxy: &ProxySettings, url: &str, cancel: &Cancell
Ok(format!("{} {}", status.as_u16(), status.canonical_reason().unwrap_or("")).trim_end().to_owned())
}
/// reqwest errors with their causes ("error sending request: … connection refused").
pub fn describe(e: &reqwest::Error) -> String {
use std::error::Error;
/// An error with its causes ("error sending request: … connection refused"), so
/// messages surfaced to the user keep the step that actually failed.
pub fn describe(e: &(dyn std::error::Error + 'static)) -> String {
let mut msg = e.to_string();
let mut source = e.source();
while let Some(s) = source {
@@ -194,6 +194,51 @@ pub fn describe(e: &reqwest::Error) -> String {
mod tests {
use super::*;
/// The updater wraps reqwest in its own error type (`tauri-plugin-updater`'s
/// `#[error(transparent)]` variant), so `describe` must follow `source` through
/// any error, not just `reqwest::Error`.
#[derive(Debug)]
struct ConnectRefused;
impl std::fmt::Display for ConnectRefused {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "tcp connect error: connection refused 127.0.0.1:55134")
}
}
impl std::error::Error for ConnectRefused {}
#[derive(Debug)]
struct WrappedRequest {
source: ConnectRefused,
}
impl std::fmt::Display for WrappedRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"error sending request for url (https://cnb.cool/l0ng-ai/openidea/-/releases/latest/download/latest.json)"
)
}
}
impl std::error::Error for WrappedRequest {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.source)
}
}
#[test]
fn describe_keeps_the_causes_behind_a_wrapped_error() {
let error = WrappedRequest { source: ConnectRefused };
assert_eq!(
describe(&error),
"error sending request for url (https://cnb.cool/l0ng-ai/openidea/-/releases/latest/download/latest.json): \
tcp connect error: connection refused 127.0.0.1:55134"
);
}
#[test]
fn describe_of_an_error_without_causes_is_unchanged() {
assert_eq!(describe(&ConnectRefused), "tcp connect error: connection refused 127.0.0.1:55134");
}
#[test]
fn auto_mode_rebuilds_the_shared_client_when_the_system_proxy_changes() {
static SYSTEM: Mutex<String> = Mutex::new(String::new());
+27 -14
Переглянути файл
@@ -186,7 +186,8 @@ impl SyntaxCache {
stats
}
pub fn outline(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> Vec<OutlineItem> {
/// The memoized outline, shared: a cache hit clones none of its `String`s.
pub fn outline(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> Arc<Vec<OutlineItem>> {
self.memoized(
doc,
lang,
@@ -211,7 +212,8 @@ impl SyntaxCache {
)
}
pub fn folding(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> Vec<FoldRange> {
/// The memoized folding ranges, shared like [`Self::outline`].
pub fn folding(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> Arc<Vec<FoldRange>> {
self.memoized(
doc,
lang,
@@ -230,7 +232,7 @@ impl SyntaxCache {
/// Highlighting from the grammar's own query; empty without one.
pub fn highlights(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> SyntaxHighlights {
SyntaxHighlights::new(self.memoized(
SyntaxHighlights::new(Arc::unwrap_or_clone(self.memoized(
doc,
lang,
version,
@@ -241,10 +243,12 @@ impl SyntaxCache {
})
.or_else(|| super::external::highlights(lang, text))
},
))
)))
}
/// `compute()` once per document version; `None` (no grammar / query) is not memoized.
/// Returns the `Arc` the memo holds; a caller that must own the result uses
/// `Arc::unwrap_or_clone`.
fn memoized<T: Clone>(
&self,
doc: DocId,
@@ -252,7 +256,7 @@ impl SyntaxCache {
version: u32,
slot: impl Fn(&mut Memo) -> &mut Option<Arc<Vec<T>>>,
compute: impl FnOnce() -> Option<Vec<T>>,
) -> Vec<T> {
) -> Arc<Vec<T>> {
let entry = self.entries.lock().get(&doc).cloned();
if let Some(e) = &entry {
let mut e = e.lock();
@@ -260,10 +264,11 @@ impl SyntaxCache {
&& let Some(hit) = slot(&mut e.memo).clone()
{
self.hits.fetch_add(1, Ordering::Relaxed);
return (*hit).clone();
return hit;
}
}
let Some(result) = compute() else { return Vec::new() };
let Some(result) = compute() else { return Arc::new(Vec::new()) };
let result = Arc::new(result);
if let Some(e) = &entry {
let mut e = e.lock();
// Containers without their own grammar memoize their web outline too.
@@ -271,7 +276,7 @@ impl SyntaxCache {
if e.version == version
&& (e.tree.is_some() || (e.lang == *lang && self.syntax.web_grammar_name(lang) == Some("html")))
{
*slot(e.memo.at(version, lang)) = Some(Arc::new(result.clone()));
*slot(e.memo.at(version, lang)) = Some(result.clone());
}
}
result
@@ -426,7 +431,7 @@ mod tests {
let mut doc = Document::new(SRC);
cache.open(id, &rust(), doc.version());
let first = cache.outline(id, &rust(), 0, &doc.text());
assert_eq!(first, cache.syntax().outline(&rust(), SRC));
assert_eq!(first.as_ref(), &cache.syntax().outline(&rust(), SRC));
assert_eq!(cache.stats().full_parses, 1);
cache.folding(id, &rust(), 0, &doc.text());
assert_eq!(cache.stats().hits, 1);
@@ -444,8 +449,16 @@ mod tests {
cache.edit(id, doc.version(), &edits);
let text = doc.text();
let v = doc.version();
assert_eq!(cache.outline(id, &rust(), v, &text), cache.syntax().outline(&rust(), &text), "round {round}");
assert_eq!(cache.folding(id, &rust(), v, &text), cache.syntax().folding(&rust(), &text), "round {round}");
assert_eq!(
cache.outline(id, &rust(), v, &text).as_ref(),
&cache.syntax().outline(&rust(), &text),
"round {round}"
);
assert_eq!(
cache.folding(id, &rust(), v, &text).as_ref(),
&cache.syntax().folding(&rust(), &text),
"round {round}"
);
let off = seed % (doc.len_utf16() + 1);
assert_eq!(
cache.selection_ranges(id, &rust(), v, &text, off),
@@ -481,7 +494,7 @@ mod tests {
cache.edit(id, doc.version(), &edits);
let text = doc.text();
let edited = cache.outline(id, &rust(), 1, &text);
assert_eq!(edited, cache.syntax().outline(&rust(), &text));
assert_eq!(edited.as_ref(), &cache.syntax().outline(&rust(), &text));
assert_ne!(edited, outline);
// Another language at the same version is not answered from the memo.
assert!(cache.outline(id, &LanguageId::new("plaintext"), 1, &text).is_empty());
@@ -504,7 +517,7 @@ mod tests {
cache.edit(id, doc.version(), &edits);
let second = cache.outline(id, &lang, doc.version(), &doc.text());
assert_ne!(second, first);
assert_eq!(second, cache.syntax().outline(&lang, &doc.text()));
assert_eq!(second.as_ref(), &cache.syntax().outline(&lang, &doc.text()));
// An older query must not replace the current version's memo.
cache.outline(id, &lang, 0, "<script>const old = 0;</script>");
let hits = cache.stats().hits;
@@ -528,7 +541,7 @@ mod tests {
let edits = edit(&mut doc, 0, 0, "// y\n");
cache.edit(id, doc.version(), &edits);
let text = doc.text();
assert_eq!(cache.outline(id, &rust(), 2, &text), cache.syntax().outline(&rust(), &text));
assert_eq!(cache.outline(id, &rust(), 2, &text).as_ref(), &cache.syntax().outline(&rust(), &text));
assert_eq!(cache.stats().full_parses, 2, "dropped tree re-parses from scratch");
// A query for a version the cache has not reached is answered but not stored.
+4 -4
Переглянути файл
@@ -2033,9 +2033,9 @@ fn cached_outline_matches_syntax_outline_for_web_documents() {
let id = DocId::next();
let src = "<template><div/></template>\n<script lang=\"ts\">\nconst app = 1;\n</script>\n";
cache.open(id, &lang("vue"), 0);
assert_eq!(cache.outline(id, &lang("vue"), 0, src), syntax().outline(&lang("vue"), src));
assert_eq!(cache.outline(id, &lang("vue"), 0, src).as_ref(), &syntax().outline(&lang("vue"), src));
cache.open(id, &lang("html"), 0);
assert_eq!(cache.outline(id, &lang("html"), 0, src), syntax().outline(&lang("html"), src));
assert_eq!(cache.outline(id, &lang("html"), 0, src).as_ref(), &syntax().outline(&lang("html"), src));
}
#[test]
@@ -2137,7 +2137,7 @@ fn outline_restructuredtext_unicode_crlf_and_cached_edits() {
let cache = SyntaxCache::new(Arc::new(Syntax::new()));
cache.open(id, &language, 0);
let items = cache.outline(id, &language, 0, src);
assert_eq!(items, syntax().outline(&language, src));
assert_eq!(items.as_ref(), &syntax().outline(&language, src));
assert_eq!(items[0].name, "中文😀");
assert_eq!(items[0].selection_range, Range::new(Pos::new(1, 1), Pos::new(1, 5)));
assert_eq!(items[0].children[0].name, "子章节");
@@ -2146,7 +2146,7 @@ fn outline_restructuredtext_unicode_crlf_and_cached_edits() {
assert_eq!(items[0].children[1].name, "Other");
let edited = src.replace("子章节", "新章节😀");
let updated = cache.outline(id, &language, 1, &edited);
assert_eq!(updated, syntax().outline(&language, &edited));
assert_eq!(updated.as_ref(), &syntax().outline(&language, &edited));
assert_eq!(updated[0].children[0].selection_range.end, Pos::new(4, 5));
assert_ne!(items, updated);
}
+7 -2
Переглянути файл
@@ -168,8 +168,13 @@ pub fn client_capabilities() -> Value {
"typeHierarchy": { "dynamicRegistration": false }
},
// rust-analyzer: report when the project has loaded (`quiescent`).
// java-analyzer: Spring bean markers of open documents may have changed (`spring_beans.rs`).
"experimental": { "serverStatusNotification": true, "java-analyzer/springBeanMarkersChanged": true },
// java-analyzer: Spring bean and AOP markers of open documents may have changed
// (`spring_beans.rs`, `spring_aop.rs`).
"experimental": {
"serverStatusNotification": true,
"java-analyzer/springBeanMarkersChanged": true,
"java-analyzer/springAopMarkersChanged": true
},
// Jupyter notebooks: code cells are synced with `notebookDocument/*` (see `notebook.rs`).
"notebookDocument": { "synchronization": { "dynamicRegistration": false, "executionSummarySupport": false } }
})
+3
Переглянути файл
@@ -783,6 +783,9 @@ impl Handler for ClientHandler {
crate::spring_beans::CHANGED if self.server.is_live(self.generation) => {
mgr.sink().emit(IdeEvent::LspRefresh { server: self.server.id, kind: LspRefreshKind::SpringBeanMarkers })
}
crate::spring_aop::CHANGED if self.server.is_live(self.generation) => {
mgr.sink().emit(IdeEvent::LspRefresh { server: self.server.id, kind: LspRefreshKind::SpringAopMarkers })
}
"window/showMessage" => self.show_message(&mgr, &params),
"window/logMessage" => {
let text = params.get("message").and_then(Value::as_str).unwrap_or_default();
+2
Переглянути файл
@@ -137,6 +137,7 @@ fn java_result_of(
JavaSeverity::Warning => ProblemSeverity::Warning,
},
message: p.message,
location: None,
})
.collect();
// java-analyzer is stateless: no confirmation token, the client applies what it got.
@@ -271,6 +272,7 @@ impl LspManager {
problems: vec![RefactoringProblem {
severity: ProblemSeverity::Fatal,
message: "The interface could not be extracted".to_owned(),
location: None,
}],
edit: None,
confirmation: None,
+24 -6
Переглянути файл
@@ -3,7 +3,9 @@
//! server advertises them (`crate::phoxite`). The server checks the move and computes the edit; the UI
//! shows its problems and applies the edit itself.
use super::COMMAND_TIMEOUT;
use crate::types::{HierarchyChoice, HierarchyMembers, HierarchyRefactored, HierarchyRefactoring, RefactoringProblem};
use crate::types::{
HierarchyChoice, HierarchyMembers, HierarchyRefactored, HierarchyRefactoring, ProblemSeverity, RefactoringProblem,
};
use crate::{DocSnap, LspManager, Target, convert};
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Pos};
use serde::Deserialize;
@@ -29,10 +31,20 @@ fn java_analyzer(caps: &crate::caps::ServerCaps, kind: HierarchyRefactoring) ->
#[derive(Default, Deserialize)]
struct JavaRefactored {
#[serde(default)]
problems: Vec<RefactoringProblem>,
problems: Vec<JavaProblem>,
edit: Option<lsp_types::WorkspaceEdit>,
}
/// java-analyzer's problem shape: the location is an LSP location, converted to IDE
/// coordinates like the edit is.
#[derive(Deserialize)]
struct JavaProblem {
severity: ProblemSeverity,
message: String,
#[serde(default)]
location: Option<lsp_types::Location>,
}
/// The extension's answer: a result, or why the position can't be refactored.
#[derive(Deserialize)]
#[serde(untagged)]
@@ -187,9 +199,15 @@ impl LspManager {
}
let answer = answer.unwrap_or_default();
let conv = self.conv(target.enc());
Ok(HierarchyRefactored {
problems: answer.problems,
edit: answer.edit.map(|edit| convert::workspace_edit(&conv, edit)),
})
let problems = answer
.problems
.into_iter()
.map(|problem| RefactoringProblem {
severity: problem.severity,
message: problem.message,
location: problem.location.as_ref().and_then(|loc| conv.location(loc)),
})
.collect();
Ok(HierarchyRefactored { problems, edit: answer.edit.map(|edit| convert::workspace_edit(&conv, edit)) })
}
}
+94 -3
Переглянути файл
@@ -6,12 +6,38 @@
//! arguments back unchanged.
use super::COMMAND_TIMEOUT;
use super::signature::{RefactorEdit, changed};
use crate::types::ServerRefactored;
use crate::{LspManager, convert};
use ide_core::{CancellationToken, DocId, IdeError, IdeResult};
use crate::caps::ServerCaps;
use crate::types::{MoveChoice, MoveInfo, ProblemSeverity, RefactoringProblem, ServerRefactored};
use crate::{DocSnap, LspManager, Target, convert};
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Pos};
use serde::Deserialize;
use serde_json::{Value, json};
const FEATURE: &str = "Move";
/// java-analyzer's dialog-driven Move pair, advertised in `capabilities.experimental`.
const JAVA_INFO: &str = "java-analyzer/moveInfo";
const JAVA_EDIT: &str = "java-analyzer/move";
fn java_analyzer(caps: &ServerCaps) -> bool {
caps.raw["experimental"][JAVA_INFO] == true && caps.raw["experimental"][JAVA_EDIT] == true
}
#[derive(Default, Deserialize)]
struct JavaMoveResult {
#[serde(default)]
problems: Vec<JavaProblem>,
edit: Option<lsp_types::WorkspaceEdit>,
}
/// java-analyzer's problem shape: the location is an LSP location, converted to the
/// IDE's coordinates like the edit is.
#[derive(Deserialize)]
struct JavaProblem {
severity: ProblemSeverity,
message: String,
#[serde(default)]
location: Option<lsp_types::Location>,
}
/// What `java/getMoveDestinations` and `java/move` accept as `moveKind`.
const KINDS: [&str; 6] =
["moveResource", "moveInstanceMethod", "moveStaticMember", "moveTypeToNewFile", "moveTypeToClass", "moveType"];
@@ -95,6 +121,71 @@ impl LspManager {
}
}
impl LspManager {
async fn java_move_target(&self, doc: DocId) -> IdeResult<(DocSnap, Target)> {
let (snap, targets) = self.doc_targets(doc, FEATURE, |_| true).await?;
if let Some(t) = targets.iter().find(|t| java_analyzer(&t.caps())) {
return Ok((snap, t.clone()));
}
if targets.iter().any(|t| t.server.name == "java-analyzer") {
return Err(IdeError::unavailable(
"java-analyzer doesn't support Move; use the file tree's Move or the jdtls Move actions",
));
}
Err(IdeError::unavailable(format!("{FEATURE} needs a Java language server")))
}
/// What can move at `pos` and where it can go (java-analyzer's `moveInfo`).
pub async fn java_move_info(&self, doc: DocId, pos: Pos, cancel: CancellationToken) -> IdeResult<MoveInfo> {
let (snap, t) = self.java_move_target(doc).await?;
let params = json!({
"textDocument": { "uri": snap.uri },
"position": snap.position(&t, pos),
});
let info: Option<MoveInfo> = self.call(&t, JAVA_INFO, params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
info.ok_or_else(|| IdeError::invalid("There is nothing movable at the caret"))
}
/// Checks the chosen move and computes its edit (java-analyzer's `move`).
pub async fn java_move_refactor(
&self,
doc: DocId,
pos: Pos,
destination: MoveChoice,
cancel: CancellationToken,
) -> IdeResult<ServerRefactored> {
let (snap, t) = self.java_move_target(doc).await?;
let params = json!({
"textDocument": { "uri": snap.uri },
"position": snap.position(&t, pos),
"destination": { "kind": destination.kind, "id": destination.id },
});
let answer: Option<JavaMoveResult> = self.call(&t, JAVA_EDIT, params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let answer = answer.unwrap_or_default();
let conv = self.conv(t.enc());
let problems = answer
.problems
.into_iter()
.map(|problem| RefactoringProblem {
severity: problem.severity,
message: problem.message,
location: problem.location.as_ref().and_then(|loc| conv.location(loc)),
})
.collect();
Ok(ServerRefactored {
problems,
edit: answer.edit.map(|edit| convert::workspace_edit(&conv, edit)),
confirmation: None,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
+6 -5
Переглянути файл
@@ -110,6 +110,7 @@ fn java_result_of(
JavaSeverity::Warning => ProblemSeverity::Warning,
},
message: p.message,
location: None,
})
.collect();
// java-analyzer is stateless: no confirmation token, the client applies what it got.
@@ -139,11 +140,11 @@ pub(super) fn changed(
convert_edit: impl FnOnce(lsp_types::WorkspaceEdit) -> ide_core::WorkspaceEdit,
) -> ServerRefactored {
let problem = |severity| {
answer
.error_message
.as_deref()
.filter(|m| !m.trim().is_empty())
.map(|message| RefactoringProblem { severity, message: message.trim().to_owned() })
answer.error_message.as_deref().filter(|m| !m.trim().is_empty()).map(|message| RefactoringProblem {
severity,
message: message.trim().to_owned(),
location: None,
})
};
if let Some(token) = answer.confirmation_token {
return ServerRefactored {
+1
Переглянути файл
@@ -40,6 +40,7 @@ mod roslyn;
mod scope;
mod server;
mod source_actions;
mod spring_aop;
mod spring_beans;
mod switch_source_header;
mod tcp;
+103
Переглянути файл
@@ -0,0 +1,103 @@
//! Spring AOP markers of a Java document: advised methods with the advices applied to them, and
//! advice methods with the methods they advise. The first source is java-analyzer's
//! `java-analyzer/springAopMarkers`, one request per document; its answer is turned into the
//! server-independent [`SpringAopMarker`]s the gutter shows.
use crate::types::{SpringAopAdviceKind, SpringAopDirection, SpringAopMarker, SpringAopTarget};
use crate::{LspManager, Target, lsp};
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Range};
use serde::Deserialize;
use serde_json::json;
use std::time::Duration;
/// `{ textDocument: { uri } }` → `{ markers: [{ range, name, direction, targets: [{ location, label, adviceKind, order }] }] }`.
pub(crate) const METHOD: &str = "java-analyzer/springAopMarkers";
/// Sent by the server, to clients that declare it, when markers of open documents may have changed.
pub(crate) const CHANGED: &str = "java-analyzer/springAopMarkersChanged";
/// The first answer of a large workspace pairs every advised method with its advices.
const TIMEOUT: Duration = Duration::from_secs(60);
#[derive(Deserialize)]
struct Answer {
markers: Vec<WireMarker>,
}
#[derive(Deserialize)]
struct WireMarker {
range: lsp::Range,
name: String,
direction: SpringAopDirection,
targets: Vec<WireTarget>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct WireTarget {
location: lsp::Location,
label: String,
#[serde(default)]
advice_kind: Option<SpringAopAdviceKind>,
#[serde(default)]
order: Option<i32>,
}
impl LspManager {
/// The document's Spring AOP markers; `None` when no server attached to it provides them
/// (jdtls, an older java-analyzer, a server not running yet), without asking any server.
pub async fn spring_aop_markers(
&self,
doc: DocId,
cancel: CancellationToken,
) -> IdeResult<Option<Vec<SpringAopMarker>>> {
let snap = self.snapshot(doc)?;
// Only an instance the document is open on: waiting for servers to start would hold
// every Java file of a jdtls project for a background feature.
let source = self.docs.lock().get(&doc).and_then(|d| {
d.servers.iter().find_map(|a| {
let run = a.server.running()?;
let provides = {
let caps = run.caps.read();
// AOP markers are implementation navigation: `features` without it leave it out.
caps.restriction.implementation() && caps.raw["experimental"][METHOD] == true
};
(provides && a.opened_gen == Some(run.generation)).then(|| Target::new(a.server.clone(), run))
})
});
let Some(target) = source else { return Ok(None) };
let answer: Option<Answer> =
self.call(&target, METHOD, json!({ "textDocument": snap.ident() }), Some(&cancel), TIMEOUT).await?;
// Ranges are read against the text the request was made for.
if self.snapshot(doc)?.version != snap.version {
return Err(IdeError::cancelled());
}
let enc = target.enc();
let conv = self.conv(enc);
let pos = |p| snap.text.lsp_to_ide(enc, p);
let markers = answer.map_or_else(Vec::new, |a| a.markers);
Ok(Some(
markers
.into_iter()
.filter_map(|m| {
let targets: Vec<_> = m
.targets
.into_iter()
.filter_map(|t| {
Some(SpringAopTarget {
location: conv.location(&t.location)?,
label: t.label,
advice_kind: t.advice_kind,
order: t.order,
})
})
.collect();
(!targets.is_empty()).then(|| SpringAopMarker {
range: Range::new(pos(m.range.start), pos(m.range.end)),
name: m.name,
direction: m.direction,
targets,
})
})
.collect(),
))
}
}
+96
Переглянути файл
@@ -542,6 +542,10 @@ pub enum ProblemSeverity {
pub struct RefactoringProblem {
pub severity: ProblemSeverity,
pub message: String,
/// Where the problem was found, when the server can say.
#[serde(default)]
#[specta(optional)]
pub location: Option<Location>,
}
/// A checked refactoring: what the server found, and the edit unless a problem is fatal.
@@ -552,6 +556,55 @@ pub struct HierarchyRefactored {
pub edit: Option<WorkspaceEdit>,
}
/// The kind of element Move (F6) would move, as java-analyzer reports it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MoveKind {
Type,
StaticMember,
InstanceMethod,
}
/// One destination Move can go to.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MoveDestination {
/// `package`, `class`, `newFile`, `field` or `parameter`.
pub kind: String,
/// Server-owned identity, passed back unchanged.
pub id: String,
pub name: String,
#[serde(default)]
pub qualified_name: String,
#[serde(default)]
pub detail: String,
#[serde(default)]
pub current: bool,
/// For field/parameter destinations: the type of the field or parameter.
#[serde(default)]
pub target_type: String,
#[serde(default)]
pub is_field: bool,
}
/// The element at a position and where Move can take it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MoveInfo {
pub kind: MoveKind,
/// The element being moved, as the server renders it.
pub label: String,
pub destinations: Vec<MoveDestination>,
}
/// A Move destination choice, as the dialog sends it back.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MoveChoice {
pub kind: String,
pub id: String,
}
/// A parameter in Change Signature: its type, name, the value passed at existing calls when it is
/// added, and its index in the current signature (-1 for an added one).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -787,3 +840,46 @@ pub enum SpringBeanResolution {
Resolved,
Candidate,
}
/// A Spring AOP marker on a Java method: an advised method (`ToAdvice`) or an advice
/// method (`ToAdvised`), whichever server found it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SpringAopMarker {
/// The method's name range.
pub range: Range,
pub name: String,
pub direction: SpringAopDirection,
/// Never empty.
pub targets: Vec<SpringAopTarget>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum SpringAopDirection {
/// On an advised method: its targets are the advices applied to it.
ToAdvice,
/// On an advice method: its targets are the methods it advises.
ToAdvised,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SpringAopTarget {
pub location: Location,
pub label: String,
/// Set on an advice target; `None` on an advised method.
pub advice_kind: Option<SpringAopAdviceKind>,
/// The advice's Spring `order`; `None` when it has none.
pub order: Option<i32>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum SpringAopAdviceKind {
Before,
After,
AfterReturning,
AfterThrowing,
Around,
}
+177 -2
Переглянути файл
@@ -7832,7 +7832,11 @@ async fn gopls_interactive_command_validates_before_execution_and_applies_edits(
.await
.unwrap();
assert_eq!(created, vec![new_file.clone()]);
assert_eq!(std::fs::read_to_string(&new_file).unwrap(), "package probe_test\n\nimport \"testing\"\n");
// A created file takes the system line separator (CRLF on Windows).
assert_eq!(
std::fs::read_to_string(&new_file).unwrap().replace("\r\n", "\n"),
"package probe_test\n\nimport \"testing\"\n"
);
}
/// bash-language-server formats a whole file with `Position.create(Number.MAX_VALUE,
@@ -9674,7 +9678,8 @@ async fn a_server_is_sent_the_documents_it_registers_a_selector_for() {
let after = open_data("after.dt");
eventually(|| fw.docs.lock().contains_key(&uri_of(&after))).await;
// Its own server keeps the documents, and one the selector doesn't name stays with it alone.
assert!(own.docs.lock().contains_key(&uri_of(&after)) && own.docs.lock().contains_key(&uri_of(&unrelated)));
eventually(|| own.docs.lock().contains_key(&uri_of(&after)) && own.docs.lock().contains_key(&uri_of(&unrelated)))
.await;
assert!(!fw.docs.lock().contains_key(&uri_of(&unrelated)));
// The server list names the language among the ones it serves.
let served = h.mgr.servers().into_iter().find(|s| s.name == "fw").unwrap().languages;
@@ -10923,3 +10928,173 @@ async fn initialize_sends_active_locale_and_restarts_on_locale_change() {
assert_eq!(state.requested("initialize")[2]["locale"], "zh-TW");
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn move_uses_java_analyzer_when_advertised() {
let mut ja_caps = incremental_caps();
ja_caps["positionEncoding"] = json!("utf-8");
ja_caps["experimental"] = json!({
"java-analyzer/moveInfo": true,
"java-analyzer/move": true,
});
let h = harness_configured("java", "java", &[("java-analyzer", ja_caps), ("jdtls", incremental_caps())], |_| {});
let (doc, path) =
h.open("Dog.java", "package app;\npublic class Dog extends Animal {\n int bark() { return 1; }\n}\n");
for name in ["java-analyzer", "jdtls"] {
h.wait_status(name, ServerStatus::Ready).await;
}
let (ja, jdtls) = (h.launcher.state("java-analyzer"), h.launcher.state("jdtls"));
eventually(|| !ja.notified("textDocument/didOpen").is_empty()).await;
let caret = Pos::new(2, 9);
ja.respond(
"java-analyzer/moveInfo",
json!({
"kind": "instanceMethod",
"label": "app.Dog.bark()",
"destinations": [{
"kind": "parameter", "id": "parameter:target", "name": "target",
"qualifiedName": "app.Target", "targetType": "app.Target", "isField": false,
}],
}),
);
let info = h.mgr.java_move_info(doc, caret, Default::default()).await.unwrap();
assert_eq!(info.label, "app.Dog.bark()");
assert_eq!(info.destinations[0].id, "parameter:target");
assert_eq!(
ja.requested("java-analyzer/moveInfo")[0],
json!({ "textDocument": { "uri": uri_of(&path) }, "position": { "line": 2, "character": 9 } })
);
assert!(jdtls.requested("java/getMoveDestinations").is_empty());
ja.respond(
"java-analyzer/move",
json!({
"edit": { "changes": {
uri_of(&path): [{
"range": { "start": { "line": 2, "character": 0 }, "end": { "line": 2, "character": 0 } },
"newText": "",
}],
} },
"problems": [{ "severity": "warning", "message": "Review this call" }],
}),
);
let res = h
.mgr
.java_move_refactor(
doc,
caret,
MoveChoice { kind: "parameter".to_owned(), id: "parameter:target".to_owned() },
Default::default(),
)
.await
.unwrap();
assert_eq!(res.problems[0].severity, ProblemSeverity::Warning);
assert!(res.edit.is_some());
assert!(res.confirmation.is_none());
assert_eq!(
ja.requested("java-analyzer/move")[0],
json!({
"textDocument": { "uri": uri_of(&path) },
"position": { "line": 2, "character": 9 },
"destination": { "kind": "parameter", "id": "parameter:target" },
})
);
assert!(jdtls.requested("java/move").is_empty());
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn move_without_the_pair_on_java_analyzer_says_so() {
let h = harness_configured("java", "java", &[("java-analyzer", incremental_caps())], |_| {});
let (doc, _) = h.open("Dog.java", "package app;\nclass Dog {\n int bark() { return 1; }\n}\n");
h.wait_status("java-analyzer", ServerStatus::Ready).await;
let err = h.mgr.java_move_info(doc, Pos::new(2, 9), Default::default()).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
assert!(err.message.starts_with("java-analyzer doesn't support Move"), "{}", err.message);
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn spring_aop_markers_come_from_the_server_that_declares_them() {
let mut caps = incremental_caps();
caps["positionEncoding"] = json!("utf-8");
caps["experimental"] = json!({ "java-analyzer/springAopMarkers": true });
let h = harness(&[("aop", caps), ("plain", incremental_caps())]);
// "é😀" is 3 UTF-16 units and 6 bytes before `clock`.
let (doc, path) = h.open("a.mk", "é😀clock;\nclass App {}\n");
for name in ["aop", "plain"] {
h.wait_status(name, ServerStatus::Ready).await;
}
let (aop, plain) = (h.launcher.state("aop"), h.launcher.state("plain"));
eventually(|| !aop.notified("textDocument/didOpen").is_empty()).await;
let init = &aop.requested("initialize")[0];
assert_eq!(init["capabilities"]["experimental"]["java-analyzer/springAopMarkersChanged"], true);
let at = |l: u32, c0: u32, c1: u32| json!({"start":{"line":l,"character":c0},"end":{"line":l,"character":c1}});
aop.respond(
"java-analyzer/springAopMarkers",
json!({ "markers": [
{ "range": at(0, 6, 11), "name": "clock", "direction": "toAdvice", "targets": [
{ "location": { "uri": uri_of(&path), "range": at(1, 6, 9) }, "label": "logBefore", "adviceKind": "before", "order": 1 },
{ "location": { "uri": uri_of(&path), "range": at(0, 0, 2) }, "label": "é", "adviceKind": "around", "order": null },
] },
{ "range": at(1, 6, 9), "name": "App", "direction": "toAdvised", "targets": [
{ "location": { "uri": uri_of(&path), "range": at(0, 3, 8) }, "label": "clock", "adviceKind": null, "order": null },
] },
{ "range": at(1, 0, 3), "name": "App", "direction": "toAdvised", "targets": [] },
] }),
);
let markers = h.mgr.spring_aop_markers(doc, Default::default()).await.unwrap().unwrap();
assert_eq!(aop.requested("java-analyzer/springAopMarkers")[0], json!({ "textDocument": { "uri": uri_of(&path) } }));
assert!(plain.requested("java-analyzer/springAopMarkers").is_empty());
// The marker without targets is dropped; positions are UTF-16 in every file.
assert_eq!(markers.len(), 2);
assert_eq!(markers[0].range, rng(0, 3, 0, 8));
assert_eq!(markers[0].direction, SpringAopDirection::ToAdvice);
assert_eq!(markers[0].targets[0].location.range, rng(1, 6, 1, 9));
assert_eq!(markers[0].targets[0].advice_kind, Some(SpringAopAdviceKind::Before));
assert_eq!(markers[0].targets[0].order, Some(1));
assert_eq!(markers[0].targets[1].location.range, rng(0, 0, 0, 1));
assert_eq!(markers[0].targets[1].advice_kind, Some(SpringAopAdviceKind::Around));
assert_eq!(markers[0].targets[1].order, None);
assert_eq!(markers[1].direction, SpringAopDirection::ToAdvised);
assert_eq!(markers[1].targets[0].advice_kind, None);
assert_eq!(markers[1].targets[0].order, None);
let refreshes = || {
h.events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::SpringAopMarkers, .. }))
.count()
};
aop.peer().notify("java-analyzer/springAopMarkersChanged", json!({})).unwrap();
eventually(|| refreshes() == 1).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn spring_aop_markers_ask_no_server_without_the_capability() {
let h = harness(&[("plain", incremental_caps())]);
let (doc, _) = h.open("a.mk", "class App {}\n");
// Not ready yet: no wait for it to start.
assert_eq!(h.mgr.spring_aop_markers(doc, Default::default()).await.unwrap(), None);
h.wait_status("plain", ServerStatus::Ready).await;
let plain = h.launcher.state("plain");
eventually(|| !plain.notified("textDocument/didOpen").is_empty()).await;
assert_eq!(h.mgr.spring_aop_markers(doc, Default::default()).await.unwrap(), None);
assert!(plain.requested("java-analyzer/springAopMarkers").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn spring_aop_markers_follow_the_servers_features() {
let mut caps = incremental_caps();
caps["experimental"] = json!({ "java-analyzer/springAopMarkers": true });
// Used for diagnostics only: no navigation from it, AOP markers included.
let h = harness_configured("mock", "mk", &[("aop", caps)], |cfg| cfg.features = vec!["diagnostics".into()]);
let (doc, _) = h.open("a.mk", "class App {}\n");
h.wait_status("aop", ServerStatus::Ready).await;
let aop = h.launcher.state("aop");
eventually(|| !aop.notified("textDocument/didOpen").is_empty()).await;
assert_eq!(h.mgr.spring_aop_markers(doc, Default::default()).await.unwrap(), None);
assert!(aop.requested("java-analyzer/springAopMarkers").is_empty());
}
+15
Переглянути файл
@@ -693,6 +693,13 @@ pub trait HostApi: Send + Sync {
Err(HostError::Failed("watching paths is unavailable here".into()))
}
fn unsubscribe(&self, kind: &str);
/// Wakes this plugin with a `timer` event `id` after `after`, in window `client`
/// (API 1.21); replaces a pending timer with the same id. `id` and `after` are checked.
fn schedule(&self, _client: Option<&str>, _id: &str, _after: std::time::Duration) -> Result<(), HostError> {
Err(HostError::Failed("timers are unavailable here".into()))
}
/// Cancels this plugin's pending timer `id`, if any (API 1.21).
fn cancel_schedule(&self, _id: &str) {}
/// Starts `cmd` and returns the handle to it without waiting.
fn start_process(&self, cmd: ProcessCommand, cwd: Option<&Path>, client: Option<&str>) -> Result<u64, HostError>;
/// Starts `cmd` with streaming options (API 1.15).
@@ -1274,7 +1281,15 @@ fn event_to_wit(e: WorkbenchEvent) -> wit_events::Event {
kind: "project-closed".into(),
data: serde_json::to_string(&p).expect("path serializes"),
}),
WorkbenchEvent::ProjectTreeExpanded(paths) => wit_events::Event::Other(wit_types::Extension {
kind: "project-tree-expanded".into(),
data: serde_json::to_string(&paths).expect("paths serialize"),
}),
WorkbenchEvent::Scheduled => wit_events::Event::Scheduled,
WorkbenchEvent::Timer(id) => wit_events::Event::Other(wit_types::Extension {
kind: "timer".into(),
data: serde_json::to_string(&id).expect("id serializes"),
}),
WorkbenchEvent::ActionPerformed(a) => wit_events::Event::ActionPerformed(wit_events::ActionPerformed {
action: a.action,
title: a.title,
+17 -1
Переглянути файл
@@ -239,11 +239,16 @@ pub enum EventKind {
ProjectClosed,
/// Paths outside the project watched with `events.watch-paths` changed (API 1.18).
WatchedFilesChanged,
/// Project tree folders newly expanded, or already expanded when a plugin subscribes (API 1.21):
/// a JSON array of absolute paths (`Event::Other`).
ProjectTreeExpanded,
Scheduled,
/// A timer the plugin set with `events.schedule` fired (API 1.21); delivered without subscribing.
Timer,
}
impl EventKind {
pub const ALL: [Self; 22] = [
pub const ALL: [Self; 24] = [
Self::DocumentChanged,
Self::WebsocketReady,
Self::FileClosed,
@@ -265,7 +270,9 @@ impl EventKind {
Self::ProblemsChanged,
Self::ProjectClosed,
Self::WatchedFilesChanged,
Self::ProjectTreeExpanded,
Self::Scheduled,
Self::Timer,
];
pub fn name(self) -> &'static str {
@@ -291,7 +298,9 @@ impl EventKind {
Self::ProblemsChanged => "problems-changed",
Self::ProjectClosed => "project-closed",
Self::WatchedFilesChanged => "watched-files-changed",
Self::ProjectTreeExpanded => "project-tree-expanded",
Self::Scheduled => "scheduled",
Self::Timer => "timer",
}
}
@@ -306,6 +315,7 @@ impl EventKind {
Self::ActionPerformed | Self::InputModeChanged => Some(ide_extension::Capability::InputEvents),
Self::RunOutput => Some(ide_extension::Capability::RunOutput),
Self::Scheduled
| Self::Timer
| Self::RunStarted
| Self::RunExited
| Self::TerminalExited
@@ -484,7 +494,11 @@ pub enum WorkbenchEvent {
/// Changes to paths outside the project watched with `events.watch-paths` (API 1.18);
/// `project` is the project the watch belongs to, `generation` is unset.
WatchedFilesChanged(FilesChanged),
/// Project tree folders newly expanded, or already expanded when a plugin subscribes (API 1.21).
ProjectTreeExpanded(Vec<String>),
Scheduled,
/// A timer this plugin set with `events.schedule` fired (API 1.21): its id.
Timer(String),
}
impl WorkbenchEvent {
@@ -511,7 +525,9 @@ impl WorkbenchEvent {
Self::ProblemsChanged => EventKind::ProblemsChanged,
Self::ProjectClosed(_) => EventKind::ProjectClosed,
Self::WatchedFilesChanged(_) => EventKind::WatchedFilesChanged,
Self::ProjectTreeExpanded(_) => EventKind::ProjectTreeExpanded,
Self::Scheduled => EventKind::Scheduled,
Self::Timer(_) => EventKind::Timer,
}
}
}
+30 -1
Переглянути файл
@@ -1824,7 +1824,7 @@ impl events::Host for StoreData {
{
return Ok(Err(to_wit(e)));
}
if matches!(kind, EventKind::RunStarted | EventKind::RunOutput)
if matches!(kind, EventKind::RunStarted | EventKind::RunOutput | EventKind::ProjectTreeExpanded)
&& let Err(e) = self.host.require_api(kind.name(), 21)
{
return Ok(Err(to_wit(e)));
@@ -1895,6 +1895,32 @@ impl events::Host for StoreData {
Ok(())
}
fn schedule(&mut self, id: String, after_ms: u32) -> Fallible<()> {
if let Err(e) = self.host.require_api("events.schedule", 21) {
return Ok(Err(to_wit(e)));
}
if id.is_empty() || id.len() > 128 || id.chars().any(char::is_control) {
return Ok(Err(wit::Error::Invalid("timer id must be 1-128 bytes without control characters".into())));
}
if !(MIN_TIMER_MS..=MAX_TIMER_MS).contains(&after_ms) {
return Ok(Err(wit::Error::Invalid(format!(
"a timer fires {MIN_TIMER_MS} ms to {MAX_TIMER_MS} ms from now"
))));
}
let client = self.client().map(str::to_owned);
Ok(self
.host
.schedule(client.as_deref(), &id, std::time::Duration::from_millis(u64::from(after_ms)))
.map_err(to_wit))
}
fn cancel_schedule(&mut self, id: String) -> wasmtime::Result<()> {
if self.host.require_api("events.schedule", 21).is_ok() {
self.host.cancel_schedule(&id);
}
Ok(())
}
fn watch_paths(&mut self, paths: Vec<String>) -> Fallible<()> {
if let Err(e) = self.require(Capability::Events) {
return Ok(Err(e));
@@ -1934,6 +1960,9 @@ impl events::Host for StoreData {
/// The most paths one plugin watches outside one project (`events.watch-paths`).
const MAX_WATCHED_PATHS: usize = 32;
/// Bounds of `events.schedule`: the event loop's own period, and a day.
const MIN_TIMER_MS: u32 = 250;
const MAX_TIMER_MS: u32 = 24 * 60 * 60 * 1000;
impl tasks::Host for StoreData {
fn begin(&mut self, title: String, cancellable: bool) -> wasmtime::Result<Resource<TaskRes>> {
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
0db78244977b314a99277abd9259edbfc62c304e97a39d46fda547069c5186c1
b8be10102efb9a73945b342e1077130e3ae259d318a1328aa449f3fc6d33c95d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
4e7ceccb5ef879e0124f2717ae29ee7c241330a085f1628a7ea775078cddebfb
75910c8950f19404d2b389c31250b38e94e0845b8406fd65086d801c3b7beb42
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
1034c381a884838c3ba6516c947ce6824c06f0dc9740a6aac9c43874649f5dd8
4dd181187bc087ad2155ac92d304f50cda4fededc63b02ad57cf012f01eef3f6
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
40d95bcd5086e5a20bc23d130b960e87a7c13c065d06cc05edcad931cd0d7f33
99dbde69e800adbb3277f78b0a7ffbf6c86b387995c7cf7f7701a5cc7175f87d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
9b6b716f511497a37d37bdde39b8d669f78cb440ada45cdffe9dfe453bbaf930
4d795c1074d4be794c7327c623b0e366e1daab50778f918a42a2d38439542a12
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
c4100a64064acf9d51de0eed6b3232102df06d70eb7d3ea4793228be84e5a00d
b85013d2dac330df156621e610bcb7b529761f34891ccb0a43139caff9b806e6
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
457306cdbd68b2b0aaa7073a9574d966deeb54993192f1935c1e4d0d92520d9f
6742d26393161e0858d7a672969d861493f36e28ae122fd3606aee570bf154f7
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b10e885276249c17d2a41f2cc4cf7c1452eaefd2f9c2c4d1e2037f311ea0171e
31fec64f6ce288e5514d93dd2d451ec5e00c25ca5fd6568bde636765bc980168
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2de813834872315bac348dbbc1f44d9e67ca3fbccf24f3d6ac2e0404d4632652
24fb126861d1398a19a4b9a9167dc253f4f03760428013050986f94391ed4c79
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
dfbb456cb19f79cf4bde2961434193602659f3b357a09aa42b2c5647350a70b8
65c6e23c92a58ecb73518445eaf2f95decdd3ee434d2ba34101cd7b122881d1c
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2afe22a19f5d3ce2a47476de1421240dbb89a43a1b90d4e21b681be447587459
2f5ce9268f54296994835c650667142893574c96b707410024897242370d522f
Бінарний файл не відображається.
Loaded 100 of 466 files, more files were not shown because too many files have changed in this diff. Show more