дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 10:07:11 +02:00
Merge remote-tracking branch 'origin/main' into fix/python-remember-interpreters
Цей коміт міститься в:
коміт
9cef29acde
657 files changed
+16542
-2220
No files matched your search
@@ -16,5 +16,5 @@ test-group = "windows-clipboard"
|
||||
# that hangs (a server left stopped) is ended after 5 minutes instead of waiting for svn's own
|
||||
# timeout.
|
||||
[[profile.default.overrides]]
|
||||
filter = 'package(=ide-svn) | (package(=ide-host) & (binary(=svn) | binary(=ij_svn_roots)))'
|
||||
filter = 'package(=ide-svn) | (package(=ide-host) & binary(=integration) & (test(/^svn::/) | test(/^ij_svn_roots::/)))'
|
||||
slow-timeout = { period = "60s", terminate-after = 5 }
|
||||
@@ -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.
|
||||
|
||||
@@ -117,14 +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: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
- 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
|
||||
@@ -146,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
|
||||
@@ -169,17 +162,20 @@ jobs:
|
||||
shell: bash
|
||||
run: svn --version --quiet && svnadmin --version --quiet && svnserve --version --quiet && sqlite3 --version
|
||||
# tauri-build checks that frontendDist exists.
|
||||
- run: pnpm install --frozen-lockfile && mkdir -p dist
|
||||
- run: mkdir -p dist
|
||||
shell: bash
|
||||
- if: runner.os == 'Linux'
|
||||
run: cargo fmt --all --check
|
||||
- run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
# On PRs, run clippy on Linux only; macOS/Windows still compile and test all targets
|
||||
# via nextest, and run clippy on main/merge_group so platform-only lints are still caught.
|
||||
- if: runner.os == 'Linux' || github.event_name != 'pull_request'
|
||||
run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
# Test fixtures write LF files; keep Git from converting them on checkout.
|
||||
- run: git config --global core.autocrlf false
|
||||
- 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') }}
|
||||
@@ -213,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 }
|
||||
@@ -235,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 }
|
||||
@@ -257,7 +253,7 @@ jobs:
|
||||
docker pull busybox:latest
|
||||
# --workspace, not -p ide-host: -p would rebuild instead of reusing the test build above.
|
||||
cargo nextest run --workspace --run-ignored only \
|
||||
-E 'package(=ide-host) & binary(=remote_daemon) & test(=compose_service_survives_disconnect_and_is_removed_on_stop)'
|
||||
-E 'package(=ide-host) & binary(=integration) & test(=remote_daemon::compose_service_survives_disconnect_and_is_removed_on_stop)'
|
||||
# nextest skips doctests; ide-command's are its compile-fail tests.
|
||||
- if: runner.os == 'Linux'
|
||||
run: cargo test --doc -p ide-command
|
||||
@@ -291,12 +287,14 @@ 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
|
||||
if: runner.environment != 'self-hosted'
|
||||
with: { key: server-musl }
|
||||
with:
|
||||
key: server-musl
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
@@ -320,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'
|
||||
@@ -356,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
|
||||
@@ -385,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
|
||||
|
||||
@@ -398,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
|
||||
@@ -431,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' || '' }}
|
||||
@@ -453,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' || '' }}
|
||||
@@ -464,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 }}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -26,6 +26,9 @@ on:
|
||||
- "src/features/build/**"
|
||||
- "src/features/build-tools/**"
|
||||
- "src/platform/**"
|
||||
- "!src/platform/locales/text/**"
|
||||
- "!src/platform/locales/*.json"
|
||||
- "src/platform/locales/en.json"
|
||||
- "src/workbench/**"
|
||||
- "src/ui/**"
|
||||
- "src/editor/api.ts"
|
||||
@@ -89,6 +92,7 @@ jobs:
|
||||
pull-requests: read
|
||||
outputs:
|
||||
languages: ${{ steps.classify.outputs.languages }}
|
||||
groups: ${{ steps.classify.outputs.groups }}
|
||||
steps:
|
||||
- id: classify
|
||||
env:
|
||||
@@ -98,8 +102,18 @@ jobs:
|
||||
set -euo pipefail
|
||||
all="typescript python rust go java kotlin php c cpp"
|
||||
emit() { tr ' ' '\n' <<< "$1" | { grep . || true; } | sort -u | jq -Rsc 'split("\n") | map(select(. != ""))'; }
|
||||
emit_groups() {
|
||||
jq -nc --argjson langs "$1" '
|
||||
[
|
||||
{ name: "jvm", languages: ($langs | map(select(. == "java" or . == "kotlin"))) },
|
||||
{ name: "systems", languages: ($langs | map(select(. == "rust" or . == "go" or . == "c" or . == "cpp"))) },
|
||||
{ name: "scripting", languages: ($langs | map(select(. == "typescript" or . == "python" or . == "php"))) }
|
||||
] | map(select(.languages | length > 0))'
|
||||
}
|
||||
if [ "$GITHUB_EVENT_NAME" != pull_request ]; then
|
||||
echo "languages=$(emit "$all")" | tee -a "$GITHUB_OUTPUT"
|
||||
langs_json=$(emit "$all")
|
||||
echo "languages=$langs_json" | tee -a "$GITHUB_OUTPUT"
|
||||
echo "groups=$(emit_groups "$langs_json")" | tee -a "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \
|
||||
@@ -108,8 +122,9 @@ jobs:
|
||||
# Crates outside what the smoke runs (language servers, debuggers, run configurations,
|
||||
# SDKs, build tools, the project model, Find Usages candidates, debug stream traces):
|
||||
# cargo metadata, ide-host's direct deps ide-search/ide-streams and the deps of
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# ide-lsp/dap/run/sdk/tools. Also skip non-English lazy locale catalogs (smoke always
|
||||
# runs in the default English locale).
|
||||
unused='^(crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/|src/platform/locales/text/)'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|lineNumberOptions|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src/assets/openidea-logo\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
@@ -117,6 +132,8 @@ jobs:
|
||||
case "$f" in
|
||||
crates/ide-host/tests/language_smoke.rs | crates/ide-host/tests/project_smoke.rs) langs="$all"; break ;;
|
||||
crates/*/tests/* | crates/*/benches/*) ;;
|
||||
src/platform/locales/en.json) langs="$all"; break ;;
|
||||
src/platform/locales/*.json) ;;
|
||||
fixtures/ts-app/*) langs+=" typescript" ;;
|
||||
fixtures/python-app/*) langs+=" python" ;;
|
||||
fixtures/rust-app/*) langs+=" rust" ;;
|
||||
@@ -141,7 +158,9 @@ jobs:
|
||||
*) if grep -Eq "$smoke" <<< "$f" && ! grep -Eq "$unused" <<< "$f"; then langs="$all"; break; fi ;;
|
||||
esac
|
||||
done < files.txt
|
||||
echo "languages=$(emit "$langs")" | tee -a "$GITHUB_OUTPUT"
|
||||
langs_json=$(emit "$langs")
|
||||
echo "languages=$langs_json" | tee -a "$GITHUB_OUTPUT"
|
||||
echo "groups=$(emit_groups "$langs_json")" | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
# Builds the smoke test binaries and openidea-server once for every language below.
|
||||
build:
|
||||
@@ -157,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'
|
||||
@@ -186,16 +205,16 @@ 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:
|
||||
name: Language smoke (${{ matrix.language }})
|
||||
name: Language smoke (${{ matrix.group.name }})
|
||||
needs: [changes, build]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: ${{ fromJSON(needs.changes.outputs.languages) }}
|
||||
group: ${{ fromJSON(needs.changes.outputs.groups) }}
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
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' }}
|
||||
@@ -205,29 +224,30 @@ 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"
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
- 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' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
- if: matrix.language == 'typescript'
|
||||
- if: contains(matrix.group.languages, 'typescript')
|
||||
run: npm install --global "@vtsls/language-server@$VTSLS" "typescript@$TYPESCRIPT"
|
||||
|
||||
# The smoke checks C/C++ with clangd and debugs c-app with GDB's own DAP interpreter (GDB 14+).
|
||||
- if: matrix.language == 'c' || matrix.language == 'cpp'
|
||||
- if: contains(matrix.group.languages, 'c') || contains(matrix.group.languages, 'cpp')
|
||||
shell: bash
|
||||
run: |
|
||||
pkgs=()
|
||||
@@ -243,22 +263,22 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- if: matrix.language == 'python'
|
||||
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||
- if: contains(matrix.group.languages, 'python')
|
||||
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
||||
with: { python-version: "3.12" }
|
||||
- if: matrix.language == 'python'
|
||||
- if: contains(matrix.group.languages, 'python')
|
||||
run: pip install "basedpyright==$BASEDPYRIGHT" "ruff==$RUFF"
|
||||
|
||||
- if: matrix.language == 'go'
|
||||
uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
|
||||
- if: contains(matrix.group.languages, 'go')
|
||||
uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
|
||||
with: { go-version: "1.27", cache: false }
|
||||
- if: matrix.language == 'go'
|
||||
- if: contains(matrix.group.languages, 'go')
|
||||
run: go install "golang.org/x/tools/gopls@$GOPLS"
|
||||
|
||||
- if: matrix.language == 'java' || matrix.language == 'kotlin'
|
||||
uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
|
||||
- if: contains(matrix.group.languages, 'java') || contains(matrix.group.languages, 'kotlin')
|
||||
uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
|
||||
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
|
||||
- if: matrix.language == 'java'
|
||||
- if: contains(matrix.group.languages, 'java')
|
||||
run: |
|
||||
command -v mvn >/dev/null || { sudo apt-get update && sudo apt-get install -y maven; }
|
||||
mkdir -p "$RUNNER_TEMP/jdtls"
|
||||
@@ -267,10 +287,12 @@ jobs:
|
||||
echo "$RUNNER_TEMP/jdtls/bin" >> "$GITHUB_PATH"
|
||||
|
||||
# The Kotlin fixture has no Gradle wrapper: the server imports it with the Gradle on PATH.
|
||||
- if: matrix.language == 'kotlin'
|
||||
uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
|
||||
with: { gradle-version: "${{ env.GRADLE }}" }
|
||||
- if: matrix.language == 'kotlin'
|
||||
- if: contains(matrix.group.languages, 'kotlin')
|
||||
uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1
|
||||
with:
|
||||
gradle-version: "${{ env.GRADLE }}"
|
||||
cache-read-only: ${{ github.ref != 'refs/heads/main' }}
|
||||
- if: contains(matrix.group.languages, 'kotlin')
|
||||
run: |
|
||||
mkdir -p "$RUNNER_TEMP/kotlin-lsp" "$RUNNER_TEMP/bin"
|
||||
curl -fsSL "https://download.jetbrains.com/language-server/kotlin-server/$KOTLIN_LSP/kotlin-server-$KOTLIN_LSP.tar.gz" \
|
||||
@@ -279,31 +301,48 @@ jobs:
|
||||
echo "$RUNNER_TEMP/bin" >> "$GITHUB_PATH"
|
||||
|
||||
# Xdebug for the debug smoke; Composer installs the fixture's Pest for the run smoke.
|
||||
- if: matrix.language == 'php'
|
||||
- if: contains(matrix.group.languages, 'php')
|
||||
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
|
||||
with: { php-version: "8.5", coverage: xdebug, tools: composer }
|
||||
- if: matrix.language == 'php'
|
||||
- if: contains(matrix.group.languages, 'php')
|
||||
run: npm install --global "intelephense@$INTELEPHENSE"
|
||||
|
||||
# The binaries from the build job, run from the crate directory as `cargo test` does.
|
||||
- working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
|
||||
# Problems › TypeScript Project Errors runs the project's own tsc: the global install stands in.
|
||||
- if: matrix.language == 'typescript'
|
||||
- name: Code intelligence and project smoke
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/language_smoke --ignored --exact typescript_project_errors typescript_import_style
|
||||
- if: matrix.language == 'java'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
|
||||
- if: matrix.language == 'kotlin'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact gradle_sync
|
||||
- if: matrix.language == 'python'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact python_venv
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
status=0
|
||||
for lang in ${{ join(matrix.group.languages, ' ') }}; do
|
||||
echo "::group::language_smoke ($lang)"
|
||||
../../smoke-bin/language_smoke --ignored --exact "$lang" || status=1
|
||||
# Problems › TypeScript Project Errors runs the project's own tsc: the global install stands in.
|
||||
if [ "$lang" = typescript ]; then
|
||||
../../smoke-bin/language_smoke --ignored --exact typescript_project_errors typescript_import_style || status=1
|
||||
fi
|
||||
if [ "$lang" = java ]; then
|
||||
../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier || status=1
|
||||
fi
|
||||
if [ "$lang" = kotlin ]; then
|
||||
../../smoke-bin/project_smoke --ignored --exact gradle_sync || status=1
|
||||
fi
|
||||
if [ "$lang" = python ]; then
|
||||
../../smoke-bin/project_smoke --ignored --exact python_venv || status=1
|
||||
fi
|
||||
echo "::endgroup::"
|
||||
done
|
||||
exit "$status"
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm smoke smoke/run.test.ts -t "^${{ matrix.language }}$"
|
||||
- run: pnpm smoke smoke/debug.test.ts -t "^${{ matrix.language }}$"
|
||||
- name: Run and debug smoke
|
||||
shell: bash
|
||||
# The IDE installs the debugger from GitHub releases: authenticated, against rate limits.
|
||||
env: { GITHUB_TOKEN: "${{ github.token }}" }
|
||||
run: |
|
||||
set -euo pipefail
|
||||
pattern="^($(echo "${{ join(matrix.group.languages, '|') }}"))$"
|
||||
status=0
|
||||
pnpm smoke smoke/run.test.ts -t "$pattern" || status=1
|
||||
pnpm smoke smoke/debug.test.ts -t "$pattern" || status=1
|
||||
exit "$status"
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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`;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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>,
|
||||
|
||||
@@ -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")));
|
||||
}
|
||||
}
|
||||
@@ -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")))
|
||||
}
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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")] {
|
||||
|
||||
@@ -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"] {
|
||||
|
||||
@@ -294,7 +294,7 @@ pub fn plan(
|
||||
}
|
||||
BuildSystem::TypeScript => ts_steps(&dir, kind),
|
||||
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
|
||||
BuildSystem::Dotnet => dotnet_steps(&dir, kind)?,
|
||||
BuildSystem::Dotnet => dotnet_steps(&dir, kind, file)?,
|
||||
// Never detected from a folder: it comes from the Project Structure (`structure_plan`).
|
||||
BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")),
|
||||
}
|
||||
@@ -553,10 +553,24 @@ fn dotnet_target(dir: &Path) -> Option<PathBuf> {
|
||||
solution.or_else(|| files.iter().find(|p| matches!(ext(p).as_str(), "csproj" | "fsproj" | "vbproj"))).cloned()
|
||||
}
|
||||
|
||||
/// `dotnet build` of the directory's solution or project; Rebuild skips incremental builds,
|
||||
/// `dotnet build` of `file` when it is a solution or project in `dir` (a run configuration's
|
||||
/// project), else of the directory's solution or project; Rebuild skips incremental builds,
|
||||
/// Build Artifacts publishes. The summary that repeats every message is left out.
|
||||
fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
|
||||
let target = dotnet_target(dir).ok_or_else(|| IdeError::not_found("no .NET solution or project found"))?;
|
||||
fn dotnet_steps(dir: &Path, kind: BuildKind, file: Option<&Path>) -> IdeResult<Vec<BuildStep>> {
|
||||
let given = file.filter(|f| {
|
||||
f.parent() == Some(dir)
|
||||
&& f.is_file()
|
||||
&& f.extension().is_some_and(|e| {
|
||||
matches!(
|
||||
e.to_string_lossy().to_ascii_lowercase().as_str(),
|
||||
"sln" | "slnx" | "csproj" | "fsproj" | "vbproj"
|
||||
)
|
||||
})
|
||||
});
|
||||
let target = given
|
||||
.map(Path::to_path_buf)
|
||||
.or_else(|| dotnet_target(dir))
|
||||
.ok_or_else(|| IdeError::not_found("no .NET solution or project found"))?;
|
||||
let target = target.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned());
|
||||
let verb = if kind == BuildKind::Artifacts { "publish" } else { "build" };
|
||||
let mut step = BuildStep::new("dotnet", &[verb, &target, "-nologo", "-clp:NoSummary"], dir, Format::Msbuild);
|
||||
@@ -1734,6 +1748,36 @@ mod tests {
|
||||
let p = plan(&net, &BuildModel::default(), BuildKind::Artifacts, None, None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args[0], "publish");
|
||||
// A run configuration's project is built even when its folder holds other projects or a
|
||||
// solution that sort first (#8179).
|
||||
write(&net, "src/Host/Legacy.csproj", "<Project/>");
|
||||
write(&net, "src/Host/Main.csproj", "<Project/>");
|
||||
write(&net, "src/Host/All.sln", "");
|
||||
for name in ["Main.csproj", "All.sln", "Legacy.csproj"] {
|
||||
let file = net.join("src/Host").join(name);
|
||||
let p = plan(
|
||||
&net,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
Some(&file),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args[1], name);
|
||||
}
|
||||
let p = plan(
|
||||
&net,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
Some(&net.join("src/Host/Program.cs")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args[1], "All.sln");
|
||||
|
||||
let cm = tmp.path().join("cm");
|
||||
write(&cm, "CMakeLists.txt", "project(app)");
|
||||
|
||||
@@ -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") {
|
||||
|
||||
@@ -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#"
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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(&[
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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"] {
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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}");
|
||||
|
||||
@@ -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()));
|
||||
|
||||
@@ -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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,6 @@
|
||||
mod debugpy;
|
||||
mod godot;
|
||||
mod php_debug;
|
||||
mod real_adapters;
|
||||
mod script_debuggers;
|
||||
mod unity;
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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``;`"#;
|
||||
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,11 @@
|
||||
mod clickhouse;
|
||||
mod jdbc;
|
||||
mod mysql;
|
||||
mod pg_console_sessions;
|
||||
mod pg_console_transactions;
|
||||
mod postgres;
|
||||
mod snowflake;
|
||||
mod sqlite;
|
||||
mod sqlite_console_sessions;
|
||||
mod sqlserver;
|
||||
mod ssh_tunnel;
|
||||
@@ -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(())
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
+86
-2
@@ -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();
|
||||
@@ -701,7 +785,7 @@ async fn managed_tunnel_shares_the_forwarder_and_closes_it_after_the_last_target
|
||||
executable: std::env::current_exe()?.to_string_lossy().into_owned(),
|
||||
arguments: vec![
|
||||
"--exact".into(),
|
||||
"postgres_tunnel_fixture".into(),
|
||||
"postgres::postgres_tunnel_fixture".into(),
|
||||
"--skip".into(),
|
||||
"listen={localPort}".into(),
|
||||
"--skip".into(),
|
||||
@@ -758,7 +842,7 @@ async fn external_startup_does_not_block_another_source_and_disconnect_cancels_i
|
||||
executable: std::env::current_exe()?.to_string_lossy().into_owned(),
|
||||
arguments: vec![
|
||||
"--exact".into(),
|
||||
"postgres_tunnel_fixture".into(),
|
||||
"postgres::postgres_tunnel_fixture".into(),
|
||||
"--skip".into(),
|
||||
"listen={localPort}".into(),
|
||||
"--skip".into(),
|
||||
+1
-1
@@ -320,7 +320,7 @@ async fn explorer_metadata_against_a_real_account() {
|
||||
// each is either answered or refused by Snowflake (an edition or privilege it needs), never
|
||||
// misread by the client. `USE` goes to what the session already has.
|
||||
let fixture: serde_json::Value =
|
||||
serde_json::from_str(include_str!("fixtures/snowflake/commands.json")).expect("the fixture parses");
|
||||
serde_json::from_str(include_str!("../fixtures/snowflake/commands.json")).expect("the fixture parses");
|
||||
let mut statements: Vec<(String, String)> = fixture["commands"]
|
||||
.as_array()
|
||||
.expect("commands")
|
||||
@@ -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(())
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -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"] {
|
||||
|
||||
@@ -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,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());
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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(),
|
||||
}))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -80,6 +80,17 @@ pub trait PluginWorkspace: Send + Sync {
|
||||
) -> Result<String, HostError> {
|
||||
Err(HostError::Failed("agent fork unavailable".into()))
|
||||
}
|
||||
/// Start a new agent task in the invoking window's project, unsent, and open it in
|
||||
/// the Agents window for the user to review and send (API 1.21).
|
||||
fn start_agent_task(
|
||||
&self,
|
||||
_client: &str,
|
||||
_provider: &str,
|
||||
_prompt: &str,
|
||||
_fork: Option<(&str, &Path)>,
|
||||
) -> Result<String, HostError> {
|
||||
Err(HostError::Failed("agent task unavailable".into()))
|
||||
}
|
||||
|
||||
/// Roots of the open projects.
|
||||
fn projects(&self) -> Vec<PathBuf>;
|
||||
@@ -303,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.
|
||||
@@ -799,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>>,
|
||||
@@ -907,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(),
|
||||
@@ -1053,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);
|
||||
@@ -1109,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)
|
||||
}
|
||||
@@ -1213,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);
|
||||
@@ -2441,6 +2487,23 @@ impl HostApi for PluginApi {
|
||||
.ok_or_else(|| HostError::NotFound("window project".into()))?
|
||||
.fork_agent_session(client, agent, session_id, cwd)
|
||||
}
|
||||
fn start_agent_task(
|
||||
&self,
|
||||
client: &str,
|
||||
provider: &str,
|
||||
prompt: &str,
|
||||
fork: Option<(&str, &Path)>,
|
||||
) -> Result<String, HostError> {
|
||||
let task_id = self
|
||||
.shared
|
||||
.workspace()
|
||||
.ok_or_else(|| HostError::NotFound("window project".into()))?
|
||||
.start_agent_task(client, provider, prompt, fork)?;
|
||||
self.shared
|
||||
.sink
|
||||
.emit(Some(client), PluginEvent::OpenAgentTask { task_id: task_id.clone(), prompt: prompt.to_owned() });
|
||||
Ok(task_id)
|
||||
}
|
||||
fn console_rules(&self, rules: Vec<ide_plugin::ConsoleRule>) -> Result<(), HostError> {
|
||||
let rules = super::console_rules::normalize(rules).map_err(HostError::Invalid)?;
|
||||
let mut all = self.shared.console_rules.lock();
|
||||
@@ -3797,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)
|
||||
}
|
||||
@@ -4393,6 +4477,31 @@ impl PluginWorkspace for HostWorkspace {
|
||||
Ok(project.agents.fork_session(agent, session_id, cwd).map_err(failed)?.id)
|
||||
}
|
||||
|
||||
fn start_agent_task(
|
||||
&self,
|
||||
client: &str,
|
||||
provider: &str,
|
||||
prompt: &str,
|
||||
fork: Option<(&str, &Path)>,
|
||||
) -> Result<String, HostError> {
|
||||
let host = self.0.upgrade().ok_or(HostError::Cancelled)?;
|
||||
let project = host.project(client).map_err(failed)?;
|
||||
project.require_trust().map_err(failed)?;
|
||||
if let Some((session_id, cwd)) = fork {
|
||||
// The fork path validates the recording and builds the invocation itself.
|
||||
return Ok(project.agents.fork_session(provider, session_id, cwd).map_err(failed)?.id);
|
||||
}
|
||||
let request = ide_agent::NewAgentTask {
|
||||
prompt: ide_agent::AgentPrompt { text: prompt.to_owned(), ..Default::default() },
|
||||
provider: provider.to_owned(),
|
||||
isolation: ide_agent::Isolation::Local,
|
||||
// Unsent: the prompt only names the task; the user reviews it in the Agents window and sends.
|
||||
idle: true,
|
||||
..Default::default()
|
||||
};
|
||||
Ok(host.runtime.block_on(project.agents.create(request)).map_err(failed)?.id)
|
||||
}
|
||||
|
||||
fn buffer_text_in(&self, client: Option<&str>, path: &Path) -> Option<String> {
|
||||
client
|
||||
.and_then(|w| self.0.upgrade()?.project(w).ok()?.documents.text_of(path))
|
||||
@@ -5865,6 +5974,33 @@ impl PluginApi {
|
||||
items
|
||||
.iter_mut()
|
||||
.for_each(|d| d.colors = d.colors.take().filter(|c| c.foreground.is_some() || c.background.is_some()));
|
||||
// Hover-card actions (API 1.21): bounded, and each command must be one the plugin declares.
|
||||
for item in &items {
|
||||
if item.actions.len() > 4 {
|
||||
return Err(HostError::Invalid("at most 4 actions per decoration".into()));
|
||||
}
|
||||
for a in &item.actions {
|
||||
if a.label.is_empty() || a.label.len() > 64 || a.label.chars().any(char::is_control) {
|
||||
return Err(HostError::Invalid(
|
||||
"action label must be 1-64 bytes without control characters".into(),
|
||||
));
|
||||
}
|
||||
if a.tooltip.as_ref().is_some_and(|t| t.len() > 256) {
|
||||
return Err(HostError::Invalid("action tooltip is at most 256 bytes".into()));
|
||||
}
|
||||
if a.argument.as_ref().is_some_and(|s| s.len() > 4096) {
|
||||
return Err(HostError::Invalid("action argument is at most 4 KiB".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
if items.iter().any(|d| !d.actions.is_empty()) {
|
||||
let commands = self.shared.ui.items("commands", Some(self.id()));
|
||||
for a in items.iter().flat_map(|d| &d.actions) {
|
||||
if !commands.iter().any(|c| c.key == a.command) {
|
||||
return Err(HostError::NotFound(format!("the plugin declares no command {:?}", a.command)));
|
||||
}
|
||||
}
|
||||
}
|
||||
// An item with its own colors (API 1.17) may leave the style empty.
|
||||
items.retain(|d| decoration_style(&d.style) || (d.style.is_empty() && d.colors.is_some()));
|
||||
if items.iter().any(|d| d.range.start > d.range.end) {
|
||||
@@ -6217,6 +6353,7 @@ mod workbench_tests {
|
||||
after: Some("after".into()),
|
||||
markdown_hover: None,
|
||||
colors: None,
|
||||
actions: vec![],
|
||||
};
|
||||
api.decorations(Some(&path), "set", vec![item("highlight"), item("unknown")]).unwrap();
|
||||
assert_eq!(api.shared.decoration_sets()["test"][0].items.len(), 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()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
)
|
||||
})
|
||||
{
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -283,6 +283,10 @@ pub enum PluginEvent {
|
||||
/// Open the IDE's native table data grid in the invoking window (API 1.21).
|
||||
#[serde(rename_all = "camelCase")]
|
||||
OpenDatabaseTable { plugin_id: String, source_id: String, catalog: Option<String>, schema: String, table: String },
|
||||
/// Open a plugin-started task in the invoking window's Agents window (API 1.21):
|
||||
/// created unsent, with `prompt` in its message field for the user to review and send.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
OpenAgentTask { task_id: String, prompt: String },
|
||||
/// Complete replacement of one plugin's clickable console link rules (API 1.21).
|
||||
#[serde(rename_all = "camelCase")]
|
||||
ConsoleLinksChanged { plugin_id: String, rules: Vec<ide_plugin::ConsoleLinkRule> },
|
||||
@@ -546,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")]
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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
-1
@@ -1,6 +1,6 @@
|
||||
//! The mode new agent tasks start in.
|
||||
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_host::{Host, HostConfig};
|
||||
use serde_json::json;
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
//! worktree auto-GC + retention cap, `NeedsInput` approval, in-session `Send Later` / `/loop`,
|
||||
//! and persistent `openidea-server --daemon` keep-alive across disconnects.
|
||||
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_agent::{
|
||||
AgentPrompt, AutomationContinuity, AutomationPermissionMode, AutomationRunOrigin, AutomationRunStatus,
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
//! Values of agents' environment variables live in the credential store; agent files keep only their names.
|
||||
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_host::Host;
|
||||
use ide_ssh::secrets::testing::{files_containing, use_memory_store};
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
//! External MCP servers in Settings › Agents, as the host stores and lists them.
|
||||
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_agent::{McpScope, McpServer, McpServerInput};
|
||||
use ide_core::settings::McpTransport;
|
||||
+1
-2
@@ -1,7 +1,6 @@
|
||||
//! Separate project windows share discovery and its backend-enforced cooldown.
|
||||
#![cfg(unix)]
|
||||
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_agent::AgentEvent;
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
//! Each project of a workspace keeps its own excluded folders: they apply below that project only.
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_core::RequestId;
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
//! Binary command arguments over the remote protocol: base64 strings, not arrays of numbers.
|
||||
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_core::IpcBytes;
|
||||
use ide_host::Host;
|
||||
+1
-2
@@ -1,8 +1,7 @@
|
||||
//! Closing a project takes the background processes of its window with it, as IDEA does,
|
||||
//! and leaves the other windows' processes alone.
|
||||
#![cfg(unix)]
|
||||
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_host::{Host, ops};
|
||||
use std::sync::Arc;
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
//! The PHP of a Docker and of a Compose run target, against a real daemon. Ignored by default:
|
||||
//! `docker` with the Compose plugin must be on `PATH` and able to pull `php:8.3-cli`.
|
||||
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_host::{Host, ops};
|
||||
use std::sync::Arc;
|
||||
+1
-2
@@ -3,9 +3,8 @@
|
||||
//! daemon can bind-mount (on this machine, or at the same path in a VM such as OrbStack's),
|
||||
//! `docker` with the Compose plugin and `basedpyright-langserver` must be on `PATH`, and
|
||||
//! this machine's Python must not have Django installed.
|
||||
#![cfg(unix)]
|
||||
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_core::IdeEvent;
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
//! It downloads CSharpier, so it runs only on request:
|
||||
//! `cargo test -p ide-host --test csharpier -- --ignored`; skipped without a .NET SDK.
|
||||
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{IdeEvent, IdeResult, Pos, Range, TextEdit};
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_host::Host;
|
||||
use ide_host::ops::db;
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
//! that sends no real window (the desktop shell once passed `""`) never reaches the debugger,
|
||||
//! and a project in Restricted Mode never reads the debuggee's memory.
|
||||
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_core::IdeError;
|
||||
use ide_host::Host;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_core::RequestId;
|
||||
use ide_host::{
|
||||
File renamed without changes.
+1
-2
@@ -2,9 +2,8 @@
|
||||
//! `OPENIDEA_DOCKER_TEST_DIR` names an empty folder the daemon can bind-mount
|
||||
//! (on this machine, or at the same path in a VM such as OrbStack's), and
|
||||
//! `docker` with the Compose plugin must be on `PATH`.
|
||||
#![cfg(unix)]
|
||||
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_host::{Host, ops};
|
||||
use ide_run::{OutputChunk, RunConfig};
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
//! Explicit external logs allow history reads without adding a writable project root.
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_host::{Host, ops::vcs};
|
||||
use std::{path::Path, process::Command};
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
//! SvnExternalTest, SvnExternalCommitNoticedTest and SvnCommitTest (scenarios only); the
|
||||
//! working copies themselves are checked in crates/ide-svn/tests/ij_files.rs.
|
||||
//! Skipped when `svn` or `svnadmin` is not installed (a failure in CI).
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_host::Host;
|
||||
use ide_host::ops::vcs;
|
||||
+7
-7
@@ -1,4 +1,4 @@
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_build::compile::BuildEvent;
|
||||
use ide_core::RequestId;
|
||||
@@ -26,11 +26,11 @@ async fn pom_launch_uses_dependency_classpath_without_a_java_project() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
let pom = include_str!("../../ide-build/tests/fixtures/jbuild-maven/pom.xml")
|
||||
let pom = include_str!("../../../ide-build/tests/fixtures/jbuild-maven/pom.xml")
|
||||
.replace("</modules>", "<module>assembly</module></modules>");
|
||||
write(&root, "pom.xml", &pom);
|
||||
write(&root, "lib/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/lib/pom.xml"));
|
||||
write(&root, "app/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/app/pom.xml"));
|
||||
write(&root, "lib/pom.xml", include_str!("../../../ide-build/tests/fixtures/jbuild-maven/lib/pom.xml"));
|
||||
write(&root, "app/pom.xml", include_str!("../../../ide-build/tests/fixtures/jbuild-maven/app/pom.xml"));
|
||||
write(
|
||||
&root,
|
||||
"assembly/pom.xml",
|
||||
@@ -130,9 +130,9 @@ async fn maven_launch_compiles_with_the_ides_java_build() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
write(&root, "pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/pom.xml"));
|
||||
write(&root, "lib/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/lib/pom.xml"));
|
||||
write(&root, "app/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/app/pom.xml"));
|
||||
write(&root, "pom.xml", include_str!("../../../ide-build/tests/fixtures/jbuild-maven/pom.xml"));
|
||||
write(&root, "lib/pom.xml", include_str!("../../../ide-build/tests/fixtures/jbuild-maven/lib/pom.xml"));
|
||||
write(&root, "app/pom.xml", include_str!("../../../ide-build/tests/fixtures/jbuild-maven/app/pom.xml"));
|
||||
write(
|
||||
&root,
|
||||
"lib/src/main/java/l/L.java",
|
||||
File renamed without changes.
+1
-1
@@ -1,6 +1,6 @@
|
||||
//! LightEdit: a window editing loose files without a project.
|
||||
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_core::{ChangeSet, Pos, Range, SymbolKind, TextChange};
|
||||
use ide_host::{Host, catalogue::TrustClass, ops};
|
||||
@@ -0,0 +1,102 @@
|
||||
#[path = "../common/mod.rs"]
|
||||
mod common;
|
||||
|
||||
mod agent_approvals;
|
||||
mod agent_automations;
|
||||
mod agent_env_secrets;
|
||||
mod agent_mcp;
|
||||
#[cfg(unix)]
|
||||
mod agent_model_refresh;
|
||||
mod attached_excludes;
|
||||
mod binary_args;
|
||||
#[cfg(unix)]
|
||||
mod close_project;
|
||||
mod container_php_real;
|
||||
#[cfg(unix)]
|
||||
mod container_python_real;
|
||||
mod csharpier;
|
||||
mod data_dirs;
|
||||
mod db_consoles;
|
||||
mod debug_jvm_memory_ipc;
|
||||
mod directory_sync;
|
||||
mod distribution;
|
||||
#[cfg(unix)]
|
||||
mod docker_run_targets_real;
|
||||
mod external_log;
|
||||
mod gradle_linkage;
|
||||
mod ij_svn_roots;
|
||||
mod java_build;
|
||||
mod jdtls_excluded_checkout;
|
||||
mod light_edit;
|
||||
mod maven_external;
|
||||
mod mcp;
|
||||
mod mcp_secrets;
|
||||
mod nav_inheritance;
|
||||
#[cfg(windows)]
|
||||
mod network_images;
|
||||
mod open_project;
|
||||
mod plugin_clipboard;
|
||||
mod plugin_code_semantics;
|
||||
mod plugin_commit;
|
||||
mod plugin_completion_list;
|
||||
mod plugin_completion_resolve;
|
||||
mod plugin_data_tools;
|
||||
mod plugin_database_open;
|
||||
mod plugin_dependencies;
|
||||
mod plugin_diagnostics;
|
||||
mod plugin_hover;
|
||||
mod plugin_indexing;
|
||||
mod plugin_inlay_hints;
|
||||
mod plugin_language_features;
|
||||
mod plugin_project_view;
|
||||
mod plugin_refactoring;
|
||||
mod plugin_rename;
|
||||
mod plugin_run_anything;
|
||||
mod plugin_run_output;
|
||||
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;
|
||||
mod pom_encoding;
|
||||
mod properties;
|
||||
mod pytest_fixtures;
|
||||
mod python_move;
|
||||
mod python_rename_comments;
|
||||
mod python_signature;
|
||||
mod python_signature_ops;
|
||||
#[cfg(unix)]
|
||||
mod remote_daemon;
|
||||
#[cfg(unix)]
|
||||
mod remote_plugins;
|
||||
mod replace_all;
|
||||
mod roslyn_editorconfig;
|
||||
mod roslyn_hints;
|
||||
mod rpc;
|
||||
mod run_configs;
|
||||
mod search_encoding;
|
||||
mod settings_sync;
|
||||
mod spell_dictionary;
|
||||
mod ssh_terminal;
|
||||
mod svn;
|
||||
#[cfg(any(unix, windows))]
|
||||
mod terminal_images;
|
||||
mod trust;
|
||||
#[cfg(unix)]
|
||||
mod trust_git_binary;
|
||||
mod trust_vcs_sweep;
|
||||
mod unity;
|
||||
mod vcs_backends;
|
||||
mod vcs_delete_added;
|
||||
mod vcs_documents;
|
||||
mod vcs_encoding;
|
||||
mod vcs_flow;
|
||||
mod vcs_roots;
|
||||
mod vcs_shelf_roots;
|
||||
mod vcs_watcher_moved_repository;
|
||||
mod vcs_worktrees;
|
||||
mod workspace_edits;
|
||||
mod workspaces;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use ide_workspace::settings::SettingsScope;
|
||||
@@ -1,8 +1,9 @@
|
||||
mod common;
|
||||
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}");
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
//! credential store; `settings.toml` keeps only their names. A project's own servers keep
|
||||
//! their values in the project's file, where the project shares them.
|
||||
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_agent::{McpKeyValue, McpScope, McpServer, McpServerInput};
|
||||
use ide_core::settings::McpTransport;
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
//! written in its source, so the UI can compute inheritance gutter markers without a
|
||||
//! language server's type-hierarchy provider.
|
||||
|
||||
mod common;
|
||||
use crate::common;
|
||||
|
||||
use ide_host::{Host, ops};
|
||||
use std::path::PathBuf;
|
||||
Loaded 100 of 657 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача