дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 10:07:11 +02:00
Порівняти коміти
154
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
2bf4c72d93 | ||
|
|
c341799768 | ||
|
|
69fca0aaa3 | ||
|
|
f8e1705dff | ||
|
|
a4394d3ece | ||
|
|
4021bdd0d1 | ||
|
|
8e8a3f397b | ||
|
|
cfbc0e3ed3 | ||
|
|
775a5e04d0 | ||
|
|
90f1ad67d4 | ||
|
|
67c48409c8 | ||
|
|
85e03f72ee | ||
|
|
98ffcf5919 | ||
|
|
4650d88b73 | ||
|
|
305b8c7eec | ||
|
|
03ce267445 | ||
|
|
2aa242252f | ||
|
|
4ff4b2d016 | ||
|
|
d85939395b | ||
|
|
95ac0a0c1a | ||
|
|
396a490adf | ||
|
|
cc877ed9f7 | ||
|
|
0c495e2eed | ||
|
|
1cbb572631 | ||
|
|
251f3953fa | ||
|
|
aa124276b2 | ||
|
|
fb91ace8aa | ||
|
|
c931cbecc0 | ||
|
|
cfaf05c84b | ||
|
|
59f3994b6c | ||
|
|
908b753daf | ||
|
|
3790f578be | ||
|
|
68ffce6340 | ||
|
|
3f74972f11 | ||
|
|
eefe6cc9c8 | ||
|
|
e9480d690c | ||
|
|
13b8024588 | ||
|
|
452d897032 | ||
|
|
a69ff2499d | ||
|
|
0df4bc2289 | ||
|
|
83a3b1208a | ||
|
|
94cfde8025 | ||
|
|
b228d31ff9 | ||
|
|
f160d60a7a | ||
|
|
46031d162b | ||
|
|
4c44beba35 | ||
|
|
65545d3563 | ||
|
|
b4148e2f39 | ||
|
|
6e642b4d4b | ||
|
|
4bd6f8e720 | ||
|
|
7145b81ac1 | ||
|
|
8f080ee99e | ||
|
|
feb5262a16 | ||
|
|
7911a74c05 | ||
|
|
bb7cacb357 | ||
|
|
b5f7f0f472 | ||
|
|
8a26dff72b | ||
|
|
529cd33ddc | ||
|
|
838cf14845 | ||
|
|
4baa407e25 | ||
|
|
b01ba2da03 | ||
|
|
e4f7709f53 | ||
|
|
bcee799269 | ||
|
|
ec4da5efa5 | ||
|
|
94a28cbd1d | ||
|
|
63830dcbaf | ||
|
|
4ab9f02dc2 | ||
|
|
1102822981 | ||
|
|
006777dae1 | ||
|
|
df77c18117 | ||
|
|
360c6f1ae1 | ||
|
|
258639c372 | ||
|
|
9a10fde46f | ||
|
|
eecd78aee5 | ||
|
|
32fa8b60f8 | ||
|
|
7f81ec7f63 | ||
|
|
1f4ac3afbb | ||
|
|
7a20b20b2d | ||
|
|
cd0fe6c8f5 | ||
|
|
b8d0d12142 | ||
|
|
7ba1acc0cf | ||
|
|
9aab39de87 | ||
|
|
c77545460d | ||
|
|
6d22097e9a | ||
|
|
cd92df2007 | ||
|
|
8a301dad86 | ||
|
|
66b90e3ee8 | ||
|
|
ee6f9f81a5 | ||
|
|
c13cb2bf27 | ||
|
|
7d30d23a56 | ||
|
|
749c34df7a | ||
|
|
acf5e53953 | ||
|
|
9d5c294218 | ||
|
|
588d1d17aa | ||
|
|
6b94744df3 | ||
|
|
30c80107e3 | ||
|
|
05a88394fb | ||
|
|
455e32ab76 | ||
|
|
c55ee61b71 | ||
|
|
0b7485f69f | ||
|
|
5a44ccb615 | ||
|
|
587d964e42 | ||
|
|
63f20ce5cc | ||
|
|
2389f55bae | ||
|
|
af416b0572 | ||
|
|
a19864d5b1 | ||
|
|
1548f5cfe5 | ||
|
|
bca532e4e3 | ||
|
|
c04fe9a72b | ||
|
|
04d5eae0d1 | ||
|
|
32242eaf53 | ||
|
|
ef986fbeca | ||
|
|
7f40257632 | ||
|
|
630e56a263 | ||
|
|
6d576e8ff5 | ||
|
|
6600a06ee8 | ||
|
|
ca4644cbde | ||
|
|
d1c07306e9 | ||
|
|
9f63ea75fe | ||
|
|
cff33ee70d | ||
|
|
ccb73f4efd | ||
|
|
d69ebb9f1e | ||
|
|
579ce3f731 | ||
|
|
71ded3e4c0 | ||
|
|
59397c4842 | ||
|
|
76cb012b92 | ||
|
|
853a0304e1 | ||
|
|
5c2b52075d | ||
|
|
2389c0e07e | ||
|
|
df5df76c92 | ||
|
|
4fe11aacbd | ||
|
|
11db5c34d9 | ||
|
|
7d4d0cb921 | ||
|
|
d84cae9525 | ||
|
|
61a4118921 | ||
|
|
63ce54dc1e | ||
|
|
2d3f81cf54 | ||
|
|
cd989aace8 | ||
|
|
bb628998cc | ||
|
|
72aa411d2b | ||
|
|
d1925ada22 | ||
|
|
1eb91d4cef | ||
|
|
3b00295036 | ||
|
|
86a39c6573 | ||
|
|
979d19d066 | ||
|
|
ea32779559 | ||
|
|
42ba15665b | ||
|
|
65e243f5fc | ||
|
|
3a956c72b8 | ||
|
|
84ae5bb179 | ||
|
|
f49302d365 | ||
|
|
35f525dbde | ||
|
|
24b00c3db1 | ||
|
|
6a1cd830f5 |
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 }
|
||||
@@ -6,4 +6,6 @@ updates:
|
||||
directory: /
|
||||
schedule: { interval: weekly }
|
||||
groups:
|
||||
actions: { patterns: ["*"] }
|
||||
# tauri-action builds and uploads the release, so its updates come as their own PR and are
|
||||
# merged after a draft release has gone through with them.
|
||||
actions: { patterns: ["*"], exclude-patterns: ["tauri-apps/tauri-action"] }
|
||||
@@ -118,13 +118,6 @@ jobs:
|
||||
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: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
with: { components: "clippy, rustfmt" }
|
||||
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
|
||||
@@ -148,6 +141,11 @@ jobs:
|
||||
fi
|
||||
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
|
||||
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
|
||||
with:
|
||||
dotnet-version: 10.0.x
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
@@ -164,11 +162,14 @@ 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
|
||||
@@ -212,14 +213,47 @@ jobs:
|
||||
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
|
||||
if: runner.environment == 'github-hosted'
|
||||
id: yappi-python
|
||||
with: { python-version: "3.12", update-environment: false }
|
||||
- name: Install yappi for the Python profiler tests
|
||||
if: steps.yappi-python.outputs.python-path != ''
|
||||
shell: bash
|
||||
env:
|
||||
PYTHON: ${{ steps.yappi-python.outputs.python-path }}
|
||||
run: |
|
||||
"$PYTHON" -m venv "$RUNNER_TEMP/yappi-venv"
|
||||
venv_py="$RUNNER_TEMP/yappi-venv/bin/python"
|
||||
[ -x "$venv_py" ] || venv_py="$RUNNER_TEMP/yappi-venv/Scripts/python.exe"
|
||||
"$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
|
||||
if: runner.os != 'Windows' && runner.environment == 'github-hosted'
|
||||
id: memray-python
|
||||
with: { python-version: "3.12", update-environment: false }
|
||||
- name: Install memray for the Python profiler tests
|
||||
# Self-hosted runners have no setup-python; without MEMRAY_PYTHON those tests return early.
|
||||
if: steps.memray-python.outputs.python-path != ''
|
||||
shell: bash
|
||||
env:
|
||||
PYTHON: ${{ steps.memray-python.outputs.python-path }}
|
||||
run: |
|
||||
"$PYTHON" -m venv "$RUNNER_TEMP/memray-venv"
|
||||
"$RUNNER_TEMP/memray-venv/bin/python" -m pip install memray==1.21.0
|
||||
echo "MEMRAY_PYTHON=$RUNNER_TEMP/memray-venv/bin/python" >> "$GITHUB_ENV"
|
||||
- run: cargo nextest run --workspace --no-fail-fast
|
||||
- name: Remote backend with Docker Compose
|
||||
# Self-hosted runner containers do not mount /var/run/docker.sock (scripts/selfhost-runner/README.md).
|
||||
if: runner.os == 'Linux' && runner.environment != 'self-hosted'
|
||||
run: |
|
||||
docker pull busybox:latest
|
||||
cargo nextest run -p ide-host --test remote_daemon --run-ignored only \
|
||||
-E 'test(=compose_service_survives_disconnect_and_is_removed_on_stop)'
|
||||
# --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(=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
|
||||
@@ -258,7 +292,9 @@ jobs:
|
||||
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
|
||||
|
||||
@@ -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:
|
||||
@@ -190,12 +209,12 @@ jobs:
|
||||
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' }}
|
||||
@@ -208,7 +227,8 @@ jobs:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
# 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
|
||||
with: { name: smoke-bin }
|
||||
@@ -223,11 +243,11 @@ jobs:
|
||||
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'
|
||||
- if: contains(matrix.group.languages, 'python')
|
||||
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.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'
|
||||
- if: contains(matrix.group.languages, 'go')
|
||||
uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.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'
|
||||
- if: contains(matrix.group.languages, 'java') || contains(matrix.group.languages, 'kotlin')
|
||||
uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
|
||||
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'
|
||||
- if: contains(matrix.group.languages, 'kotlin')
|
||||
uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
|
||||
with: { gradle-version: "${{ env.GRADLE }}" }
|
||||
- if: matrix.language == 'kotlin'
|
||||
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"
|
||||
@@ -47,6 +47,7 @@ jobs:
|
||||
environment: release
|
||||
env:
|
||||
OPENIDEA_OFFICIAL_PLUGIN_KEYS: ${{ needs.plugin-keys.outputs.keys }}
|
||||
OPENIDEA_BUILD: ${{ github.sha }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
|
||||
@@ -27,6 +27,7 @@ dist-ssr
|
||||
|
||||
# Rust
|
||||
target/
|
||||
!/crates/ide-ssh/src/target/
|
||||
# Tauri generated schemas
|
||||
/src-tauri/gen/schemas
|
||||
*.tsbuildinfo
|
||||
|
||||
+3
-1
@@ -122,7 +122,9 @@ Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
|
||||
- `pnpm build` — typecheck + bundle frontend.
|
||||
- `pnpm dogfood:local [--build-only]` (or `mise run dogfood:local`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
|
||||
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
|
||||
- `pnpm dogfood:all <remote_name> [--restart | --no-restart]` (or `mise run dogfood:all <remote_name>`) — run `dogfood:local` and `dogfood:remote <remote_name>` in parallel.
|
||||
- `pnpm dogfood:servers [all | x86_64 | aarch64]` (or `mise run dogfood:servers ...`) — cross-build and locally stage Linux `openidea-server` binaries with Zig.
|
||||
- `pnpm dogfood:all [all | x86_64 | aarch64] [--build-only]` (or `mise run dogfood:all ...`) — run `dogfood:local` and `dogfood:servers` in parallel, without requiring an SSH host;
|
||||
`dogfood:all <remote_name> [--restart | --no-restart]` runs `dogfood:local` and `dogfood:remote <remote_name>` in parallel instead.
|
||||
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
|
||||
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
|
||||
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
|
||||
|
||||
Створено
+110
-159
@@ -104,12 +104,6 @@ version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
||||
|
||||
[[package]]
|
||||
name = "ambient-authority"
|
||||
version = "0.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b"
|
||||
|
||||
[[package]]
|
||||
name = "android_system_properties"
|
||||
version = "0.1.6"
|
||||
@@ -775,24 +769,6 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cap-primitives"
|
||||
version = "4.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18"
|
||||
dependencies = [
|
||||
"ambient-authority",
|
||||
"fs-set-times",
|
||||
"io-extras",
|
||||
"io-lifetimes 3.0.1",
|
||||
"ipnet",
|
||||
"maybe-owned",
|
||||
"rustix",
|
||||
"rustix-linux-procfs",
|
||||
"windows-sys 0.61.2",
|
||||
"winx",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cargo-platform"
|
||||
version = "0.3.3"
|
||||
@@ -1202,27 +1178,27 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-assembler-x64"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c19fba13ee427c4dd29488ea51127e945bf07fd9d79093f14c9cc57f74acf757"
|
||||
checksum = "1e3f0670397b48cb1ac491069afd5229a7bac64eb6102c285f1185d56a2d1982"
|
||||
dependencies = [
|
||||
"cranelift-assembler-x64-meta",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-assembler-x64-meta"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dd88c766346fcc14bbadbd68cb11e9bc1e555e99f7e8f6b1f4c27a73ca659bec"
|
||||
checksum = "fb3c47010315916ed3cb3ad200a2f6762e653c9efb295e756732890ee5c3a772"
|
||||
dependencies = [
|
||||
"cranelift-srcgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-bforest"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f19d43d75dd963d6b1a653f2e03d4eed4365ca2e598ec57e52c15afdad6c3276"
|
||||
checksum = "31966de669d154078a789193b7be55db68e767f302119aa6d5f6c9eb307351ea"
|
||||
dependencies = [
|
||||
"cranelift-entity",
|
||||
"wasmtime-internal-core",
|
||||
@@ -1230,9 +1206,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-bitset"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "45d0b93e50856858c89c61cbe3f6d4b07596da22eb5a03a95b19420e1d08a275"
|
||||
checksum = "f7fb2cb0d1e8551fa2cc98dd1b4c34c33f0a9c62170fcf2321a81d4b3ce1122f"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_derive",
|
||||
@@ -1241,9 +1217,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-codegen"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "efbdff32d3b6b4f33f1ba8a4ac747b97ce569b1d6834c3089c1c0933b94e618c"
|
||||
checksum = "380a92c92c3532dccdc76d6aaede0d1e44bfd7e564b57ba7c594769138d4a7cd"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"cranelift-assembler-x64",
|
||||
@@ -1272,9 +1248,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-codegen-meta"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67fd11ff24916a2c1ff852ce4bb664fcf2c2970ed551de44dd5b573321123703"
|
||||
checksum = "2f516745d087302bc038d41ee3e6a440270ec499b99aff997de08c980077c3be"
|
||||
dependencies = [
|
||||
"cranelift-assembler-x64-meta",
|
||||
"cranelift-codegen-shared",
|
||||
@@ -1285,24 +1261,24 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-codegen-shared"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba5d321229c3e00a17d7bb3633529ffdf97a13bcf4962fd2e92f1e0fd39360aa"
|
||||
checksum = "3cc33acbe213c870f12a8533f063e00bce075155492506f342ac0105603acbee"
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-control"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "71cd63450256d0f80f7a0527e133452f84fa6e1ca73c7db6ca2a9e8cc89d1c18"
|
||||
checksum = "c1c425eefbef5e5c94464f827cbe44db138f372b25d8613df829002226a1f540"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-entity"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "18d2f259130db1bbb89500d26944971a9beeb410de91ff14039203f055d7f9f0"
|
||||
checksum = "3329ddee61c0af3e8c040b68e336a85d1c48eafb05461318359823366a231a9c"
|
||||
dependencies = [
|
||||
"cranelift-bitset",
|
||||
"serde",
|
||||
@@ -1312,9 +1288,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-frontend"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf37a38d982d45fe2c065d55e4de76e596b443b6acceb3ca726c2072c8ba6d7b"
|
||||
checksum = "2b5c35b9f2ca742b49837ff9eaaccbd0889ce98bdfdc94655e09308040bd2378"
|
||||
dependencies = [
|
||||
"cranelift-codegen",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -1325,26 +1301,27 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-isle"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ce8f84e2d44326879e18016d763457a2cb5d775e4a5822cd7473fc171fca063"
|
||||
checksum = "def117e190cbbfcdc21b6f6bf16a9e72e1c4161d3e24bf0325162e005342e6ef"
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-native"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df64a0392edac7b38fb2965ce8e205e7c5e219e4c531ed3cd1929c782f21853d"
|
||||
checksum = "3f141d6357c868a4baa8764a7965a614f044818d6a36d5aeea2b9df572bce4d9"
|
||||
dependencies = [
|
||||
"cranelift-codegen",
|
||||
"libc",
|
||||
"mach2",
|
||||
"target-lexicon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-srcgen"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3748e3c77c0717359cd4c089e1dc057221eb8598a9c18b0b5afccb5685975abb"
|
||||
checksum = "edc821d1689091a9277e0638a6463d8a013cb1f5cae5d5e68b8582feef7b2e3a"
|
||||
|
||||
[[package]]
|
||||
name = "crc"
|
||||
@@ -2387,17 +2364,6 @@ dependencies = [
|
||||
"num",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs-set-times"
|
||||
version = "0.20.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
|
||||
dependencies = [
|
||||
"io-lifetimes 2.0.4",
|
||||
"rustix",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs_extra"
|
||||
version = "1.3.0"
|
||||
@@ -4287,6 +4253,7 @@ dependencies = [
|
||||
name = "ide-coverage"
|
||||
version = "0.1.57"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
"quick-xml 0.42.0",
|
||||
@@ -4555,6 +4522,7 @@ name = "ide-http"
|
||||
version = "0.1.57"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"encoding_rs",
|
||||
"http",
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
@@ -4722,6 +4690,7 @@ dependencies = [
|
||||
"ide-sdk",
|
||||
"ide-text",
|
||||
"ide-vfs",
|
||||
"ide-workspace",
|
||||
"ignore",
|
||||
"lsp-types",
|
||||
"parking_lot 0.12.5",
|
||||
@@ -5285,28 +5254,6 @@ dependencies = [
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "io-extras"
|
||||
version = "0.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
|
||||
dependencies = [
|
||||
"io-lifetimes 3.0.1",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "io-lifetimes"
|
||||
version = "2.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983"
|
||||
|
||||
[[package]]
|
||||
name = "io-lifetimes"
|
||||
version = "3.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96"
|
||||
|
||||
[[package]]
|
||||
name = "ipnet"
|
||||
version = "2.12.2"
|
||||
@@ -5904,12 +5851,6 @@ dependencies = [
|
||||
"regex-automata",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "maybe-owned"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.11.0"
|
||||
@@ -7177,9 +7118,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe"
|
||||
|
||||
[[package]]
|
||||
name = "piper"
|
||||
@@ -7466,9 +7407,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pulley-interpreter"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "99ecf828c291348e4066f8e45bf37c35ea6012b07a9201e7911c21f03ad1af3e"
|
||||
checksum = "8345a00a393704a3195710f11800eb86a35ddee962cc2051eb20a0bb40da594d"
|
||||
dependencies = [
|
||||
"cranelift-bitset",
|
||||
"log",
|
||||
@@ -7478,13 +7419,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pulley-macros"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20e35ece122b2e8bbd7ea9db0709b3d32f20555b73985efc3eaf6afa4ef2ecdf"
|
||||
checksum = "7856bc0bfba6621c0419f482e87be915201b8d14cedd5d5ec8c793c266c43251"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -11076,19 +11017,29 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f64765e43c000fae008a48db8b288e175e237fc9ce20a26586836878c1bee89f"
|
||||
dependencies = [
|
||||
"leb128fmt",
|
||||
"wasmparser",
|
||||
"wasmparser 0.258.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-encoder"
|
||||
version = "0.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b883a26aea02eaabe2d2c3fba7eb039ef5cdcb5d5201ae5551e73d5e251a81f"
|
||||
dependencies = [
|
||||
"leb128fmt",
|
||||
"wasmparser 0.263.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-metadata"
|
||||
version = "0.258.3"
|
||||
version = "0.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47e10808eb27efde692f1b1706089fe19296728bf872291f5b4e0d50fba88f2f"
|
||||
checksum = "8997a297f42413bee775d73a750def062ee1ec4a6d904703cb08046c0296774d"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"indexmap 2.14.2",
|
||||
"wasm-encoder",
|
||||
"wasmparser",
|
||||
"wasm-encoder 0.263.0",
|
||||
"wasmparser 0.263.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -11109,6 +11060,17 @@ name = "wasmparser"
|
||||
version = "0.258.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe9269dd817e0e7021bf534ccd9761bc2d64778b6708e41228b8439d75eaa0b1"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"indexmap 2.14.2",
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmparser"
|
||||
version = "0.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4f5fa0a054ae153606df820eb0a84213e28cda41bbe04ba2628e71b6ba100fcb"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -11119,20 +11081,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmprinter"
|
||||
version = "0.258.3"
|
||||
version = "0.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "14a457ba8670a3db3d357c1aeac3ed4fe378a76054a221789f0df0ea507e292b"
|
||||
checksum = "b40c3aedc383a68866a7bae302578765c3f05c9e11ea6d242e5cc450f8300a26"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"termcolor",
|
||||
"wasmparser",
|
||||
"wasmparser 0.263.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "263d6a66a772efff2c98a1aa367e8e61dae32d2ecf95f85f4776733762322aa7"
|
||||
checksum = "4fe4d7f7bae504c067d5eaf3c990f706f416d9aba0c86fbd17f69aa1625514c9"
|
||||
dependencies = [
|
||||
"addr2line",
|
||||
"async-trait",
|
||||
@@ -11141,6 +11103,7 @@ dependencies = [
|
||||
"cc",
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
"indexmap 2.14.2",
|
||||
"libc",
|
||||
"log",
|
||||
"mach2",
|
||||
@@ -11156,7 +11119,7 @@ dependencies = [
|
||||
"serde_derive",
|
||||
"smallvec",
|
||||
"target-lexicon",
|
||||
"wasmparser",
|
||||
"wasmparser 0.263.0",
|
||||
"wasmtime-environ",
|
||||
"wasmtime-internal-component-macro",
|
||||
"wasmtime-internal-component-util",
|
||||
@@ -11172,9 +11135,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-environ"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5f2f0898bedc77f110dca6f70394780f89af68a8ca19e12559ee73d4187a6fe9"
|
||||
checksum = "e121151e0fd47b956f9b6bc7959a0a48e10e4947ef133515073a7c3a952845f8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"cpp_demangle",
|
||||
@@ -11191,11 +11154,10 @@ dependencies = [
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"sha2 0.10.9",
|
||||
"smallvec",
|
||||
"target-lexicon",
|
||||
"wasm-encoder",
|
||||
"wasmparser",
|
||||
"wasm-encoder 0.263.0",
|
||||
"wasmparser 0.263.0",
|
||||
"wasmprinter",
|
||||
"wasmtime-internal-component-util",
|
||||
"wasmtime-internal-core",
|
||||
@@ -11203,14 +11165,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-component-macro"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b140c28283bd2255a4bb8834621f7200bbe7581cbca91d803b5ba4adf9119a5e"
|
||||
checksum = "ef79e1caafa01f06dc80d2c2125b80ee0a80ce4e429c2a5060d9c7efa0929c59"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"syn 3.0.9",
|
||||
"wasmtime-internal-component-util",
|
||||
"wasmtime-internal-wit-bindgen",
|
||||
"wit-parser",
|
||||
@@ -11218,15 +11180,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-component-util"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "853075a197694ba7f0749e7af78b59e12c0956dff5b16dafbfc49c3b90cdbc93"
|
||||
checksum = "56db007f81976ef523c554928318e1ec5cb1e65247f9c964a9f223cab063d99e"
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-core"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e13ab3aa598d863643ef9ec043d63fde7effca4465270446d5b868936b27a6"
|
||||
checksum = "07cb09d8608a4343c2f039f4ed8ef734c08733887e5e50a19711668c324a1efd"
|
||||
dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
"libm",
|
||||
@@ -11235,9 +11197,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-cranelift"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "660103cff91df46f9f06568f3889b8b59a6ae0f56756abfcc002a0a69974cc9f"
|
||||
checksum = "158d190d15edb4baec25ea293c79b905b389c2354fccc6a59ae31974a30f024c"
|
||||
dependencies = [
|
||||
"cranelift-codegen",
|
||||
"cranelift-control",
|
||||
@@ -11252,7 +11214,7 @@ dependencies = [
|
||||
"smallvec",
|
||||
"target-lexicon",
|
||||
"thiserror 2.0.21",
|
||||
"wasmparser",
|
||||
"wasmparser 0.263.0",
|
||||
"wasmtime-environ",
|
||||
"wasmtime-internal-core",
|
||||
"wasmtime-internal-unwinder",
|
||||
@@ -11261,9 +11223,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-fiber"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4d0e958516bdf283b83015283774e11c86b66f2f4bd7d2ea52e9799fa59cddb"
|
||||
checksum = "a9ac783ac0c8a20cf1bf1a33599345ed62dc8e7bddfa2929cedb68aa0722ec2f"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
@@ -11275,9 +11237,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-jit-debug"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad61b1e661871bb7d11b5543202a05c44ed8682806b438f68ced629a22719463"
|
||||
checksum = "2153e59eefff0626431d2c8eea389db01b3e10fcaeaf17a1c034772213902d73"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"wasmtime-internal-versioned-export-macros",
|
||||
@@ -11285,9 +11247,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-jit-icache-coherence"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52c641b9e1bab449c7316896f01d4a0c426e2a502a5a8098e1af4a0392053e7a"
|
||||
checksum = "25b5537454e038b22b38404f9efacb376fa65957064e5b39dff6b044ed46e007"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"wasmtime-internal-core",
|
||||
@@ -11296,9 +11258,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-unwinder"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "03303a9abd333edcbd44fee3b1e0905ad156d3bcec311323d061cdff92e7d1f3"
|
||||
checksum = "2f4f72e4d5be23320ee4dd70c8020e6ce861a0fb2851e91be91cbc842debddf8"
|
||||
dependencies = [
|
||||
"cranelift-codegen",
|
||||
"log",
|
||||
@@ -11308,20 +11270,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-versioned-export-macros"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8db0c7f417e5ca3ba92d127d17b980529455d01c141be99204e6d309630c42de"
|
||||
checksum = "1af2217d501904ce9f9e1771bde6633ddb3c717d5dbef57c994f96acadb7a030"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-wit-bindgen"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6292ee4f797f9befb64aa2b3477ec8576501d6302ec21fd2785a8d3f94cf8717"
|
||||
checksum = "b9d9a611c2a63d553eee62a0555114ab221c54ae30d08d50b92f2ac2e449baa7"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags 2.13.2",
|
||||
@@ -11333,15 +11295,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-wasi"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3175ff29e2992269f51ec372f7757941f11f87b265a614761726960d42ef6e4d"
|
||||
checksum = "a5099e3b95d50c5c7998da4ca0c9c25402dd865e45386690a9a40add3f575011"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bitflags 2.13.2",
|
||||
"bytes",
|
||||
"cap-primitives",
|
||||
"futures",
|
||||
"libc",
|
||||
"rand 0.10.3",
|
||||
"rustix",
|
||||
"rustix-linux-procfs",
|
||||
@@ -11352,14 +11314,13 @@ dependencies = [
|
||||
"wasmtime",
|
||||
"wasmtime-wasi-io",
|
||||
"windows-sys 0.61.2",
|
||||
"winx",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-wasi-io"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bb561839e32b61bf0cdd51efe3874fac5de1bd5775a5b7c41bdf70993e367ea"
|
||||
checksum = "ad8ac873113e37bf22bbd58523ea82d45591eeb4f71e06809534d3950345718c"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes",
|
||||
@@ -11378,7 +11339,7 @@ dependencies = [
|
||||
"leb128fmt",
|
||||
"memchr",
|
||||
"unicode-width",
|
||||
"wasm-encoder",
|
||||
"wasm-encoder 0.258.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -12057,16 +12018,6 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winx"
|
||||
version = "0.36.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.57.1"
|
||||
@@ -12075,9 +12026,9 @@ checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
|
||||
|
||||
[[package]]
|
||||
name = "wit-component"
|
||||
version = "0.258.3"
|
||||
version = "0.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0fca88950af0c1f42bc77e17315e48798b8d68340171b6d204f62bc19a878a6"
|
||||
checksum = "4189bd180353b942b788715519dff886517b540e648c6f6e5129f57429945bf7"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags 2.13.2",
|
||||
@@ -12086,17 +12037,17 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"wasm-encoder",
|
||||
"wasm-encoder 0.263.0",
|
||||
"wasm-metadata",
|
||||
"wasmparser",
|
||||
"wasmparser 0.263.0",
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-parser"
|
||||
version = "0.258.3"
|
||||
version = "0.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72a2127663dcf3ee16614fb0e3c33d5c6c66fec9dad317a8b0fdd3869487a533"
|
||||
checksum = "874d6ce9db4261cb66980ab14f3da066b24292497b6f46f988c0d1b9b27913f3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -12108,7 +12059,7 @@ dependencies = [
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"unicode-ident",
|
||||
"wasmparser",
|
||||
"wasmparser 0.263.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -80,6 +80,8 @@ fn client_capabilities() -> Value {
|
||||
"subagents": {},
|
||||
// Forms the agent asks the user to fill in (`elicitation/create`); not URL mode.
|
||||
"elicitation": { "form": {} },
|
||||
// Ghost-text next-prompt suggestions (`prompt_suggestions_update`).
|
||||
"session": { "promptSuggestions": {} },
|
||||
// Cursor exposes model parameters (e.g. Composer `fast`) as separate config options
|
||||
// only when the client advertises this flag (undocumented Cursor ACP extension).
|
||||
"_meta": { "parameterizedModelPicker": true },
|
||||
@@ -94,7 +96,7 @@ pub(crate) fn initialize_params(client_info: &Value) -> Value {
|
||||
json!({
|
||||
"protocolVersion": 2,
|
||||
"info": client_info,
|
||||
"capabilities": {},
|
||||
"capabilities": { "session": { "promptSuggestions": {} } },
|
||||
"clientCapabilities": client_capabilities(),
|
||||
"clientInfo": client_info,
|
||||
})
|
||||
@@ -359,7 +361,7 @@ impl Handler for Dialect {
|
||||
|
||||
fn on_request_raw(&self, method: &str, params: Value, raw: &[u8]) -> Result<Value, (i64, String, Option<Value>)> {
|
||||
if self.v2() && method == "session/request_permission" {
|
||||
return self.on_request_with_data(method, params);
|
||||
return self.inner.on_request_raw(method, v1_permission_request(params), raw);
|
||||
}
|
||||
self.inner.on_request_raw(method, params, raw)
|
||||
}
|
||||
|
||||
@@ -133,11 +133,14 @@ fn the_negotiating_request_carries_both_versions() {
|
||||
);
|
||||
// Forms only: URL mode would open pages the agent names.
|
||||
assert_eq!(p["clientCapabilities"]["elicitation"], json!({ "form": {} }));
|
||||
assert_eq!(p["clientCapabilities"]["session"], json!({ "promptSuggestions": {} }));
|
||||
assert_eq!(p["capabilities"]["session"], json!({ "promptSuggestions": {} }));
|
||||
// What we sent in the capture is what claude-agent-acp negotiated v2 and v1 from.
|
||||
let sent = frames(TURN, "out")[0]["params"]["clientCapabilities"].clone();
|
||||
let mut expected = sent;
|
||||
expected["_meta"] = p["clientCapabilities"]["_meta"].clone();
|
||||
expected["elicitation"] = p["clientCapabilities"]["elicitation"].clone();
|
||||
expected["session"] = p["clientCapabilities"]["session"].clone();
|
||||
assert_eq!(expected, p["clientCapabilities"]);
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -10,6 +10,7 @@ use crate::model::AgentEntry;
|
||||
use crate::timeline::{Timeline, blocks_text, content_text};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// Where an entry lives: the task's own conversation (`None`) or a subagent's session.
|
||||
pub(crate) type Session = Option<String>;
|
||||
@@ -107,7 +108,7 @@ impl Conversation {
|
||||
out.push((parent, index));
|
||||
if stopped && let Some(child) = self.timeline_mut(&Some(id.to_owned())) {
|
||||
let id = Some(id.to_owned());
|
||||
out.extend(child.end_turn(None).into_iter().map(|i| (id.clone(), i)));
|
||||
out.extend(child.end_turn(None, &HashSet::new()).into_iter().map(|i| (id.clone(), i)));
|
||||
}
|
||||
}
|
||||
"session_message" | "session_message_chunk" => {
|
||||
@@ -169,18 +170,20 @@ impl Conversation {
|
||||
self.subagents.retain(|_| keep.next().unwrap_or(true));
|
||||
}
|
||||
|
||||
/// Settles what an ended turn of the task left open. Subagents work on (in the background).
|
||||
pub fn end_turn(&mut self, done: Option<f64>) -> Vec<(Session, usize)> {
|
||||
self.main.end_turn(done).into_iter().map(|i| (None, i)).collect()
|
||||
/// Settles what an ended turn of the task left open. Subagents work on (in the background),
|
||||
/// and the requests in `open`, which they asked, stay open.
|
||||
pub fn end_turn(&mut self, done: Option<f64>, open: &HashSet<u32>) -> Vec<(Session, usize)> {
|
||||
self.main.end_turn(done, open).into_iter().map(|i| (None, i)).collect()
|
||||
}
|
||||
|
||||
/// Settles everything left open once the agent is gone, subagents included.
|
||||
pub fn settle(&mut self, now: f64) -> Vec<(Session, usize)> {
|
||||
let mut out: Vec<(Session, usize)> = self.main.end_turn(None).into_iter().map(|i| (None, i)).collect();
|
||||
let none = HashSet::new();
|
||||
let mut out: Vec<(Session, usize)> = self.main.end_turn(None, &none).into_iter().map(|i| (None, i)).collect();
|
||||
out.extend(self.main.stop_subagents(now).into_iter().map(|i| (None, i)));
|
||||
for s in &mut self.subagents {
|
||||
let id = Some(s.id.clone());
|
||||
let mut changed = s.timeline.end_turn(None);
|
||||
let mut changed = s.timeline.end_turn(None, &none);
|
||||
changed.extend(s.timeline.stop_subagents(now));
|
||||
out.extend(changed.into_iter().map(|i| (id.clone(), i)));
|
||||
}
|
||||
|
||||
@@ -187,8 +187,14 @@ const STDERR_LINES: usize = 20;
|
||||
/// (`session/load`): the next message starts it again where it left off.
|
||||
const IDLE_RELEASE: Duration = Duration::from_secs(5 * 60);
|
||||
/// Updates of a session's state rather than its conversation.
|
||||
const SESSION_STATE: [&str; 5] =
|
||||
["session_info_update", "config_option_update", "current_mode_update", "available_commands_update", "usage_update"];
|
||||
const SESSION_STATE: [&str; 6] = [
|
||||
"session_info_update",
|
||||
"config_option_update",
|
||||
"current_mode_update",
|
||||
"available_commands_update",
|
||||
"usage_update",
|
||||
"prompt_suggestions_update",
|
||||
];
|
||||
/// A native agent's own update: it is about to retry a failed API request (see [`AgentRetry`]).
|
||||
pub(crate) const RETRY_UPDATE: &str = "openidea_retry";
|
||||
/// A native agent's own update: the usage limits of its account (see [`AgentLimit`]).
|
||||
@@ -1035,8 +1041,8 @@ struct Task {
|
||||
connecting: tokio::sync::Mutex<()>,
|
||||
/// Serializes replies from multiple windows to the same async question.
|
||||
answering_questions: tokio::sync::Mutex<()>,
|
||||
/// Unanswered permission requests: where to send the chosen option id.
|
||||
permissions: Mutex<HashMap<u32, std::sync::mpsc::Sender<Option<String>>>>,
|
||||
/// Unanswered permission requests and forms, by the `id` of their `AgentEntry::Permission`.
|
||||
permissions: Mutex<HashMap<u32, PendingRequest>>,
|
||||
next_permission: AtomicU32,
|
||||
/// Set while `session/load` replays the session's history.
|
||||
replaying: AtomicBool,
|
||||
@@ -1091,6 +1097,16 @@ struct Task {
|
||||
file: Mutex<SavedFile>,
|
||||
}
|
||||
|
||||
/// A request of the agent that waits for the user.
|
||||
struct PendingRequest {
|
||||
/// The session it was asked for: the task's own (`None`) or a subagent's.
|
||||
session: Session,
|
||||
/// Its JSON-RPC id, which the agent names to withdraw it.
|
||||
rpc_id: Option<Value>,
|
||||
/// Where to send the chosen option id; `None` cancels the request.
|
||||
reply: std::sync::mpsc::Sender<Option<String>>,
|
||||
}
|
||||
|
||||
/// What the task's file on disk holds.
|
||||
#[derive(Default)]
|
||||
struct SavedFile {
|
||||
@@ -1694,6 +1710,7 @@ impl AgentManager {
|
||||
unread: false,
|
||||
recovery_window_mins: None,
|
||||
automation: None,
|
||||
prompt_suggestions: Box::default(),
|
||||
};
|
||||
let file = TaskFile {
|
||||
task: task.clone(),
|
||||
@@ -1791,6 +1808,7 @@ impl AgentManager {
|
||||
unread: false,
|
||||
recovery_window_mins: None,
|
||||
automation: None,
|
||||
prompt_suggestions: Box::default(),
|
||||
};
|
||||
let file = TaskFile {
|
||||
task: task.clone(),
|
||||
@@ -1879,10 +1897,21 @@ impl AgentManager {
|
||||
)));
|
||||
}
|
||||
let dir = self.shared.paths.worktrees_dir.clone();
|
||||
let (t, b, task_id) = (title.clone(), req.base.clone(), id.clone());
|
||||
let c = vcs(&self.shared, move || worktree::create_for_task(&root, &dir, &task_id, &t, b.as_deref()))
|
||||
if let Some(wt_path) = req.worktree_path.map(|p| p.0) {
|
||||
let (c, before) = vcs(&self.shared, move || {
|
||||
let c = worktree::reuse_for_task(&root, &dir, &wt_path)?;
|
||||
let before = worktree::snapshot(&c.cwd).unwrap_or_default();
|
||||
Ok((c, before))
|
||||
})
|
||||
.await?;
|
||||
(c.cwd, Some(c.branch), Some(c.base), Some(c.base_commit), BTreeMap::new())
|
||||
(c.cwd, Some(c.branch), Some(c.base), Some(c.base_commit), before)
|
||||
} else {
|
||||
let (t, b, task_id) = (title.clone(), req.base.clone(), id.clone());
|
||||
let c =
|
||||
vcs(&self.shared, move || worktree::create_for_task(&root, &dir, &task_id, &t, b.as_deref()))
|
||||
.await?;
|
||||
(c.cwd, Some(c.branch), Some(c.base), Some(c.base_commit), BTreeMap::new())
|
||||
}
|
||||
}
|
||||
Isolation::Local => {
|
||||
let r = root.clone();
|
||||
@@ -1977,6 +2006,7 @@ impl AgentManager {
|
||||
unread: false,
|
||||
recovery_window_mins: None,
|
||||
automation: automation_meta.clone().map(Box::new),
|
||||
prompt_suggestions: Box::default(),
|
||||
};
|
||||
let initial_scheduled = automation_meta.as_ref().map(|m| ScheduledTurnMeta {
|
||||
permissions: m.permissions,
|
||||
@@ -2081,6 +2111,7 @@ impl AgentManager {
|
||||
} else {
|
||||
let epoch = self.shared.shutdown_epoch();
|
||||
s.busy = true;
|
||||
s.task.prompt_suggestions.clear();
|
||||
s.pending_prompt = Some(prompt.clone());
|
||||
s.active_scheduled_turn = scheduled.clone();
|
||||
// A run watcher reads the status before the spawned turn shows its prompt, and
|
||||
@@ -2397,7 +2428,7 @@ impl AgentManager {
|
||||
let mcp_servers = source.shared.mcp_servers_for_session(&base_id, &live.init, &mcp_overrides, None);
|
||||
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
|
||||
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
|
||||
let memory_delivery = source.stage_memory(&base_id, &cwd).await;
|
||||
let memory_delivery = source.memory_delivery(live.driver, &base_id);
|
||||
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
|
||||
let reply: Value = live
|
||||
.peer
|
||||
@@ -2450,6 +2481,7 @@ impl AgentManager {
|
||||
interrupted: None,
|
||||
unread: false,
|
||||
automation: None,
|
||||
prompt_suggestions: Box::default(),
|
||||
..s.task.clone()
|
||||
};
|
||||
let (session, cut) = match session {
|
||||
@@ -2533,6 +2565,7 @@ impl AgentManager {
|
||||
s.history.conversation = Conversation::default();
|
||||
// The fresh session reports its own usage; nothing carries over.
|
||||
s.task.usage = None;
|
||||
s.task.prompt_suggestions.clear();
|
||||
s.pending_rollback = 0;
|
||||
s.task.updated_ms = now_ms();
|
||||
Self::finish_rewind(&mut s, 0, restamped);
|
||||
@@ -2565,6 +2598,7 @@ impl AgentManager {
|
||||
_ => None,
|
||||
};
|
||||
s.history.conversation.truncate(cut);
|
||||
s.task.prompt_suggestions.clear();
|
||||
s.task.updated_ms = now_ms();
|
||||
Self::finish_rewind(&mut s, turns as usize, restamped);
|
||||
(first, task.turn_dir(), s.history.turns.clone())
|
||||
@@ -2688,7 +2722,7 @@ impl AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops the current turn (`session/cancel`); pending permission requests are cancelled.
|
||||
/// Stops the current turn (`session/cancel`); its pending requests are cancelled.
|
||||
/// Queued messages stay queued. With `subagent`, stops only that subagent's work.
|
||||
pub fn cancel(&self, id: &str, subagent: Option<String>) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
@@ -2698,6 +2732,7 @@ impl AgentManager {
|
||||
if let Some(live) = task.live.lock().clone() {
|
||||
let _ = live.peer.notify("session/cancel", json!({ "sessionId": sub }));
|
||||
}
|
||||
task.cancel_requests_of(&Some(sub));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -3035,8 +3070,8 @@ impl AgentManager {
|
||||
let task = self.task(id)?;
|
||||
let pending = task.permissions.lock().remove(&permission);
|
||||
match pending {
|
||||
Some(reply) => {
|
||||
let _ = reply.send(option);
|
||||
Some(request) => {
|
||||
let _ = request.reply.send(option);
|
||||
Ok(())
|
||||
}
|
||||
None => Err(IdeError::not_found("the request was already answered")),
|
||||
@@ -3291,7 +3326,12 @@ impl AgentManager {
|
||||
if isolation != Isolation::Worktree || busy || !cwd.exists() {
|
||||
return Ok(false);
|
||||
}
|
||||
let shared = self.tasks.read().values().any(|t| t.id != id && t.state.lock().task.cwd.0 == cwd);
|
||||
let target_root = worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &cwd);
|
||||
let shared = self.tasks.read().values().any(|t| {
|
||||
t.id != id
|
||||
&& worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &t.state.lock().task.cwd.0)
|
||||
== target_root
|
||||
});
|
||||
if shared {
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -3327,6 +3367,139 @@ impl AgentManager {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Checks out (or creates and checks out) a Git branch in an idle task's working directory.
|
||||
/// Rejects archived tasks, untrusted local repos, or checkouts where this task or any sibling
|
||||
/// sharing the same worktree/repo is busy. Holds `BusyGuard` across the checkout to prevent
|
||||
/// concurrent turns/checkouts, and updates `task.branch` (plus `base`/`base_commit` when
|
||||
/// switching to an existing branch) for all worktree tasks sharing the checkout.
|
||||
pub async fn checkout_branch(&self, id: &str, branch: &str, create: bool) -> IdeResult<ide_vcs::CheckoutOutcome> {
|
||||
if !git_enabled(&self.shared) {
|
||||
return Err(IdeError::invalid("Git is disabled for this project"));
|
||||
}
|
||||
let task = self.task(id)?;
|
||||
let (isolation, raw_cwd) = {
|
||||
let s = task.state.lock();
|
||||
if s.task.status == AgentStatus::Archived {
|
||||
return Err(IdeError::invalid("cannot switch branches on an archived task"));
|
||||
}
|
||||
if s.busy || matches!(s.task.status, AgentStatus::Starting | AgentStatus::Running | AgentStatus::NeedsInput)
|
||||
{
|
||||
return Err(IdeError::invalid("stop the current turn before switching branches"));
|
||||
}
|
||||
(s.task.isolation, s.task.cwd.0.clone())
|
||||
};
|
||||
let cwd = if isolation == Isolation::Worktree {
|
||||
task.verify_worktree_cwd_confined()?
|
||||
} else {
|
||||
if let Some(repo) = Repo::discover(&raw_cwd)? {
|
||||
let canon_repo = dunce::canonicalize(repo.root())?;
|
||||
if let Some(check) = self.shared.repo_trust.read().clone()
|
||||
&& !check(&canon_repo)
|
||||
{
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Git repository {} is not trusted: trust the repository root before switching branches",
|
||||
canon_repo.display()
|
||||
)));
|
||||
}
|
||||
}
|
||||
raw_cwd
|
||||
};
|
||||
let local_repo_key = if isolation == Isolation::Local {
|
||||
Repo::discover(&cwd)?.and_then(|r| dunce::canonicalize(r.root()).ok()).map(worktree::normalize_path_key)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let wt_root_key = if isolation == Isolation::Worktree {
|
||||
Some(worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &cwd))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Collect all tasks sharing this checkout in deterministic BTreeMap ID order and acquire
|
||||
// BusyGuard on every one so concurrent turns, rollbacks, or checkouts cannot race.
|
||||
let (group, guards) = {
|
||||
let tasks = self.tasks.read();
|
||||
let mut group = Vec::new();
|
||||
let mut guards = Vec::new();
|
||||
for other in tasks.values() {
|
||||
let matches = if other.id == id {
|
||||
true
|
||||
} else {
|
||||
let (other_iso, other_cwd) = {
|
||||
let s = other.state.lock();
|
||||
(s.task.isolation, s.task.cwd.0.clone())
|
||||
};
|
||||
if let Some(ref target_wt) = wt_root_key {
|
||||
worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &other_cwd) == *target_wt
|
||||
} else if other_iso == Isolation::Local
|
||||
&& let Some(ref target_repo) = local_repo_key
|
||||
{
|
||||
Repo::discover(&other_cwd)
|
||||
.ok()
|
||||
.flatten()
|
||||
.and_then(|r| dunce::canonicalize(r.root()).ok())
|
||||
.map(worktree::normalize_path_key)
|
||||
.as_ref()
|
||||
== Some(target_repo)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
};
|
||||
if !matches {
|
||||
continue;
|
||||
}
|
||||
let mut s = other.state.lock();
|
||||
if other.id == id && s.task.status == AgentStatus::Archived {
|
||||
return Err(IdeError::invalid("cannot switch branches on an archived task"));
|
||||
}
|
||||
if s.busy
|
||||
|| matches!(s.task.status, AgentStatus::Starting | AgentStatus::Running | AgentStatus::NeedsInput)
|
||||
{
|
||||
return Err(IdeError::invalid(if other.id == id {
|
||||
"stop the current turn before switching branches"
|
||||
} else {
|
||||
"another task sharing this checkout is currently running"
|
||||
}));
|
||||
}
|
||||
s.busy = true;
|
||||
guards.push(BusyGuard(other.clone()));
|
||||
group.push(other.clone());
|
||||
}
|
||||
(group, guards)
|
||||
};
|
||||
let branch = branch.to_owned();
|
||||
let (current, head_commit, outcome) =
|
||||
vcs(&self.shared, move || worktree::checkout_branch(&cwd, &branch, create)).await?;
|
||||
let switched = matches!(
|
||||
outcome,
|
||||
ide_vcs::CheckoutOutcome::Done
|
||||
| ide_vcs::CheckoutOutcome::Conflicts { .. }
|
||||
| ide_vcs::CheckoutOutcome::RestoreFailed { .. }
|
||||
);
|
||||
let mut updated = Vec::new();
|
||||
if switched && isolation == Isolation::Worktree {
|
||||
for member in &group {
|
||||
let mut s = member.state.lock();
|
||||
if s.task.isolation != Isolation::Worktree {
|
||||
continue;
|
||||
}
|
||||
s.task.branch = Some(current.clone());
|
||||
if !create {
|
||||
s.task.base = Some(current.clone());
|
||||
if let Some(ref commit) = head_commit {
|
||||
s.task.base_commit = Some(commit.clone());
|
||||
}
|
||||
}
|
||||
updated.push(member.clone());
|
||||
}
|
||||
}
|
||||
drop(guards);
|
||||
for member in updated {
|
||||
member.persist();
|
||||
member.emit_task();
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Forgets the task; with `remove_worktree` also deletes its worktree (the branch stays).
|
||||
pub async fn delete(&self, id: &str, remove_worktree: bool) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
@@ -3339,14 +3512,19 @@ impl AgentManager {
|
||||
s.task.project_root.clone().map(|p| p.0).unwrap_or_else(|| self.shared.paths.project_root.clone()),
|
||||
)
|
||||
};
|
||||
// A copy of the task (a fork) may work in the same worktree.
|
||||
let shared = self.tasks.read().values().any(|t| t.id != id && t.state.lock().task.cwd.0 == cwd);
|
||||
// A copy of the task (a fork) or a task reusing the worktree (even from a subdir) may
|
||||
// work in the same physical worktree checkout root.
|
||||
let target_root = worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &cwd);
|
||||
let shared = self.tasks.read().values().any(|t| {
|
||||
t.id != id
|
||||
&& worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &t.state.lock().task.cwd.0)
|
||||
== target_root
|
||||
});
|
||||
self.tasks.write().remove(id);
|
||||
task.file.lock().deleted = true;
|
||||
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
|
||||
let _ = std::fs::remove_dir_all(task.turn_dir());
|
||||
skills::remove_farm(&self.shared.paths.store_dir, id);
|
||||
memory::remove_farm(&self.shared.paths.store_dir, id);
|
||||
let saved = task.state.lock().saved.clone();
|
||||
if let Some(saved) = saved
|
||||
&& !self.tasks.read().values().any(|t| t.state.lock().saved.as_ref() == Some(&saved))
|
||||
@@ -3730,17 +3908,11 @@ impl AgentManager {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Sets the session's memory overrides (auto-memory mode and per-entry modes); like MCP
|
||||
/// and skill overrides, an idle resumable session recycles so the next turn starts with
|
||||
/// the updated delivery.
|
||||
/// Sets the session's auto-memory override; like MCP and skill overrides, an idle resumable
|
||||
/// session recycles so the next turn starts with the updated delivery.
|
||||
pub fn set_memory_overrides(&self, id: &str, overrides: AgentMemoryOverrides) -> IdeResult<AgentTask> {
|
||||
let task = self.task(id)?;
|
||||
let cleaned_entries: BTreeMap<String, AgentMemoryMode> = overrides
|
||||
.entries
|
||||
.into_iter()
|
||||
.filter_map(|(k, v)| (!k.trim().is_empty()).then(|| (k.trim().to_owned(), v)))
|
||||
.collect();
|
||||
let cleaned = AgentMemoryOverrides { auto_memory: overrides.auto_memory, entries: cleaned_entries };
|
||||
let cleaned = AgentMemoryOverrides { auto_memory: overrides.auto_memory };
|
||||
let next_boxed = (!cleaned.is_empty()).then(|| Box::new(cleaned));
|
||||
let (changed, busy, has_bg, out) = {
|
||||
let mut s = task.state.lock();
|
||||
@@ -3884,42 +4056,17 @@ impl Task {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves and stages the session's memory delivery (`_meta.openidea.memory`).
|
||||
async fn stage_memory(&self, provider: &str, cwd: &Path) -> Option<memory::Delivery> {
|
||||
let (policy, overrides, home, roots) = {
|
||||
let shared = &self.shared;
|
||||
let mut policy = shared.memory_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
|
||||
let (overrides, task_root) = {
|
||||
let s = self.state.lock();
|
||||
(s.task.memory_overrides.as_deref().cloned(), s.task.project_root.as_ref().map(|p| p.0.clone()))
|
||||
};
|
||||
let mut roots = Vec::new();
|
||||
if let Some(tr) = task_root {
|
||||
roots.push(tr);
|
||||
}
|
||||
roots.extend(policy.workspace_roots.iter().cloned());
|
||||
roots.push(shared.paths.project_root.clone());
|
||||
policy.workspace_roots = roots.clone();
|
||||
(policy, overrides, shared.paths.home_dir.clone(), roots)
|
||||
};
|
||||
let farm = memory::farm_dir(&self.shared.paths.store_dir, &self.id);
|
||||
let out_cwd = cwd.to_path_buf();
|
||||
let provider = provider.to_owned();
|
||||
match blocking(move || {
|
||||
let entries = memory::discover_memories(&roots, home.as_deref());
|
||||
let states = memory::resolve_entries(entries, overrides.as_ref(), &policy);
|
||||
let (auto_mode, _) = memory::resolve_provider_auto_memory(&provider, overrides.as_ref(), &policy);
|
||||
memory::stage(&farm, &provider, &states, auto_mode, &out_cwd, home.as_deref())
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(delivery) => Some(delivery),
|
||||
Err(e) => {
|
||||
tracing::warn!("agent task {}: staging its memory failed: {e}", self.id);
|
||||
None
|
||||
}
|
||||
/// Resolves the session's auto-memory delivery (`_meta.openidea.memory`) for native drivers
|
||||
/// that enforce it (`claude`, `codex`).
|
||||
fn memory_delivery(&self, driver: provider::Driver, provider: &str) -> Option<memory::Delivery> {
|
||||
let driver_key = stage_key(driver);
|
||||
if !matches!(driver_key, "claude" | "codex") {
|
||||
return None;
|
||||
}
|
||||
let policy = self.shared.memory_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
|
||||
let overrides = self.state.lock().task.memory_overrides.as_deref().cloned();
|
||||
let (auto_mode, _) = memory::resolve_provider_auto_memory(provider, overrides.as_ref(), &policy);
|
||||
memory::build_delivery(driver_key, auto_mode)
|
||||
}
|
||||
|
||||
/// A task whose conversation is at hand (a new task, a copy).
|
||||
@@ -3944,6 +4091,7 @@ impl Task {
|
||||
/// The task from the parts of `file` other than its history, which `history` holds.
|
||||
fn assemble(file: TaskFile, history: StoredHistory, adopt: bool, shared: Arc<Shared>) -> Arc<Self> {
|
||||
let mut task = file.task;
|
||||
task.prompt_suggestions.clear();
|
||||
config::add_client_options(&shared.base_id(&task.provider), &mut task.config);
|
||||
let mut wanted = file.wanted;
|
||||
let mut pending_model = file.pending_switch.or_else(|| {
|
||||
@@ -4799,7 +4947,7 @@ impl Task {
|
||||
} else if let Some(&delay) = CURSOR_RETRY_DELAYS.get(capacity_retries) {
|
||||
capacity_retries += 1;
|
||||
if self.wait_for_cursor_retry(capacity_retries, delay, epoch).await {
|
||||
let changed = self.state.lock().history.conversation.end_turn(Some(now_ms()));
|
||||
let changed = self.end_turn(&mut self.state.lock(), Some(now_ms()));
|
||||
self.mark_dirty(changed);
|
||||
recovery = Some(InterruptionReason::CursorCapacity);
|
||||
prompt = continuation_prompt_for(InterruptionReason::CursorCapacity);
|
||||
@@ -4832,6 +4980,7 @@ impl Task {
|
||||
// Kill any broken child session before waiting for network to return.
|
||||
if let Some(live) = self.live.lock().take() {
|
||||
live.peer.kill();
|
||||
self.cancel_permissions();
|
||||
}
|
||||
match self.wait_for_network(&failure.message, now_ms(), epoch).await {
|
||||
NetworkWaitOutcome::ShutDown => return,
|
||||
@@ -4844,7 +4993,7 @@ impl Task {
|
||||
}
|
||||
NetworkWaitOutcome::Recovered { forced } => {
|
||||
if forced || self.record_auto_resume_attempt(now_ms()) {
|
||||
let changed = self.state.lock().history.conversation.end_turn(Some(now_ms()));
|
||||
let changed = self.end_turn(&mut self.state.lock(), Some(now_ms()));
|
||||
self.mark_dirty(changed);
|
||||
network_resumes_this_turn += 1;
|
||||
prompt = continuation_prompt_for(InterruptionReason::NetworkTimeout);
|
||||
@@ -4864,7 +5013,7 @@ impl Task {
|
||||
if self.shared.shut_down_since(epoch) {
|
||||
return;
|
||||
}
|
||||
let changed = s.history.conversation.end_turn(Some(now_ms()));
|
||||
let changed = self.end_turn(&mut s, Some(now_ms()));
|
||||
let archived = s.task.status == AgentStatus::Archived;
|
||||
let go_on = !archived
|
||||
&& match &result {
|
||||
@@ -4883,13 +5032,21 @@ impl Task {
|
||||
self.persist_for_epoch(epoch);
|
||||
return;
|
||||
}
|
||||
if let Ok(stop) = &result
|
||||
&& stop == "refusal"
|
||||
{
|
||||
let stopped_early = match &result {
|
||||
Ok(stop) if stop == "refusal" => Some("The agent declined to continue."),
|
||||
Ok(stop) if stop == "max_tokens" => {
|
||||
Some("The reply was cut off: the agent reached its output token limit.")
|
||||
}
|
||||
Ok(stop) if stop == "max_turn_requests" => {
|
||||
Some("The turn stopped: the agent reached its limit of model requests per turn.")
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(message) = stopped_early {
|
||||
if self.shared.shut_down_since(epoch) {
|
||||
return;
|
||||
}
|
||||
self.push_entry(AgentEntry::Error { message: "The agent declined to continue.".into() });
|
||||
self.push_entry(AgentEntry::Error { message: message.into() });
|
||||
}
|
||||
match (next, result) {
|
||||
(Some(queued), _) => {
|
||||
@@ -5115,6 +5272,8 @@ impl Task {
|
||||
/// Drops an idle resumable live session so the next turn reloads it.
|
||||
fn recycle_resumable_session(&self) {
|
||||
self.mcp_reload_pending.store(false, Ordering::Release);
|
||||
self.skills_reload_pending.store(false, Ordering::Release);
|
||||
self.memory_reload_pending.store(false, Ordering::Release);
|
||||
let live = {
|
||||
let mut live = self.live.lock();
|
||||
if live.as_ref().is_some_and(|l| l.resumable && !l.peer.is_closed()) { live.take() } else { None }
|
||||
@@ -5122,6 +5281,7 @@ impl Task {
|
||||
if let Some(live) = live {
|
||||
tracing::debug!("agent task {}: recycling idle resumable session", self.id);
|
||||
live.peer.kill();
|
||||
self.cancel_permissions();
|
||||
self.clear_shown_background();
|
||||
}
|
||||
}
|
||||
@@ -5729,25 +5889,13 @@ impl Task {
|
||||
if self.shared.shut_down_since(epoch) {
|
||||
return Err(SessionOpenError { message: "The agent manager shut down.".into(), allow_acp_fallback: false });
|
||||
}
|
||||
let memory_delivery = self.stage_memory(&base_id, cwd).await;
|
||||
let memory_delivery = self.memory_delivery(spec.driver, &base_id);
|
||||
if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(&base_id) {
|
||||
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
|
||||
for name in self.shared.mcp_servers_off_for_session(&base_id, &mcp_overrides) {
|
||||
spec.args.push("--disable-mcp-server".into());
|
||||
spec.args.push(name);
|
||||
}
|
||||
if let Some(mem) = memory_delivery.as_ref() {
|
||||
if mem.copilot_enable_memory == Some(true) {
|
||||
spec.args.push("--enable-memory".into());
|
||||
}
|
||||
if mem.copilot_exclude_store_memory {
|
||||
spec.args.push("--excluded-tools".into());
|
||||
spec.args.push("store_memory".into());
|
||||
}
|
||||
if mem.copilot_disable_custom_instructions {
|
||||
spec.args.push("--no-custom-instructions".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
self.stderr.lock().clear();
|
||||
self.config_sent.lock().clear();
|
||||
@@ -5888,7 +6036,7 @@ impl Task {
|
||||
if let Some(shown) = shown {
|
||||
if loaded.is_ok() {
|
||||
self.adopting_replay.store(false, Ordering::Release);
|
||||
let changed = self.state.lock().history.conversation.end_turn(None);
|
||||
let changed = self.end_turn(&mut self.state.lock(), None);
|
||||
self.mark_dirty(changed);
|
||||
} else {
|
||||
// A failed load may still have replayed part of it.
|
||||
@@ -6405,10 +6553,24 @@ impl Task {
|
||||
.or(s.task.usage.take());
|
||||
true
|
||||
}
|
||||
"prompt_suggestions_update" => {
|
||||
if self.replaying.load(Ordering::Acquire) {
|
||||
false
|
||||
} else {
|
||||
let next = prompt_suggestions_of(update);
|
||||
let changed = *s.task.prompt_suggestions != next;
|
||||
*s.task.prompt_suggestions = next;
|
||||
changed
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
};
|
||||
if task_changed {
|
||||
if kind == "prompt_suggestions_update" {
|
||||
self.emit_task();
|
||||
return;
|
||||
}
|
||||
let (config, commands, model) = {
|
||||
let s = self.state.lock();
|
||||
(
|
||||
@@ -6491,14 +6653,22 @@ impl Task {
|
||||
self.set_retry(None);
|
||||
let applied = self.state.lock().history.conversation.apply(session, update, now_ms());
|
||||
self.mark_dirty(applied);
|
||||
// A subagent that stopped working no longer waits for what it asked.
|
||||
if kind == "subagent_update"
|
||||
&& update.pointer("/state/state").and_then(Value::as_str) == Some("idle")
|
||||
&& let Some(child) = update.get("sessionId").and_then(Value::as_str)
|
||||
{
|
||||
self.cancel_requests_of(&Some(child.to_owned()));
|
||||
}
|
||||
// A subagent can start or finish after the turn that started it: nothing else saves it then.
|
||||
if matches!(kind, "subagent_update" | "user_question") {
|
||||
self.persist_soon_for_epoch(epoch);
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocks the calling (blocking-pool) thread until the user answers.
|
||||
fn ask_permission(self: &Arc<Self>, params: &Value, epoch: u64) -> Value {
|
||||
/// Blocks the calling (blocking-pool) thread until the user answers. `rpc_id` is the
|
||||
/// request's JSON-RPC id.
|
||||
fn ask_permission(self: &Arc<Self>, params: &Value, rpc_id: Option<Value>, epoch: u64) -> Value {
|
||||
if self.shared.shut_down_since(epoch) {
|
||||
return json!({ "outcome": { "outcome": "cancelled" } });
|
||||
}
|
||||
@@ -6591,7 +6761,8 @@ impl Task {
|
||||
form: None,
|
||||
chosen: None,
|
||||
});
|
||||
self.permissions.lock().insert(id, tx);
|
||||
let session = s.history.conversation.owner(params.get("sessionId").and_then(Value::as_str));
|
||||
self.permissions.lock().insert(id, PendingRequest { session, rpc_id, reply: tx });
|
||||
s.change_status(AgentStatus::NeedsInput, None);
|
||||
entry
|
||||
};
|
||||
@@ -6670,7 +6841,13 @@ impl Task {
|
||||
|
||||
/// An agent's form (`elicitation/create`): asked in the conversation like a permission
|
||||
/// request, and answered with its values, declined or cancelled. Blocks like `ask_permission`.
|
||||
fn elicit(self: &Arc<Self>, params: &Value, raw: Option<&[u8]>, epoch: u64) -> Result<Value, String> {
|
||||
fn elicit(
|
||||
self: &Arc<Self>,
|
||||
params: &Value,
|
||||
raw: Option<&[u8]>,
|
||||
rpc_id: Option<Value>,
|
||||
epoch: u64,
|
||||
) -> Result<Value, String> {
|
||||
let mut form = elicitation::form_of(params)?;
|
||||
if let Some(raw) = raw {
|
||||
elicitation::in_schema_order(&mut form, raw);
|
||||
@@ -6699,7 +6876,8 @@ impl Task {
|
||||
form: if questions.is_some() { None } else { Some(form.clone()) },
|
||||
chosen: None,
|
||||
});
|
||||
self.permissions.lock().insert(id, tx);
|
||||
let session = s.history.conversation.owner(params.get("sessionId").and_then(Value::as_str));
|
||||
self.permissions.lock().insert(id, PendingRequest { session, rpc_id, reply: tx });
|
||||
s.change_status(AgentStatus::NeedsInput, None);
|
||||
entry
|
||||
};
|
||||
@@ -6738,7 +6916,9 @@ impl Task {
|
||||
}
|
||||
let resumed = s.task.status == AgentStatus::NeedsInput && self.permissions.lock().is_empty();
|
||||
if resumed {
|
||||
s.change_status(AgentStatus::Running, None);
|
||||
// A subagent can still ask after the turn that started it ended.
|
||||
let status = if s.busy { AgentStatus::Running } else { AgentStatus::Ready };
|
||||
s.change_status(status, None);
|
||||
}
|
||||
resumed
|
||||
};
|
||||
@@ -6763,19 +6943,45 @@ impl Task {
|
||||
if let AgentEntry::Permission { id, options, questions, chosen: None, .. } = entry
|
||||
&& questions.is_empty()
|
||||
&& let Some(option) = options.iter().find(|o| o.kind == "allow_once")
|
||||
&& let Some(reply) = pending.remove(id)
|
||||
&& let Some(request) = pending.remove(id)
|
||||
{
|
||||
let _ = reply.send(Some(option.id.clone()));
|
||||
let _ = request.reply.send(Some(option.id.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_permissions(&self) {
|
||||
for (_, reply) in self.permissions.lock().drain() {
|
||||
let _ = reply.send(None);
|
||||
for (_, request) in self.permissions.lock().drain() {
|
||||
let _ = request.reply.send(None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers the open requests of session `session` as cancelled: its work was stopped or ended.
|
||||
fn cancel_requests_of(&self, session: &Session) {
|
||||
for (_, request) in self.permissions.lock().extract_if(|_, r| &r.session == session) {
|
||||
let _ = request.reply.send(None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers the open request the agent sent with JSON-RPC id `rpc_id` as cancelled: the agent withdrew it.
|
||||
fn withdraw(&self, rpc_id: &Value) {
|
||||
for (_, request) in self.permissions.lock().extract_if(|_, r| r.rpc_id.as_ref() == Some(rpc_id)) {
|
||||
let _ = request.reply.send(None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Settles what the task's ended turn left open (see [`Conversation::end_turn`]). Its own
|
||||
/// requests are answered as cancelled; a subagent's stay open while the subagent works.
|
||||
fn end_turn(&self, s: &mut TaskState, done: Option<f64>) -> Vec<(Session, usize)> {
|
||||
let mut pending = self.permissions.lock();
|
||||
for (_, request) in pending.extract_if(|_, r| r.session.is_none()) {
|
||||
let _ = request.reply.send(None);
|
||||
}
|
||||
let open: HashSet<u32> = pending.keys().copied().collect();
|
||||
drop(pending);
|
||||
s.history.conversation.end_turn(done, &open)
|
||||
}
|
||||
|
||||
fn cancel_explicit(&self) {
|
||||
if self.state.lock().busy {
|
||||
self.explicit_stop.store(true, Ordering::Release);
|
||||
@@ -6789,7 +6995,8 @@ impl Task {
|
||||
self.cancel_pending.store(true, Ordering::Release);
|
||||
}
|
||||
self.network_poke.notify_waiters();
|
||||
self.cancel_permissions();
|
||||
// A subagent that works on keeps its requests until it stops.
|
||||
self.cancel_requests_of(&None);
|
||||
if let Some(live) = self.live.lock().clone() {
|
||||
let _ = live.peer.notify("session/cancel", json!({ "sessionId": live.session }));
|
||||
}
|
||||
@@ -6849,6 +7056,19 @@ impl Handler for Client {
|
||||
}
|
||||
return;
|
||||
}
|
||||
// The agent took a request back: ACP's `$/cancel_request`, or `$/cancelRequest` as a
|
||||
// `Peer` sends it (the native drivers' side of their connection).
|
||||
let withdrawn = match method {
|
||||
"$/cancel_request" => params.get("requestId"),
|
||||
"$/cancelRequest" => params.get("id"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(rpc_id) = withdrawn {
|
||||
if let Some(task) = self.task.upgrade() {
|
||||
task.withdraw(rpc_id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if method == "session/update"
|
||||
&& let (Some(task), Some(update)) = (self.task.upgrade(), params.get("update"))
|
||||
{
|
||||
@@ -6870,21 +7090,36 @@ impl Handler for Client {
|
||||
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
|
||||
let task = self.task.upgrade().ok_or((codes::INTERNAL_ERROR, "task closed".to_owned()))?;
|
||||
match method {
|
||||
"session/request_permission" => Ok(task.ask_permission(¶ms, self.epoch)),
|
||||
"elicitation/create" => task.elicit(¶ms, None, self.epoch).map_err(|e| (codes::INVALID_PARAMS, e)),
|
||||
"session/request_permission" => Ok(task.ask_permission(¶ms, None, self.epoch)),
|
||||
"elicitation/create" => {
|
||||
task.elicit(¶ms, None, None, self.epoch).map_err(|e| (codes::INVALID_PARAMS, e))
|
||||
}
|
||||
_ => Err((codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn on_request_raw(&self, method: &str, params: Value, raw: &[u8]) -> Result<Value, (i64, String, Option<Value>)> {
|
||||
if method != "elicitation/create" {
|
||||
if !matches!(method, "session/request_permission" | "elicitation/create") {
|
||||
return self.on_request_with_data(method, params);
|
||||
}
|
||||
let task = self.task.upgrade().ok_or((codes::INTERNAL_ERROR, "task closed".to_owned(), None))?;
|
||||
task.elicit(¶ms, Some(raw), self.epoch).map_err(|e| (codes::INVALID_PARAMS, e, None))
|
||||
let rpc_id = request_id(raw);
|
||||
if method == "session/request_permission" {
|
||||
return Ok(task.ask_permission(¶ms, rpc_id, self.epoch));
|
||||
}
|
||||
task.elicit(¶ms, Some(raw), rpc_id, self.epoch).map_err(|e| (codes::INVALID_PARAMS, e, None))
|
||||
}
|
||||
}
|
||||
|
||||
/// The JSON-RPC id of request `raw`, as the agent sent it.
|
||||
fn request_id(raw: &[u8]) -> Option<Value> {
|
||||
#[derive(Deserialize)]
|
||||
struct Request {
|
||||
id: Value,
|
||||
}
|
||||
serde_json::from_slice::<Request>(raw).ok().map(|request| request.id)
|
||||
}
|
||||
|
||||
/// The prompt trimmed, or `None` when there is nothing to send.
|
||||
fn clean(mut prompt: AgentPrompt) -> Option<AgentPrompt> {
|
||||
prompt.text = prompt.text.trim().to_owned();
|
||||
@@ -7799,3 +8034,77 @@ fn sync_usage_context_size(task: &mut AgentTask) {
|
||||
usage.size = tokens;
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_PROMPT_SUGGESTIONS: usize = 5;
|
||||
|
||||
/// Extracts plain-text prompt suggestions from an ACP `prompt_suggestions_update` payload.
|
||||
fn prompt_suggestions_of(update: &Value) -> Vec<String> {
|
||||
let Some(items) = update.get("suggestions").and_then(Value::as_array) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for item in items {
|
||||
let Some(blocks) = item.get("prompt").and_then(Value::as_array) else {
|
||||
continue;
|
||||
};
|
||||
let mut text = String::new();
|
||||
for block in blocks {
|
||||
match block.get("type").and_then(Value::as_str) {
|
||||
Some("text") => {
|
||||
if let Some(s) = block.get("text").and_then(Value::as_str) {
|
||||
text.push_str(s);
|
||||
}
|
||||
}
|
||||
Some("resource_link") => {
|
||||
let label = block
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.or_else(|| block.get("uri").and_then(Value::as_str).and_then(|u| u.rsplit('/').next()));
|
||||
if let Some(label) = label {
|
||||
if !text.is_empty() && !text.ends_with(char::is_whitespace) {
|
||||
text.push(' ');
|
||||
}
|
||||
text.push('@');
|
||||
text.push_str(label.trim());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let trimmed = text.trim();
|
||||
if !trimmed.is_empty() && !out.iter().any(|existing| existing == trimmed) {
|
||||
out.push(trimmed.to_owned());
|
||||
if out.len() >= MAX_PROMPT_SUGGESTIONS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod prompt_suggestion_tests {
|
||||
use super::prompt_suggestions_of;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn parses_text_and_resource_link_prompt_suggestions() {
|
||||
let update = json!({
|
||||
"sessionUpdate": "prompt_suggestions_update",
|
||||
"suggestions": [
|
||||
{ "prompt": [{ "type": "text", "text": "Run the unit tests" }] },
|
||||
{
|
||||
"prompt": [
|
||||
{ "type": "text", "text": "Explain " },
|
||||
{ "type": "resource_link", "uri": "file:///repo/src/lib.rs", "name": "src/lib.rs" }
|
||||
]
|
||||
},
|
||||
{ "prompt": [{ "type": "text", "text": " " }] },
|
||||
{ "prompt": [{ "type": "text", "text": "Run the unit tests" }] }
|
||||
]
|
||||
});
|
||||
assert_eq!(prompt_suggestions_of(&update), vec!["Run the unit tests", "Explain @src/lib.rs"]);
|
||||
assert!(prompt_suggestions_of(&json!({ "suggestions": [] })).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
//! Unified Agent Memory hub (#6810): discovers curated instruction files, path-scoped
|
||||
//! rules, and cross-session learned auto-memories across every coding agent (`claude`,
|
||||
//! `codex`, `copilot`, `cursor`, `gemini`, `hermes`, `opencode`, and custom ACP agents),
|
||||
//! deduplicates symlinks and `@AGENTS.md` imports, resolves `[agents.memory]` policies
|
||||
//! under Workspace Trust without mutating tracked repository files, stages per-session
|
||||
//! `_meta.openidea.memory` delivery for each driver.
|
||||
//! Unified Agent Rules & Memory hub: discovers curated instruction files, path-scoped
|
||||
//! rules, and cross-session learned auto-memories across coding agents (`claude`, `codex`,
|
||||
//! `copilot`, `cursor`, `gemini`, `hermes`, and custom ACP agents), deduplicates symlinks
|
||||
//! and `@AGENTS.md` wrapper imports, resolves per-provider auto-memory policies under
|
||||
//! Workspace Trust, and builds native per-session `_meta.openidea.memory` payloads only
|
||||
//! for drivers that enforce them (`claude`, `codex`).
|
||||
|
||||
use crate::{
|
||||
AgentAutoMemoryStatus, AgentMemoryCatalog, AgentMemoryCreateTarget, AgentMemoryEntry, AgentMemoryEntryPolicy,
|
||||
AgentMemoryKind, AgentMemoryMode, AgentMemoryOrigin, AgentMemoryOverrides, AgentMemorySettings, AgentMemorySource,
|
||||
AgentMemoryState, AutoMemoryMode, CreateAgentMemoryInput, McpScope, PromoteAgentMemoryInput, hermes,
|
||||
AgentAutoMemoryStatus, AgentMemoryCatalog, AgentMemoryCreateTarget, AgentMemoryEntry, AgentMemoryKind,
|
||||
AgentMemoryOrigin, AgentMemoryOverrides, AgentMemorySettings, AgentMemorySource, AutoMemoryMode,
|
||||
CreateAgentMemoryInput, McpScope, PromoteAgentMemoryInput, hermes,
|
||||
};
|
||||
use ide_core::output_encoding::strip_ansi;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -21,7 +21,11 @@ const CLAUDE_MEMORY_INDEX_WARN_LINES: u32 = 180;
|
||||
const CLAUDE_MEMORY_INDEX_BYTE_CAP: u64 = 25 * 1024;
|
||||
const CLAUDE_MEMORY_INDEX_WARN_BYTES: u64 = 22 * 1024;
|
||||
const INSTRUCTION_WARN_LINES: u32 = 200;
|
||||
const MAX_STAGED_SYSTEM_BYTES: usize = 32 * 1024;
|
||||
|
||||
const CLAUDE_AUTO_MODES: &[AutoMemoryMode] = &[AutoMemoryMode::Inherit, AutoMemoryMode::ReadWrite, AutoMemoryMode::Off];
|
||||
const CODEX_AUTO_MODES: &[AutoMemoryMode] =
|
||||
&[AutoMemoryMode::Inherit, AutoMemoryMode::ReadWrite, AutoMemoryMode::ReadOnly, AutoMemoryMode::Off];
|
||||
const HERMES_AUTO_MODES: &[AutoMemoryMode] = &[AutoMemoryMode::ReadWrite, AutoMemoryMode::Off];
|
||||
|
||||
const SKIP_MONOREPO_DIRS: &[&str] =
|
||||
&["node_modules", "target", "dist", "build", "out", "vendor", "coverage", ".git", ".openidea", ".idea"];
|
||||
@@ -46,56 +50,43 @@ impl Default for MemoryPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-session memory payload attached to `session/new`, `session/load`, and `session/fork`
|
||||
/// at `_meta.openidea.memory`.
|
||||
/// Per-session auto-memory payload attached to `session/new`, `session/load`, and `session/fork`
|
||||
/// at `_meta.openidea.memory` for native drivers that enforce it (`claude`, `codex`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct Delivery {
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub claude_auto_memory: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub claude_md_excludes: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub claude_instruction_files: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub claude_add_dir: Option<PathBuf>,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub claude_additional_dirs_claude_md: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub codex_use_memories: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub codex_generate_memories: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub codex_developer_instructions: Option<String>,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub copilot_exclude_store_memory: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub copilot_enable_memory: Option<bool>,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub copilot_disable_custom_instructions: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub copilot_system_message: Option<String>,
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
/// Normalizes a provider id to its auto-memory policy key.
|
||||
/// Native `claude` and `codex` keep their exact ids (distinct from `claude-acp` / `codex-acp`,
|
||||
/// whose external ACP adapters do not consume `_meta.openidea.memory`); Hermes profiles collapse
|
||||
/// onto `"hermes"`.
|
||||
pub fn provider_key(provider: &str) -> &str {
|
||||
let trimmed = provider.trim();
|
||||
if trimmed == "hermes" || trimmed.starts_with("hermes-") { "hermes" } else { trimmed }
|
||||
}
|
||||
|
||||
pub fn normalize_provider_id(provider: &str) -> &str {
|
||||
let base = provider.strip_suffix("-acp").unwrap_or(provider);
|
||||
if base == "hermes" || base.starts_with("hermes-") { "hermes" } else { base }
|
||||
}
|
||||
|
||||
pub fn matches_agent_filter(agents: &[String], provider: &str) -> bool {
|
||||
if agents.is_empty() {
|
||||
return true;
|
||||
/// Auto-memory modes enforced by `provider`. Empty means the agent manages auto-memory itself.
|
||||
pub fn supported_auto_memory_modes(provider: &str) -> &'static [AutoMemoryMode] {
|
||||
match provider_key(provider) {
|
||||
"claude" => CLAUDE_AUTO_MODES,
|
||||
"codex" => CODEX_AUTO_MODES,
|
||||
"hermes" => HERMES_AUTO_MODES,
|
||||
_ => &[],
|
||||
}
|
||||
let target = normalize_provider_id(provider);
|
||||
agents.iter().any(|raw| {
|
||||
let trimmed = raw.trim();
|
||||
trimmed.eq_ignore_ascii_case(provider) || normalize_provider_id(trimmed).eq_ignore_ascii_case(target)
|
||||
})
|
||||
}
|
||||
|
||||
/// True when `provider`'s auto-memory mode is persisted directly in its own native config file
|
||||
/// (e.g. `~/.hermes/config.yaml`) rather than per-project settings or per-session overrides.
|
||||
pub fn is_native_config_auto_memory(provider: &str) -> bool {
|
||||
provider_key(provider) == "hermes"
|
||||
}
|
||||
|
||||
fn source_key(source: AgentMemorySource) -> &'static str {
|
||||
@@ -473,7 +464,7 @@ pub fn discover_memories_with_plugins(
|
||||
out
|
||||
}
|
||||
|
||||
/// Resolves the full [`AgentMemoryCatalog`] (entries + per-provider auto-memory statuses)
|
||||
/// Resolves the full [`AgentMemoryCatalog`] (discovered entries + per-provider auto-memory statuses)
|
||||
/// against `policy` and optional per-session `session_overrides`.
|
||||
pub fn resolve_catalog(
|
||||
entries: Vec<AgentMemoryEntry>,
|
||||
@@ -481,105 +472,45 @@ pub fn resolve_catalog(
|
||||
policy: &MemoryPolicy,
|
||||
home: Option<&Path>,
|
||||
) -> AgentMemoryCatalog {
|
||||
let resolved_entries = resolve_entries(entries, session_overrides, policy);
|
||||
let (auto_memory, auto_memory_origin) = resolve_global_auto_memory(session_overrides, policy);
|
||||
let providers = build_provider_statuses(&resolved_entries, session_overrides, policy, home);
|
||||
AgentMemoryCatalog { entries: resolved_entries, providers, auto_memory, auto_memory_origin }
|
||||
let providers = build_provider_statuses(&entries, session_overrides, policy, home);
|
||||
AgentMemoryCatalog { entries, providers, workspace_trusted: policy.workspace_trusted }
|
||||
}
|
||||
|
||||
/// Resolves every discovered memory entry's effective [`AgentMemoryMode`] with precedence:
|
||||
/// `Workspace Trust > Session Override > Workspace Settings > User Settings > Default (Auto)`.
|
||||
pub fn resolve_entries(
|
||||
entries: Vec<AgentMemoryEntry>,
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
) -> Vec<AgentMemoryState> {
|
||||
let mut out = Vec::with_capacity(entries.len());
|
||||
for entry in entries {
|
||||
if entry.source.is_workspace() && !policy.workspace_trusted {
|
||||
out.push(AgentMemoryState {
|
||||
entry,
|
||||
mode: AgentMemoryMode::Off,
|
||||
agents: Vec::new(),
|
||||
origin: AgentMemoryOrigin::Trust,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let ws_pol = lookup_entry_policy(&policy.workspace.entries, &entry.id)
|
||||
.filter(|p| policy.workspace_trusted || p.mode == AgentMemoryMode::Off);
|
||||
let user_pol = lookup_entry_policy(&policy.user.entries, &entry.id);
|
||||
let agents = ws_pol
|
||||
.filter(|p| !p.agents.is_empty())
|
||||
.or_else(|| user_pol.filter(|p| !p.agents.is_empty()))
|
||||
.map(|p| p.agents.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
let (mode, origin) =
|
||||
if let Some(chosen) = session_overrides.and_then(|s| lookup_session_entry(&s.entries, &entry.id)) {
|
||||
(chosen, AgentMemoryOrigin::Session)
|
||||
} else if let Some(ws) = ws_pol {
|
||||
(ws.mode, AgentMemoryOrigin::Workspace)
|
||||
} else if let Some(us) = user_pol {
|
||||
(us.mode, AgentMemoryOrigin::User)
|
||||
} else {
|
||||
(AgentMemoryMode::Auto, AgentMemoryOrigin::None)
|
||||
};
|
||||
out.push(AgentMemoryState { entry, mode, agents, origin });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn resolve_global_auto_memory(
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
) -> (AutoMemoryMode, AgentMemoryOrigin) {
|
||||
if let Some(mode) = session_overrides.and_then(|s| s.auto_memory) {
|
||||
return (mode, AgentMemoryOrigin::Session);
|
||||
}
|
||||
let ws_mode = policy.workspace.auto_memory;
|
||||
if ws_mode != AutoMemoryMode::Inherit && (policy.workspace_trusted || ws_mode == AutoMemoryMode::Off) {
|
||||
return (ws_mode, AgentMemoryOrigin::Workspace);
|
||||
}
|
||||
if policy.user.auto_memory != AutoMemoryMode::Inherit {
|
||||
return (policy.user.auto_memory, AgentMemoryOrigin::User);
|
||||
}
|
||||
(AutoMemoryMode::Inherit, AgentMemoryOrigin::None)
|
||||
}
|
||||
|
||||
/// Resolves the effective [`AutoMemoryMode`] for one `provider` (`claude`, `codex`, `copilot`, `hermes`, etc.).
|
||||
/// Resolves the effective [`AutoMemoryMode`] for one `provider` that supports OpenIDEA-managed
|
||||
/// settings/session overrides (`claude`, `codex`).
|
||||
/// Precedence: `Session Override > Workspace Settings (when trusted or Off) > User Settings > Inherit`.
|
||||
pub fn resolve_provider_auto_memory(
|
||||
provider: &str,
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
) -> (AutoMemoryMode, AgentMemoryOrigin) {
|
||||
if let Some(mode) = session_overrides.and_then(|s| s.auto_memory) {
|
||||
let supported = supported_auto_memory_modes(provider);
|
||||
if supported.is_empty() || is_native_config_auto_memory(provider) {
|
||||
return (AutoMemoryMode::Inherit, AgentMemoryOrigin::None);
|
||||
}
|
||||
let accepts = |mode: AutoMemoryMode| mode != AutoMemoryMode::Inherit && supported.contains(&mode);
|
||||
if let Some(mode) = session_overrides.and_then(|s| s.auto_memory)
|
||||
&& accepts(mode)
|
||||
{
|
||||
return (mode, AgentMemoryOrigin::Session);
|
||||
}
|
||||
let key = normalize_provider_id(provider);
|
||||
let key = provider_key(provider);
|
||||
if let Some(ws_prov) = policy.workspace.providers.get(key)
|
||||
&& ws_prov.auto_memory != AutoMemoryMode::Inherit
|
||||
&& accepts(ws_prov.auto_memory)
|
||||
&& (policy.workspace_trusted || ws_prov.auto_memory == AutoMemoryMode::Off)
|
||||
{
|
||||
return (ws_prov.auto_memory, AgentMemoryOrigin::Workspace);
|
||||
}
|
||||
if policy.workspace.auto_memory != AutoMemoryMode::Inherit
|
||||
&& (policy.workspace_trusted || policy.workspace.auto_memory == AutoMemoryMode::Off)
|
||||
{
|
||||
return (policy.workspace.auto_memory, AgentMemoryOrigin::Workspace);
|
||||
}
|
||||
if let Some(user_prov) = policy.user.providers.get(key)
|
||||
&& user_prov.auto_memory != AutoMemoryMode::Inherit
|
||||
&& accepts(user_prov.auto_memory)
|
||||
{
|
||||
return (user_prov.auto_memory, AgentMemoryOrigin::User);
|
||||
}
|
||||
if policy.user.auto_memory != AutoMemoryMode::Inherit {
|
||||
return (policy.user.auto_memory, AgentMemoryOrigin::User);
|
||||
}
|
||||
(AutoMemoryMode::Inherit, AgentMemoryOrigin::None)
|
||||
}
|
||||
|
||||
fn build_provider_statuses(
|
||||
states: &[AgentMemoryState],
|
||||
entries: &[AgentMemoryEntry],
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
home: Option<&Path>,
|
||||
@@ -587,11 +518,9 @@ fn build_provider_statuses(
|
||||
let stats_for = |src: AgentMemorySource| -> (u32, u32) {
|
||||
let mut count = 0u32;
|
||||
let mut tokens = 0u32;
|
||||
for s in states.iter().filter(|s| s.entry.source == src) {
|
||||
for e in entries.iter().filter(|e| e.source == src) {
|
||||
count += 1;
|
||||
if s.mode != AgentMemoryMode::Off {
|
||||
tokens = tokens.saturating_add(s.entry.approx_tokens);
|
||||
}
|
||||
tokens = tokens.saturating_add(e.approx_tokens);
|
||||
}
|
||||
(count, tokens)
|
||||
};
|
||||
@@ -614,19 +543,12 @@ fn build_provider_statuses(
|
||||
codex_dir.as_ref().map(|d| markdown_files(&d.join("rollout_summaries"), 1).len() as u32).unwrap_or(0);
|
||||
let (codex_mode, codex_origin) = resolve_provider_auto_memory("codex", session_overrides, policy);
|
||||
|
||||
let (copilot_mode, copilot_origin) = resolve_provider_auto_memory("copilot", session_overrides, policy);
|
||||
|
||||
let (hermes_notes, hermes_tokens) = stats_for(AgentMemorySource::HermesAuto);
|
||||
let hermes_dir = hermes_root(home).map(|r| r.join("memories"));
|
||||
let (mut hermes_mode, hermes_origin) = resolve_provider_auto_memory("hermes", session_overrides, policy);
|
||||
if hermes_mode == AutoMemoryMode::Inherit
|
||||
&& let Some(root) = hermes_root(home)
|
||||
&& let Some(cfg_mode) = read_hermes_config_memory_mode(&root)
|
||||
{
|
||||
hermes_mode = cfg_mode;
|
||||
}
|
||||
|
||||
let (acp_mode, acp_origin) = resolve_provider_auto_memory("acp", session_overrides, policy);
|
||||
let (hermes_mode, hermes_origin) = match hermes_root(home).and_then(|root| read_hermes_config_memory_mode(&root)) {
|
||||
Some(cfg_mode) => (cfg_mode, AgentMemoryOrigin::Native),
|
||||
None => (AutoMemoryMode::ReadWrite, AgentMemoryOrigin::Native),
|
||||
};
|
||||
|
||||
vec![
|
||||
AgentAutoMemoryStatus {
|
||||
@@ -634,12 +556,12 @@ fn build_provider_statuses(
|
||||
label: "Claude Code".into(),
|
||||
mode: claude_mode,
|
||||
origin: claude_origin,
|
||||
supported_modes: CLAUDE_AUTO_MODES.to_vec(),
|
||||
native_config_only: false,
|
||||
note_count: claude_notes,
|
||||
rollout_count: 0,
|
||||
approx_tokens: claude_tokens,
|
||||
storage_path: claude_dir.map(Into::into),
|
||||
supports_auto_control: true,
|
||||
supports_file_exclusion: true,
|
||||
supports_reset: true,
|
||||
},
|
||||
AgentAutoMemoryStatus {
|
||||
@@ -647,295 +569,81 @@ fn build_provider_statuses(
|
||||
label: "Codex".into(),
|
||||
mode: codex_mode,
|
||||
origin: codex_origin,
|
||||
supported_modes: CODEX_AUTO_MODES.to_vec(),
|
||||
native_config_only: false,
|
||||
note_count: codex_notes,
|
||||
rollout_count: codex_rollouts,
|
||||
approx_tokens: codex_tokens,
|
||||
storage_path: codex_dir.map(Into::into),
|
||||
supports_auto_control: true,
|
||||
supports_file_exclusion: false,
|
||||
supports_reset: true,
|
||||
},
|
||||
AgentAutoMemoryStatus {
|
||||
provider: "copilot".into(),
|
||||
label: "GitHub Copilot".into(),
|
||||
mode: copilot_mode,
|
||||
origin: copilot_origin,
|
||||
note_count: 0,
|
||||
rollout_count: 0,
|
||||
approx_tokens: 0,
|
||||
storage_path: home.map(|h| h.join(".copilot").into()),
|
||||
supports_auto_control: true,
|
||||
supports_file_exclusion: false,
|
||||
supports_reset: false,
|
||||
},
|
||||
AgentAutoMemoryStatus {
|
||||
provider: "hermes".into(),
|
||||
label: "Hermes Agent".into(),
|
||||
mode: hermes_mode,
|
||||
origin: hermes_origin,
|
||||
supported_modes: HERMES_AUTO_MODES.to_vec(),
|
||||
native_config_only: true,
|
||||
note_count: hermes_notes,
|
||||
rollout_count: 0,
|
||||
approx_tokens: hermes_tokens,
|
||||
storage_path: hermes_dir.map(Into::into),
|
||||
supports_auto_control: true,
|
||||
supports_file_exclusion: false,
|
||||
supports_reset: true,
|
||||
},
|
||||
AgentAutoMemoryStatus {
|
||||
provider: "acp".into(),
|
||||
label: "Cursor / Gemini / ACP".into(),
|
||||
mode: acp_mode,
|
||||
origin: acp_origin,
|
||||
note_count: 0,
|
||||
rollout_count: 0,
|
||||
approx_tokens: 0,
|
||||
storage_path: None,
|
||||
supports_auto_control: false,
|
||||
supports_file_exclusion: false,
|
||||
supports_reset: false,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// Directory under `<store_dir>/session-memory/<task_id>` holding per-session staged rules.
|
||||
pub fn farm_dir(store_dir: &Path, task_id: &str) -> PathBuf {
|
||||
store_dir.join("session-memory").join(task_id)
|
||||
/// Builds the per-session [`Delivery`] payload (`_meta.openidea.memory`) for a native driver
|
||||
/// (`"claude"` or `"codex"`). Returns `None` when `auto_memory` is `Inherit` or the driver
|
||||
/// does not consume `_meta.openidea.memory`.
|
||||
pub fn build_delivery(driver_key: &str, auto_memory: AutoMemoryMode) -> Option<Delivery> {
|
||||
if auto_memory == AutoMemoryMode::Inherit {
|
||||
return None;
|
||||
}
|
||||
match driver_key {
|
||||
"claude" => match auto_memory {
|
||||
AutoMemoryMode::ReadWrite => {
|
||||
Some(Delivery { auto_memory, claude_auto_memory: Some(true), ..Delivery::default() })
|
||||
}
|
||||
AutoMemoryMode::Off => {
|
||||
Some(Delivery { auto_memory, claude_auto_memory: Some(false), ..Delivery::default() })
|
||||
}
|
||||
AutoMemoryMode::Inherit | AutoMemoryMode::ReadOnly => None,
|
||||
},
|
||||
"codex" => match auto_memory {
|
||||
AutoMemoryMode::ReadWrite => Some(Delivery {
|
||||
auto_memory,
|
||||
codex_use_memories: Some(true),
|
||||
codex_generate_memories: Some(true),
|
||||
..Delivery::default()
|
||||
}),
|
||||
AutoMemoryMode::ReadOnly => Some(Delivery {
|
||||
auto_memory,
|
||||
codex_use_memories: Some(true),
|
||||
codex_generate_memories: Some(false),
|
||||
..Delivery::default()
|
||||
}),
|
||||
AutoMemoryMode::Off => Some(Delivery {
|
||||
auto_memory,
|
||||
codex_use_memories: Some(false),
|
||||
codex_generate_memories: Some(false),
|
||||
..Delivery::default()
|
||||
}),
|
||||
AutoMemoryMode::Inherit => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes a deleted task's staged memory folder, if any.
|
||||
pub fn remove_farm(store_dir: &Path, task_id: &str) {
|
||||
let _ = std::fs::remove_dir_all(farm_dir(store_dir, task_id));
|
||||
}
|
||||
|
||||
/// Computes the per-session [`Delivery`] payload (`_meta.openidea.memory`) for `provider`,
|
||||
/// staging non-native rules into `farm` where needed (e.g. Claude `.claude/rules/`).
|
||||
pub fn stage(
|
||||
farm: &Path,
|
||||
provider: &str,
|
||||
states: &[AgentMemoryState],
|
||||
auto_memory: AutoMemoryMode,
|
||||
cwd: &Path,
|
||||
home: Option<&Path>,
|
||||
) -> std::io::Result<Delivery> {
|
||||
let norm = normalize_provider_id(provider);
|
||||
let mut out = Delivery { auto_memory, ..Delivery::default() };
|
||||
|
||||
let claude_rules_dir = farm.join(".claude/rules");
|
||||
match std::fs::remove_dir_all(&claude_rules_dir) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
|
||||
_ => {}
|
||||
/// Explicitly updates Hermes's native `config.yaml` (`memory_enabled` and `user_profile_enabled`).
|
||||
/// Never called during session startup — only when the user changes Hermes's setting directly.
|
||||
pub fn set_hermes_auto_memory(provider: &str, mode: AutoMemoryMode, home: Option<&Path>) -> Result<(), String> {
|
||||
if !matches!(mode, AutoMemoryMode::ReadWrite | AutoMemoryMode::Off) {
|
||||
return Err("Hermes auto-memory supports only On (readWrite) or Off".into());
|
||||
}
|
||||
|
||||
match norm {
|
||||
"claude" => {
|
||||
out.claude_auto_memory = match auto_memory {
|
||||
AutoMemoryMode::Inherit => None,
|
||||
AutoMemoryMode::ReadWrite => Some(true),
|
||||
// Claude Code has one boolean (`autoMemoryEnabled`): ReadOnly and Off both stop background writes;
|
||||
// existing `MEMORY.md` entries that remain `Auto`/`Always` can still be staged as read-only rules.
|
||||
AutoMemoryMode::ReadOnly | AutoMemoryMode::Off => Some(false),
|
||||
};
|
||||
|
||||
let mut agents_md_active = false;
|
||||
let mut agents_md_off = false;
|
||||
let mut claude_md_active = false;
|
||||
|
||||
for state in states {
|
||||
let effective_on = state.mode != AgentMemoryMode::Off && matches_agent_filter(&state.agents, provider);
|
||||
let p = state.entry.path.0.as_path();
|
||||
let fname = file_name(p).unwrap_or_default();
|
||||
|
||||
if matches!(state.entry.source, AgentMemorySource::Workspace) && fname == "AGENTS.md" {
|
||||
if effective_on {
|
||||
agents_md_active = true;
|
||||
} else {
|
||||
agents_md_off = true;
|
||||
}
|
||||
}
|
||||
if matches!(state.entry.source, AgentMemorySource::ClaudeWorkspace)
|
||||
&& matches!(fname.as_str(), "CLAUDE.md" | "CLAUDE.local.md")
|
||||
&& effective_on
|
||||
{
|
||||
claude_md_active = true;
|
||||
}
|
||||
|
||||
if !effective_on {
|
||||
if !state.entry.source.is_auto() {
|
||||
out.claude_md_excludes.push(p.to_string_lossy().replace('\\', "/"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Stage `Always` rules from other agents, or a `ReadOnly` `ClaudeAuto` `MEMORY.md`,
|
||||
// into `<farm>/.claude/rules/`.
|
||||
let stage_into_claude = (auto_memory == AutoMemoryMode::ReadOnly
|
||||
&& state.entry.source == AgentMemorySource::ClaudeAuto
|
||||
&& fname == "MEMORY.md")
|
||||
|| (state.mode == AgentMemoryMode::Always
|
||||
&& !matches!(
|
||||
state.entry.source,
|
||||
AgentMemorySource::ClaudeWorkspace | AgentMemorySource::ClaudeUser
|
||||
));
|
||||
|
||||
if stage_into_claude {
|
||||
stage_claude_rule(&claude_rules_dir, state)?;
|
||||
}
|
||||
}
|
||||
|
||||
if agents_md_active && claude_md_active {
|
||||
out.claude_instruction_files = Some("claude-md-and-agents-md".into());
|
||||
} else if agents_md_off {
|
||||
out.claude_instruction_files = Some("claude-md".into());
|
||||
}
|
||||
|
||||
if claude_rules_dir.exists() {
|
||||
out.claude_add_dir = Some(farm.to_path_buf());
|
||||
out.claude_additional_dirs_claude_md = true;
|
||||
}
|
||||
}
|
||||
"codex" => {
|
||||
match auto_memory {
|
||||
AutoMemoryMode::Inherit => {}
|
||||
AutoMemoryMode::ReadWrite => {
|
||||
out.codex_use_memories = Some(true);
|
||||
out.codex_generate_memories = Some(true);
|
||||
}
|
||||
AutoMemoryMode::ReadOnly => {
|
||||
out.codex_use_memories = Some(true);
|
||||
out.codex_generate_memories = Some(false);
|
||||
}
|
||||
AutoMemoryMode::Off => {
|
||||
out.codex_use_memories = Some(false);
|
||||
out.codex_generate_memories = Some(false);
|
||||
}
|
||||
}
|
||||
let extra = collect_staged_text(states, provider, cwd, home, |s| {
|
||||
s.mode == AgentMemoryMode::Always
|
||||
&& !matches!(s.entry.source, AgentMemorySource::CodexUser | AgentMemorySource::CodexAuto)
|
||||
});
|
||||
if !extra.is_empty() {
|
||||
out.codex_developer_instructions = Some(extra);
|
||||
}
|
||||
}
|
||||
"copilot" => {
|
||||
match auto_memory {
|
||||
AutoMemoryMode::Inherit => {}
|
||||
AutoMemoryMode::ReadWrite => {
|
||||
out.copilot_enable_memory = Some(true);
|
||||
}
|
||||
AutoMemoryMode::ReadOnly => {
|
||||
out.copilot_enable_memory = Some(true);
|
||||
out.copilot_exclude_store_memory = true;
|
||||
}
|
||||
AutoMemoryMode::Off => {
|
||||
out.copilot_enable_memory = Some(false);
|
||||
out.copilot_exclude_store_memory = true;
|
||||
}
|
||||
}
|
||||
let native_instructions: Vec<&AgentMemoryState> = states
|
||||
.iter()
|
||||
.filter(|s| {
|
||||
matches!(
|
||||
s.entry.source,
|
||||
AgentMemorySource::Workspace
|
||||
| AgentMemorySource::ClaudeWorkspace
|
||||
| AgentMemorySource::GithubWorkspace
|
||||
| AgentMemorySource::CopilotUser
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
if !native_instructions.is_empty()
|
||||
&& native_instructions
|
||||
.iter()
|
||||
.all(|s| s.mode == AgentMemoryMode::Off || !matches_agent_filter(&s.agents, provider))
|
||||
{
|
||||
out.copilot_disable_custom_instructions = true;
|
||||
}
|
||||
let extra = collect_staged_text(states, provider, cwd, home, |s| {
|
||||
s.mode == AgentMemoryMode::Always
|
||||
&& !matches!(s.entry.source, AgentMemorySource::GithubWorkspace | AgentMemorySource::CopilotUser)
|
||||
});
|
||||
if !extra.is_empty() {
|
||||
out.copilot_system_message = Some(extra);
|
||||
}
|
||||
}
|
||||
"hermes" => {
|
||||
if auto_memory != AutoMemoryMode::Inherit
|
||||
&& let Some(root) = hermes_root(home)
|
||||
&& let Some(prof_home) = hermes::profile_home(&root, provider)
|
||||
{
|
||||
let _ = write_hermes_config_memory_mode(&prof_home, auto_memory);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn stage_claude_rule(rules_dir: &Path, state: &AgentMemoryState) -> std::io::Result<()> {
|
||||
let Ok(raw) = std::fs::read_to_string(&state.entry.path.0) else {
|
||||
return Ok(());
|
||||
};
|
||||
std::fs::create_dir_all(rules_dir)?;
|
||||
let fm = Frontmatter::parse(&raw);
|
||||
let body = raw.get(fm.body..).unwrap_or(raw.as_str()).trim();
|
||||
if body.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let slug = sanitize_slug(&state.entry.id);
|
||||
let out_text = if state.mode != AgentMemoryMode::Always && !state.entry.paths.is_empty() {
|
||||
let mut header = String::from("---\npaths:\n");
|
||||
for p in &state.entry.paths {
|
||||
header.push_str(&format!(" - \"{}\"\n", p.replace('"', "\\\"")));
|
||||
}
|
||||
header.push_str("---\n\n");
|
||||
header.push_str(body);
|
||||
header.push('\n');
|
||||
header
|
||||
} else {
|
||||
format!("{body}\n")
|
||||
};
|
||||
std::fs::write(rules_dir.join(format!("{slug}.md")), out_text)
|
||||
}
|
||||
|
||||
fn collect_staged_text<F>(
|
||||
states: &[AgentMemoryState],
|
||||
provider: &str,
|
||||
_cwd: &Path,
|
||||
_home: Option<&Path>,
|
||||
include: F,
|
||||
) -> String
|
||||
where
|
||||
F: Fn(&AgentMemoryState) -> bool,
|
||||
{
|
||||
let mut buf = String::new();
|
||||
for state in states {
|
||||
if state.mode == AgentMemoryMode::Off || !matches_agent_filter(&state.agents, provider) {
|
||||
continue;
|
||||
}
|
||||
if !include(state) {
|
||||
continue;
|
||||
}
|
||||
// Path-scoped rules only enter un-scoped system prompts when explicitly set to `Always`.
|
||||
if state.mode != AgentMemoryMode::Always && !state.entry.paths.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Ok(raw) = std::fs::read_to_string(&state.entry.path.0) else {
|
||||
continue;
|
||||
};
|
||||
let fm = Frontmatter::parse(&raw);
|
||||
let body = raw.get(fm.body..).unwrap_or(raw.as_str()).trim();
|
||||
if body.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let chunk = format!("## Memory ({})\n{}\n\n", state.entry.title, body);
|
||||
if buf.len() + chunk.len() > MAX_STAGED_SYSTEM_BYTES {
|
||||
break;
|
||||
}
|
||||
buf.push_str(&chunk);
|
||||
}
|
||||
buf.trim().to_owned()
|
||||
let root = hermes_root(home).ok_or("Home directory is unavailable")?;
|
||||
let prof_home = hermes::profile_home(&root, provider).unwrap_or(root);
|
||||
write_hermes_config_memory_mode(&prof_home, mode).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// ─── File Operations: Create, Promote, Delete & Reset ───────────────────────────────
|
||||
@@ -1064,9 +772,7 @@ pub fn promote_memory(
|
||||
pub fn delete_memory(id: &str, entries: &[AgentMemoryEntry]) -> Result<(), String> {
|
||||
let entry = entries.iter().find(|e| e.id == id).ok_or_else(|| format!("Memory entry `{id}` was not found"))?;
|
||||
if !entry.writable {
|
||||
return Err(
|
||||
"Curated instruction and rule files cannot be deleted here; open the file or set its mode to Off.".into()
|
||||
);
|
||||
return Err("Curated instruction and rule files cannot be deleted here; open the file in the editor.".into());
|
||||
}
|
||||
match std::fs::remove_file(&entry.path.0) {
|
||||
Ok(()) => Ok(()),
|
||||
@@ -1079,7 +785,7 @@ pub fn delete_memory(id: &str, entries: &[AgentMemoryEntry]) -> Result<(), Strin
|
||||
pub fn reset_provider_memory(provider: &str, workspaces: &[PathBuf], home: Option<&Path>) -> Result<u32, String> {
|
||||
let home = home.ok_or("Home directory is unavailable")?;
|
||||
let mut removed = 0u32;
|
||||
match normalize_provider_id(provider) {
|
||||
match provider_key(provider) {
|
||||
"claude" => {
|
||||
for dir in claude_auto_memory_dirs(&home.join(".claude"), home, workspaces) {
|
||||
for f in markdown_files(&dir, 2) {
|
||||
@@ -1134,19 +840,6 @@ fn validate_slug(raw: &str) -> Result<String, String> {
|
||||
Ok(trimmed.to_owned())
|
||||
}
|
||||
|
||||
fn sanitize_slug(raw: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for ch in raw.chars() {
|
||||
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
|
||||
out.push(ch.to_ascii_lowercase());
|
||||
} else if !out.ends_with('-') {
|
||||
out.push('-');
|
||||
}
|
||||
}
|
||||
let trimmed = out.trim_matches('-');
|
||||
if trimmed.is_empty() { "memory".into() } else { trimmed.to_owned() }
|
||||
}
|
||||
|
||||
fn format_markdown_with_frontmatter(
|
||||
description: Option<&str>,
|
||||
paths_key: &str,
|
||||
@@ -1201,17 +894,6 @@ fn format_cursor_mdc(description: Option<&str>, globs: &[String], always_apply:
|
||||
out
|
||||
}
|
||||
|
||||
fn lookup_entry_policy<'a>(
|
||||
map: &'a BTreeMap<String, AgentMemoryEntryPolicy>,
|
||||
id: &str,
|
||||
) -> Option<&'a AgentMemoryEntryPolicy> {
|
||||
map.get(id).or_else(|| map.iter().find(|(k, _)| k.eq_ignore_ascii_case(id)).map(|(_, v)| v))
|
||||
}
|
||||
|
||||
fn lookup_session_entry(map: &BTreeMap<String, AgentMemoryMode>, id: &str) -> Option<AgentMemoryMode> {
|
||||
map.get(id).copied().or_else(|| map.iter().find(|(k, _)| k.eq_ignore_ascii_case(id)).map(|(_, v)| *v))
|
||||
}
|
||||
|
||||
fn claude_auto_memory_dirs(claude_home: &Path, home: &Path, workspaces: &[PathBuf]) -> Vec<PathBuf> {
|
||||
let mut dirs = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
@@ -1899,111 +1581,112 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn policy_resolution_enforces_workspace_trust_and_precedence() {
|
||||
fn policy_resolution_enforces_workspace_trust_and_provider_capabilities() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ws = tmp.path().join("ws");
|
||||
let home = tmp.path().join("home");
|
||||
write(&ws.join("AGENTS.md"), "Workspace instructions\n");
|
||||
write(&home.join(".claude/CLAUDE.md"), "User memory\n");
|
||||
write(&home.join(".hermes/profile.yaml"), "display_name: default\n");
|
||||
|
||||
let entries = discover_memories(std::slice::from_ref(&ws), Some(&home));
|
||||
|
||||
let mut ws_settings = AgentMemorySettings { auto_memory: AutoMemoryMode::ReadWrite, ..Default::default() };
|
||||
// Untrusted workspace tries to turn user memory `Always` on (ignored!) and another `Off` (honored).
|
||||
ws_settings.entries.insert(
|
||||
"claudeUser::CLAUDE.md".into(),
|
||||
AgentMemoryEntryPolicy { mode: AgentMemoryMode::Always, agents: Vec::new() },
|
||||
);
|
||||
let mut ws_settings = AgentMemorySettings::default();
|
||||
ws_settings
|
||||
.providers
|
||||
.insert("claude".into(), crate::AgentProviderMemoryPolicy { auto_memory: AutoMemoryMode::ReadWrite });
|
||||
ws_settings
|
||||
.providers
|
||||
.insert("codex".into(), crate::AgentProviderMemoryPolicy { auto_memory: AutoMemoryMode::Off });
|
||||
|
||||
let untrusted = MemoryPolicy {
|
||||
user: AgentMemorySettings::default(),
|
||||
workspace: ws_settings.clone(),
|
||||
workspace: ws_settings,
|
||||
workspace_trusted: false,
|
||||
workspace_roots: vec![ws.clone()],
|
||||
};
|
||||
let cat = resolve_catalog(entries.clone(), None, &untrusted, Some(&home));
|
||||
// Workspace entry locked `Off` by Trust
|
||||
let ws_state = cat.entries.iter().find(|s| s.entry.id == "workspace::AGENTS.md").unwrap();
|
||||
assert_eq!((ws_state.mode, ws_state.origin), (AgentMemoryMode::Off, AgentMemoryOrigin::Trust));
|
||||
// Untrusted workspace could NOT escalate `claudeUser::CLAUDE.md` or `autoMemory`
|
||||
let user_state = cat.entries.iter().find(|s| s.entry.id == "claudeUser::CLAUDE.md").unwrap();
|
||||
assert_eq!((user_state.mode, user_state.origin), (AgentMemoryMode::Auto, AgentMemoryOrigin::None));
|
||||
assert_eq!(cat.auto_memory, AutoMemoryMode::Inherit);
|
||||
assert!(!cat.workspace_trusted);
|
||||
// Untrusted workspace cannot enable Claude auto-memory, but can turn Codex auto-memory off.
|
||||
let claude = cat.providers.iter().find(|p| p.provider == "claude").unwrap();
|
||||
assert_eq!((claude.mode, claude.origin), (AutoMemoryMode::Inherit, AgentMemoryOrigin::None));
|
||||
assert_eq!(claude.supported_modes, [AutoMemoryMode::Inherit, AutoMemoryMode::ReadWrite, AutoMemoryMode::Off]);
|
||||
let codex = cat.providers.iter().find(|p| p.provider == "codex").unwrap();
|
||||
assert_eq!((codex.mode, codex.origin), (AutoMemoryMode::Off, AgentMemoryOrigin::Workspace));
|
||||
let hermes = cat.providers.iter().find(|p| p.provider == "hermes").unwrap();
|
||||
assert!(hermes.native_config_only);
|
||||
assert_eq!((hermes.mode, hermes.origin), (AutoMemoryMode::ReadWrite, AgentMemoryOrigin::Native));
|
||||
|
||||
// Session override wins in a trusted workspace
|
||||
// Session override wins in a trusted workspace, and unsupported modes are ignored.
|
||||
let trusted = MemoryPolicy { workspace_trusted: true, ..untrusted };
|
||||
let session = AgentMemoryOverrides {
|
||||
auto_memory: Some(AutoMemoryMode::ReadOnly),
|
||||
entries: BTreeMap::from([("workspace::AGENTS.md".into(), AgentMemoryMode::Off)]),
|
||||
};
|
||||
let cat2 = resolve_catalog(entries, Some(&session), &trusted, Some(&home));
|
||||
assert_eq!((cat2.auto_memory, cat2.auto_memory_origin), (AutoMemoryMode::ReadOnly, AgentMemoryOrigin::Session));
|
||||
let ws_state2 = cat2.entries.iter().find(|s| s.entry.id == "workspace::AGENTS.md").unwrap();
|
||||
assert_eq!((ws_state2.mode, ws_state2.origin), (AgentMemoryMode::Off, AgentMemoryOrigin::Session));
|
||||
let session_ro = AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::ReadOnly) };
|
||||
assert_eq!(
|
||||
resolve_provider_auto_memory("claude", Some(&session_ro), &trusted),
|
||||
(AutoMemoryMode::ReadWrite, AgentMemoryOrigin::Workspace)
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_provider_auto_memory("codex", Some(&session_ro), &trusted),
|
||||
(AutoMemoryMode::ReadOnly, AgentMemoryOrigin::Session)
|
||||
);
|
||||
// External ACP adapters and unsupported providers never report OpenIDEA auto-memory control.
|
||||
assert!(supported_auto_memory_modes("claude-acp").is_empty());
|
||||
assert!(supported_auto_memory_modes("codex-acp").is_empty());
|
||||
assert!(supported_auto_memory_modes("copilot").is_empty());
|
||||
assert!(supported_auto_memory_modes("cursor").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stages_per_driver_delivery_for_claude_codex_copilot_and_hermes() {
|
||||
fn builds_delivery_only_for_native_claude_and_codex_and_keeps_hermes_explicit() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ws = tmp.path().join("ws");
|
||||
let home = tmp.path().join("home");
|
||||
let farm = tmp.path().join("farm");
|
||||
|
||||
write(&ws.join("AGENTS.md"), "Shared workspace rule\n");
|
||||
write(&ws.join("CLAUDE.md"), "Claude-specific rule\n");
|
||||
write(&ws.join("CLAUDE.local.md"), "Noisy local note\n");
|
||||
write(
|
||||
&ws.join(".github/instructions/ipc.instructions.md"),
|
||||
"---\napplyTo: \"crates/**/*.rs\"\n---\nUse async IPC for disk ops.\n",
|
||||
);
|
||||
write(&home.join(".gemini/GEMINI.md"), "Keep PRs focused.\n");
|
||||
write(&home.join(".hermes/profile.yaml"), "display_name: default\n");
|
||||
|
||||
let entries = discover_memories(std::slice::from_ref(&ws), Some(&home));
|
||||
let session = AgentMemoryOverrides {
|
||||
auto_memory: Some(AutoMemoryMode::ReadOnly),
|
||||
entries: BTreeMap::from([
|
||||
("claudeWorkspace::CLAUDE.local.md".into(), AgentMemoryMode::Off),
|
||||
// `Always` delivers another agent's files to every agent, path scope dropped.
|
||||
("githubWorkspace::.github/instructions/ipc.instructions.md".into(), AgentMemoryMode::Always),
|
||||
("geminiUser::GEMINI.md".into(), AgentMemoryMode::Always),
|
||||
]),
|
||||
};
|
||||
let policy = MemoryPolicy { workspace_roots: vec![ws.clone()], workspace_trusted: true, ..Default::default() };
|
||||
let cat = resolve_catalog(entries, Some(&session), &policy, Some(&home));
|
||||
// Claude: Inherit -> None, ReadWrite -> true, Off -> false, ReadOnly -> None
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::Inherit), None);
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::ReadOnly), None);
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::ReadWrite).unwrap().claude_auto_memory, Some(true));
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::Off).unwrap().claude_auto_memory, Some(false));
|
||||
|
||||
// 1. Claude delivery
|
||||
let claude = stage(&farm, "claude", &cat.entries, AutoMemoryMode::ReadOnly, &ws, Some(&home)).unwrap();
|
||||
assert_eq!(claude.claude_auto_memory, Some(false));
|
||||
assert_eq!(claude.claude_instruction_files.as_deref(), Some("claude-md-and-agents-md"));
|
||||
assert!(claude.claude_md_excludes.iter().any(|p| p.ends_with("CLAUDE.local.md")));
|
||||
assert!(claude.claude_add_dir.is_some());
|
||||
assert!(claude.claude_additional_dirs_claude_md);
|
||||
let staged_rule = std::fs::read_to_string(
|
||||
farm.join(".claude/rules/githubworkspace-github-instructions-ipc-instructions-md.md"),
|
||||
// Codex: ReadWrite / ReadOnly / Off
|
||||
assert_eq!(build_delivery("codex", AutoMemoryMode::Inherit), None);
|
||||
let codex_ro = build_delivery("codex", AutoMemoryMode::ReadOnly).unwrap();
|
||||
assert_eq!(codex_ro.codex_use_memories, Some(true));
|
||||
assert_eq!(codex_ro.codex_generate_memories, Some(false));
|
||||
let codex_off = build_delivery("codex", AutoMemoryMode::Off).unwrap();
|
||||
assert_eq!(codex_off.codex_use_memories, Some(false));
|
||||
assert_eq!(codex_off.codex_generate_memories, Some(false));
|
||||
|
||||
// Copilot, ACP, Hermes produce no session delivery and never touch Hermes config.yaml
|
||||
assert_eq!(build_delivery("copilot", AutoMemoryMode::Off), None);
|
||||
assert_eq!(build_delivery("acp", AutoMemoryMode::Off), None);
|
||||
assert_eq!(build_delivery("hermes", AutoMemoryMode::Off), None);
|
||||
assert!(!home.join(".hermes/config.yaml").exists());
|
||||
|
||||
// Explicit Hermes toggle updates config.yaml directly and rejects unsupported modes
|
||||
assert!(set_hermes_auto_memory("hermes", AutoMemoryMode::ReadOnly, Some(&home)).is_err());
|
||||
set_hermes_auto_memory("hermes", AutoMemoryMode::Off, Some(&home)).unwrap();
|
||||
assert_eq!(read_hermes_config_memory_mode(&home.join(".hermes")), Some(AutoMemoryMode::Off));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_settings_and_overrides_deserialize_cleanly() {
|
||||
let legacy_settings: AgentMemorySettings = serde_json::from_str(
|
||||
r#"{
|
||||
"autoMemory": "readOnly",
|
||||
"providers": { "codex": { "autoMemory": "off" } },
|
||||
"entries": { "workspace::AGENTS.md": { "mode": "off" } }
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(staged_rule, "Use async IPC for disk ops.\n");
|
||||
assert!(farm.join(".claude/rules/geminiuser-gemini-md.md").is_file());
|
||||
assert_eq!(legacy_settings.providers["codex"].auto_memory, AutoMemoryMode::Off);
|
||||
|
||||
// 2. Codex delivery
|
||||
let codex = stage(&farm, "codex", &cat.entries, AutoMemoryMode::ReadOnly, &ws, Some(&home)).unwrap();
|
||||
assert_eq!(codex.codex_use_memories, Some(true));
|
||||
assert_eq!(codex.codex_generate_memories, Some(false));
|
||||
assert!(codex.codex_developer_instructions.as_deref().unwrap().contains("Keep PRs focused."));
|
||||
|
||||
// 3. Copilot delivery
|
||||
let copilot = stage(&farm, "copilot", &cat.entries, AutoMemoryMode::ReadOnly, &ws, Some(&home)).unwrap();
|
||||
assert_eq!(copilot.copilot_enable_memory, Some(true));
|
||||
assert!(copilot.copilot_exclude_store_memory);
|
||||
let copilot_message = copilot.copilot_system_message.as_deref().unwrap();
|
||||
assert!(copilot_message.contains("Keep PRs focused."));
|
||||
// Copilot reads `.github/instructions` natively: not repeated in the system message.
|
||||
assert!(!copilot_message.contains("Use async IPC"));
|
||||
|
||||
// 4. Hermes delivery updates config.yaml
|
||||
let _ = stage(&farm, "hermes", &cat.entries, AutoMemoryMode::Off, &ws, Some(&home)).unwrap();
|
||||
assert_eq!(read_hermes_config_memory_mode(&home.join(".hermes")), Some(AutoMemoryMode::Off));
|
||||
let legacy_overrides: AgentMemoryOverrides = serde_json::from_str(
|
||||
r#"{
|
||||
"autoMemory": "off",
|
||||
"entries": { "workspace::AGENTS.md": "off" }
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(legacy_overrides.auto_memory, Some(AutoMemoryMode::Off));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -204,6 +204,10 @@ pub struct AgentTask {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub automation: Option<Box<crate::automation::AgentTaskAutomation>>,
|
||||
/// Ephemeral next-prompt suggestions from ACP `prompt_suggestions_update`.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[specta(optional)]
|
||||
pub prompt_suggestions: Box<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -870,6 +874,10 @@ pub struct NewAgentTask {
|
||||
pub isolation: Isolation,
|
||||
/// Branch to start the worktree from; the current branch when `None`.
|
||||
pub base: Option<String>,
|
||||
/// Reuse an existing managed worktree directory instead of creating a new one (`Isolation::Worktree` only).
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub worktree_path: Option<IpcPath>,
|
||||
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`).
|
||||
#[serde(default)]
|
||||
pub mcp_overrides: BTreeMap<String, bool>,
|
||||
@@ -1113,8 +1121,8 @@ fn default_true() -> bool {
|
||||
}
|
||||
|
||||
pub use ide_core::settings::{
|
||||
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings,
|
||||
AgentProviderMemoryPolicy, AgentSkillMode, AgentSkillPolicy, AutoMemoryMode,
|
||||
AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings, AgentProviderMemoryPolicy, AgentSkillMode,
|
||||
AgentSkillPolicy, AutoMemoryMode,
|
||||
};
|
||||
|
||||
/// Kind of discovered agent memory entry.
|
||||
@@ -1180,7 +1188,7 @@ impl AgentMemorySource {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which layer decided an [`AgentMemoryState::mode`] or [`AutoMemoryMode`].
|
||||
/// Which layer decided a provider's effective [`AutoMemoryMode`].
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemoryOrigin {
|
||||
@@ -1189,8 +1197,8 @@ pub enum AgentMemoryOrigin {
|
||||
Session,
|
||||
Workspace,
|
||||
User,
|
||||
/// Locked `Off` because the workspace is untrusted.
|
||||
Trust,
|
||||
/// Configured directly in the agent's own native config file (e.g. `~/.hermes/config.yaml`).
|
||||
Native,
|
||||
}
|
||||
|
||||
/// One discovered instruction file, rule file, or learned auto-memory note.
|
||||
@@ -1237,18 +1245,6 @@ pub struct AgentMemoryEntry {
|
||||
pub plugin_name: Option<String>,
|
||||
}
|
||||
|
||||
/// A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMemoryState {
|
||||
pub entry: AgentMemoryEntry,
|
||||
pub mode: AgentMemoryMode,
|
||||
/// Optional provider filter from `[agents.memory.entries.<id>]`; empty means all agents.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub agents: Vec<String>,
|
||||
pub origin: AgentMemoryOrigin,
|
||||
}
|
||||
|
||||
/// Live auto-memory status and capability summary for one agent family.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -1257,41 +1253,43 @@ pub struct AgentAutoMemoryStatus {
|
||||
pub label: String,
|
||||
pub mode: AutoMemoryMode,
|
||||
pub origin: AgentMemoryOrigin,
|
||||
/// Auto-memory modes this provider enforces (empty when the agent manages auto-memory itself).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub supported_modes: Vec<AutoMemoryMode>,
|
||||
/// True when changing the mode edits the agent's own global config (e.g. `~/.hermes/config.yaml`)
|
||||
/// rather than a project or per-session override.
|
||||
#[serde(default)]
|
||||
pub native_config_only: bool,
|
||||
pub note_count: u32,
|
||||
pub rollout_count: u32,
|
||||
pub approx_tokens: u32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub storage_path: Option<IpcPath>,
|
||||
pub supports_auto_control: bool,
|
||||
pub supports_file_exclusion: bool,
|
||||
pub supports_reset: bool,
|
||||
}
|
||||
|
||||
/// Full catalog returned to Settings › Agents › Memory and the Composer `MemoryPicker`.
|
||||
/// Full catalog returned to Settings › Agents › Rules & Memory and the Composer `MemoryPicker`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMemoryCatalog {
|
||||
pub entries: Vec<AgentMemoryState>,
|
||||
pub entries: Vec<AgentMemoryEntry>,
|
||||
pub providers: Vec<AgentAutoMemoryStatus>,
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
pub auto_memory_origin: AgentMemoryOrigin,
|
||||
pub workspace_trusted: bool,
|
||||
}
|
||||
|
||||
/// Per-session memory overrides stored on an [`AgentTask`].
|
||||
/// Per-session auto-memory override stored on an [`AgentTask`] or automation.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentMemoryOverrides {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub auto_memory: Option<AutoMemoryMode>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub entries: BTreeMap<String, AgentMemoryMode>,
|
||||
}
|
||||
|
||||
impl AgentMemoryOverrides {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.auto_memory.is_none() && self.entries.is_empty()
|
||||
self.auto_memory.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -174,13 +174,9 @@ struct Session {
|
||||
mcp_off: Vec<String>,
|
||||
/// The staged skills folder passed as `--add-dir` (its `.claude/skills` holds the copies).
|
||||
skills_add_dir: Option<PathBuf>,
|
||||
/// The staged memory rules folder passed as `--add-dir` (its `.claude/rules` holds shared rules).
|
||||
memory_add_dir: Option<PathBuf>,
|
||||
/// Load `.claude/rules` from `--add-dir` folders (`CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`).
|
||||
additional_dirs_claude_md: bool,
|
||||
/// The workspace's other roots, each passed as `--add-dir`.
|
||||
additional_dirs: Vec<String>,
|
||||
/// Combined `--settings` JSON (`skillOverrides`, `autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`).
|
||||
/// Combined `--settings` JSON (`skillOverrides`, `autoMemoryEnabled`).
|
||||
cli_settings: Option<String>,
|
||||
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
|
||||
ephemeral: bool,
|
||||
@@ -400,11 +396,6 @@ impl Shim {
|
||||
mcp_config,
|
||||
mcp_off,
|
||||
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
memory_add_dir: memory.and_then(|m| m.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
additional_dirs_claude_md: memory
|
||||
.and_then(|m| m.get("claudeAdditionalDirsClaudeMd"))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false),
|
||||
additional_dirs: additional_dirs(params),
|
||||
cli_settings,
|
||||
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
|
||||
@@ -774,11 +765,6 @@ impl Session {
|
||||
if let Some(dir) = &self.skills_add_dir {
|
||||
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
if let Some(dir) = &self.memory_add_dir
|
||||
&& self.skills_add_dir.as_ref() != Some(dir)
|
||||
{
|
||||
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
for dir in &self.additional_dirs {
|
||||
args.extend(["--add-dir".to_owned(), dir.clone()]);
|
||||
}
|
||||
@@ -789,12 +775,7 @@ impl Session {
|
||||
args.push("--no-session-persistence".to_owned());
|
||||
}
|
||||
args.extend(start.args());
|
||||
let mut env = shim.config.env.clone();
|
||||
if self.additional_dirs_claude_md
|
||||
&& !env.iter().any(|(k, _)| k == "CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD")
|
||||
{
|
||||
env.push(("CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD".to_owned(), "1".to_owned()));
|
||||
}
|
||||
let env = shim.config.env.clone();
|
||||
let launch = Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env };
|
||||
let io = shim
|
||||
.cli
|
||||
@@ -1657,8 +1638,8 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
|
||||
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
|
||||
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
|
||||
/// Claude Code's own configuration stays off too.
|
||||
/// Combines `skillOverrides` from `_meta.openidea.skills.claudeSettings` with memory
|
||||
/// settings (`autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`) into one `--settings` JSON.
|
||||
/// Combines `skillOverrides` from `_meta.openidea.skills.claudeSettings` with
|
||||
/// `autoMemoryEnabled` from `_meta.openidea.memory` into one `--settings` JSON.
|
||||
fn build_cli_settings(skills: Option<&Value>, memory: Option<&Value>) -> Option<String> {
|
||||
let mut root = skills
|
||||
.and_then(|s| s.get("claudeSettings"))
|
||||
@@ -1666,27 +1647,8 @@ fn build_cli_settings(skills: Option<&Value>, memory: Option<&Value>) -> Option<
|
||||
.and_then(|raw| serde_json::from_str::<serde_json::Map<String, Value>>(raw).ok())
|
||||
.unwrap_or_default();
|
||||
|
||||
if let Some(mem) = memory {
|
||||
if let Some(auto) = mem.get("claudeAutoMemory").and_then(Value::as_bool) {
|
||||
root.insert("autoMemoryEnabled".into(), json!(auto));
|
||||
}
|
||||
if let Some(excludes) = mem.get("claudeMdExcludes").and_then(Value::as_array) {
|
||||
let clean: Vec<Value> =
|
||||
excludes.iter().filter_map(Value::as_str).filter(|s| !s.is_empty()).map(|s| json!(s)).collect();
|
||||
if !clean.is_empty() {
|
||||
root.insert("claudeMdExcludes".into(), Value::Array(clean));
|
||||
}
|
||||
}
|
||||
if let Some(inst) = mem.get("claudeInstructionFiles").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
root.insert(
|
||||
"pluginConfigs".into(),
|
||||
json!({
|
||||
"cc-plugin-agents-md@builtin": {
|
||||
"options": { "instructionFiles": inst }
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
if let Some(auto) = memory.and_then(|m| m.get("claudeAutoMemory")).and_then(Value::as_bool) {
|
||||
root.insert("autoMemoryEnabled".into(), json!(auto));
|
||||
}
|
||||
|
||||
(!root.is_empty()).then(|| serde_json::to_string(&Value::Object(root)).expect("settings serialize"))
|
||||
|
||||
@@ -1553,7 +1553,7 @@ async fn an_ephemeral_session_is_not_saved() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env() {
|
||||
async fn session_merges_skills_and_auto_memory_into_claude_settings() {
|
||||
let cli = replay_cli(load_fixture("simple"));
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
@@ -1569,45 +1569,8 @@ async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env()
|
||||
"claudeSettings": "{\"skillOverrides\":{\"tdd\":\"user-invocable-only\"}}"
|
||||
},
|
||||
"memory": {
|
||||
"autoMemory": "readOnly",
|
||||
"claudeAutoMemory": false,
|
||||
"claudeMdExcludes": ["/repo/CLAUDE.local.md"],
|
||||
"claudeInstructionFiles": "claude-md-and-agents-md",
|
||||
"claudeAddDir": "/tmp/farm-memory",
|
||||
"claudeAdditionalDirsClaudeMd": true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-skills"]), "{args:?}");
|
||||
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-memory"]), "{args:?}");
|
||||
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
|
||||
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
|
||||
assert_eq!(parsed["skillOverrides"]["tdd"], "user-invocable-only");
|
||||
assert_eq!(parsed["autoMemoryEnabled"], false);
|
||||
assert_eq!(parsed["claudeMdExcludes"], json!(["/repo/CLAUDE.local.md"]));
|
||||
assert_eq!(
|
||||
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
|
||||
"claude-md-and-agents-md"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_merges_memory_settings_without_plugin_dir_or_plugin_config_injection() {
|
||||
let cli = replay_cli(load_fixture("simple"));
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
let h =
|
||||
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
|
||||
let params = json!({
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": {
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"claudeInstructionFiles": "claude-md-and-agents-md"
|
||||
"autoMemory": "off",
|
||||
"claudeAutoMemory": false
|
||||
},
|
||||
"plugins": { "activePlugins": ["azure", "linear@mkt"] }
|
||||
}
|
||||
@@ -1615,12 +1578,12 @@ async fn session_merges_memory_settings_without_plugin_dir_or_plugin_config_inje
|
||||
});
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-skills"]), "{args:?}");
|
||||
assert!(!args.iter().any(|a| a == "--plugin-dir"), "{args:?}");
|
||||
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
|
||||
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
|
||||
assert_eq!(
|
||||
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
|
||||
"claude-md-and-agents-md"
|
||||
);
|
||||
assert!(parsed["pluginConfigs"]["azure"].is_null());
|
||||
assert_eq!(parsed["skillOverrides"]["tdd"], "user-invocable-only");
|
||||
assert_eq!(parsed["autoMemoryEnabled"], false);
|
||||
assert!(parsed.get("claudeMdExcludes").is_none());
|
||||
assert!(parsed.get("pluginConfigs").is_none());
|
||||
}
|
||||
@@ -385,18 +385,25 @@ fn apply_thread_config(params: &Value, request: &mut Value) {
|
||||
if let Some(mem) = params.pointer("/_meta/openidea/memory")
|
||||
&& let Some(map) = config.as_object_mut()
|
||||
{
|
||||
let use_m = mem.get("codexUseMemories").and_then(Value::as_bool);
|
||||
let gen_m = mem.get("codexGenerateMemories").and_then(Value::as_bool);
|
||||
let mut mem_cfg = serde_json::Map::new();
|
||||
if let Some(use_m) = mem.get("codexUseMemories").and_then(Value::as_bool) {
|
||||
mem_cfg.insert("use_memories".into(), json!(use_m));
|
||||
if let Some(v) = use_m {
|
||||
mem_cfg.insert("use_memories".into(), json!(v));
|
||||
}
|
||||
if let Some(gen_m) = mem.get("codexGenerateMemories").and_then(Value::as_bool) {
|
||||
mem_cfg.insert("generate_memories".into(), json!(gen_m));
|
||||
if let Some(v) = gen_m {
|
||||
mem_cfg.insert("generate_memories".into(), json!(v));
|
||||
}
|
||||
if !mem_cfg.is_empty() {
|
||||
map.insert("memories".into(), Value::Object(mem_cfg));
|
||||
}
|
||||
if let Some(dev) = mem.get("codexDeveloperInstructions").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
map.insert("developer_instructions".into(), json!(dev));
|
||||
// Codex's `memories` feature flag defaults to `false`; turn it on whenever the user
|
||||
// explicitly asks to read or generate memories.
|
||||
if use_m == Some(true) || gen_m == Some(true) {
|
||||
let features = map.entry("features".to_owned()).or_insert_with(|| Value::Object(serde_json::Map::new()));
|
||||
if let Some(f) = features.as_object_mut() {
|
||||
f.insert("memories".into(), json!(true));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !config.as_object().is_some_and(|m| m.is_empty()) {
|
||||
|
||||
@@ -2227,8 +2227,7 @@ fn workspace_roots_join_the_thread_roots() {
|
||||
"skills": { "codexOff": [["noisy", "/repo/.agents/skills/noisy/SKILL.md"]] },
|
||||
"memory": {
|
||||
"codexUseMemories": true,
|
||||
"codexGenerateMemories": false,
|
||||
"codexDeveloperInstructions": "## Memory (style)\nUse targeted selectors."
|
||||
"codexGenerateMemories": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2236,8 +2235,27 @@ fn workspace_roots_join_the_thread_roots() {
|
||||
&mut mem_req,
|
||||
);
|
||||
assert_eq!(mem_req["config"]["memories"], json!({ "use_memories": true, "generate_memories": false }));
|
||||
assert_eq!(mem_req["config"]["developer_instructions"], "## Memory (style)\nUse targeted selectors.");
|
||||
assert_eq!(mem_req["config"]["features"]["memories"], true);
|
||||
assert_eq!(mem_req["config"]["skills"]["config"][0]["enabled"], false);
|
||||
|
||||
let mut off_req = json!({});
|
||||
apply_thread_config(
|
||||
&json!({
|
||||
"cwd": "/w/api",
|
||||
"mcpServers": [],
|
||||
"_meta": {
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"codexUseMemories": false,
|
||||
"codexGenerateMemories": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
&mut off_req,
|
||||
);
|
||||
assert_eq!(off_req["config"]["memories"], json!({ "use_memories": false, "generate_memories": false }));
|
||||
assert!(off_req["config"].get("features").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
@@ -471,38 +471,6 @@ fn apply_skills(params: &Value, req: &mut Value) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies `_meta.openidea.memory` to Copilot's `session.create` / `session.resume` payload:
|
||||
/// gates `store_memory` when auto-memory is `ReadOnly` or `Off`, disables custom instructions
|
||||
/// when all workspace/user instructions are muted, and appends shared OpenIDEA memories.
|
||||
fn apply_memory(params: &Value, req: &mut Value) {
|
||||
let Some(mem) = params.pointer("/_meta/openidea/memory") else {
|
||||
return;
|
||||
};
|
||||
if mem.get("copilotExcludeStoreMemory").and_then(Value::as_bool) == Some(true) {
|
||||
let mut excluded: Vec<String> = req
|
||||
.get("excludedTools")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
if !excluded.iter().any(|t| t == "store_memory") {
|
||||
excluded.push("store_memory".into());
|
||||
}
|
||||
req["excludedTools"] = json!(excluded);
|
||||
}
|
||||
if mem.get("copilotDisableCustomInstructions").and_then(Value::as_bool) == Some(true) {
|
||||
req["customInstructions"] = json!(false);
|
||||
}
|
||||
if let Some(sys) = mem.get("copilotSystemMessage").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
req["systemMessage"] = json!({
|
||||
"mode": "append",
|
||||
"content": sys,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> ResponseError {
|
||||
error(codes::INVALID_PARAMS, message)
|
||||
}
|
||||
@@ -630,7 +598,6 @@ impl CopilotShim {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
apply_skills(params, &mut req);
|
||||
apply_memory(params, &mut req);
|
||||
|
||||
let created = self.call("session.create", req).await?;
|
||||
let session_id = created
|
||||
@@ -701,7 +668,6 @@ impl CopilotShim {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
apply_skills(params, &mut req);
|
||||
apply_memory(params, &mut req);
|
||||
|
||||
let resumed = self.call("session.resume", req).await?;
|
||||
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(session_id).to_owned();
|
||||
|
||||
@@ -953,56 +953,6 @@ async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skil
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn session_new_and_load_apply_copilot_memory_gating_and_system_message() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates, move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
let meta = json!({
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"autoMemory": "readOnly",
|
||||
"copilotExcludeStoreMemory": true,
|
||||
"copilotDisableCustomInstructions": true,
|
||||
"copilotSystemMessage": "## Memory (shared)\nRun targeted tests."
|
||||
}
|
||||
}
|
||||
});
|
||||
let _: Value =
|
||||
client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [], "_meta": meta }), None).await.unwrap();
|
||||
let _: Value = client
|
||||
.request(
|
||||
"session/load",
|
||||
json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [], "_meta": meta }),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let calls = server.calls.lock();
|
||||
for method in ["session.create", "session.resume"] {
|
||||
let params = calls.iter().find_map(|(m, p)| (m == method).then_some(p)).expect(method);
|
||||
assert_eq!(params["excludedTools"], json!(["store_memory"]), "{method}: {params}");
|
||||
assert_eq!(params["customInstructions"], json!(false), "{method}: {params}");
|
||||
assert_eq!(
|
||||
params["systemMessage"],
|
||||
json!({ "mode": "append", "content": "## Memory (shared)\nRun targeted tests." }),
|
||||
"{method}: {params}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translates_context_attribution_without_double_counting_parent_rollups() {
|
||||
let payload = json!({
|
||||
|
||||
@@ -79,6 +79,10 @@ struct FakeAgent {
|
||||
open_errors: Mutex<VecDeque<(i64, String, Option<Value>)>>,
|
||||
/// Recorded `(method, _meta.openidea.memory)` payloads across `session/new`, `session/load`, and `session/fork`.
|
||||
memory_calls: Mutex<Vec<(String, Option<Value>)>>,
|
||||
/// What the client answered to the requests sent with [`FakeAgent::ask_aside`], by label.
|
||||
aside: Arc<Mutex<Vec<(String, Value)>>>,
|
||||
/// How far a test let a scenario that waits for it go on.
|
||||
go: AtomicU32,
|
||||
}
|
||||
|
||||
impl FakeAgent {
|
||||
@@ -146,6 +150,117 @@ impl FakeAgent {
|
||||
);
|
||||
self.say(root, "Found it");
|
||||
}
|
||||
|
||||
/// Sends a request without waiting for its answer, as a subagent working beside its
|
||||
/// parent does; the answer is noted in `aside` under `label`.
|
||||
fn ask_aside(&self, label: &str, method: &str, params: Value) {
|
||||
let (peer, aside, label, method) = (self.latest(), self.aside.clone(), label.to_owned(), method.to_owned());
|
||||
tokio::runtime::Handle::current().spawn(async move {
|
||||
let answer = peer.request::<_, Value>(&method, params, None).await;
|
||||
aside.lock().push((label, answer.unwrap_or_else(|e| json!(e.to_string()))));
|
||||
});
|
||||
}
|
||||
|
||||
/// Waits up to 5 s for `done`.
|
||||
fn wait_until(&self, done: impl Fn(&Self) -> bool) {
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
while !done(self) && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits until the test lets the scenario past `step` (see `go`), for at most 10 s.
|
||||
async fn step(&self, step: u32) {
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
|
||||
while self.go.load(Ordering::Acquire) < step && tokio::time::Instant::now() < deadline {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Subagent `c1` of `root` asks for permission while it works, and the turn goes on as
|
||||
/// `then` says.
|
||||
fn subagent_asks(&self, root: &str, then: &str) -> Value {
|
||||
self.update(
|
||||
root,
|
||||
json!({"sessionUpdate": "subagent_update", "sessionId": "c1", "title": "Explore",
|
||||
"capabilities": {"cancel": {}}, "state": {"state": "running"}}),
|
||||
);
|
||||
self.ask_aside(
|
||||
"permission",
|
||||
"session/request_permission",
|
||||
json!({"sessionId": "c1", "toolCall": {"toolCallId": "c1-t1", "title": "Run ls"},
|
||||
"options": [{"optionId": "yes", "name": "Allow", "kind": "allow_once"}]}),
|
||||
);
|
||||
let stopped = || {
|
||||
self.update(
|
||||
root,
|
||||
json!({"sessionUpdate": "subagent_update", "sessionId": "c1",
|
||||
"state": {"state": "idle", "stopReason": "cancelled"}}),
|
||||
)
|
||||
};
|
||||
let cancelled = |agent: &Self| agent.calls.lock().iter().any(|c| c == "session/cancel");
|
||||
match then {
|
||||
// Stop Subagent: the agent reports the subagent stopped once its requests are answered.
|
||||
"the user stops it" => {
|
||||
self.ask_aside(
|
||||
"form",
|
||||
"elicitation/create",
|
||||
json!({"sessionId": "c1", "mode": "form", "message": "Which layout?",
|
||||
"requestedSchema": {"type": "object", "properties": {"layout": {"type": "string", "title": "Layout"}}}}),
|
||||
);
|
||||
self.wait_until(cancelled);
|
||||
self.wait_until(|agent| agent.aside.lock().len() == 2);
|
||||
stopped();
|
||||
}
|
||||
"it stops" => {
|
||||
self.wait_until(|agent| agent.go.load(Ordering::Acquire) >= 1);
|
||||
stopped();
|
||||
self.wait_until(|agent| !agent.aside.lock().is_empty());
|
||||
}
|
||||
// The subagent works on after the turn it started in.
|
||||
"the user stops the task" => {
|
||||
self.wait_until(cancelled);
|
||||
return json!({"stopReason": "cancelled"});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
json!({"stopReason": "end_turn"})
|
||||
}
|
||||
|
||||
/// Asks twice and takes both requests back at step 1: the first with ACP's
|
||||
/// `$/cancel_request`, the second as a `Peer` does when its request is cancelled
|
||||
/// (`$/cancelRequest`). The turn ends at step 2.
|
||||
fn asks_then_withdraws(&self, session: &str) {
|
||||
let peer = self.latest();
|
||||
let token = ide_core::CancellationToken::new();
|
||||
let ask = |title: &str, cancel| {
|
||||
peer.request::<_, Value>(
|
||||
"session/request_permission",
|
||||
json!({"sessionId": session, "toolCall": {"toolCallId": title, "title": title},
|
||||
"options": [{"optionId": "yes", "name": "Allow", "kind": "allow_once"}]}),
|
||||
cancel,
|
||||
)
|
||||
};
|
||||
let first = async {
|
||||
tokio::select! {
|
||||
biased;
|
||||
answer = ask("Run make", None) => {
|
||||
self.aside.lock().push(("first".to_owned(), answer.unwrap_or_else(|e| json!(e.to_string()))));
|
||||
}
|
||||
() = self.step(2) => {}
|
||||
}
|
||||
};
|
||||
let take_back = async {
|
||||
self.step(1).await;
|
||||
// The first request is this connection's first, which `Peer` numbers 1.
|
||||
peer.notify("$/cancel_request", json!({"requestId": 1})).unwrap();
|
||||
token.cancel();
|
||||
self.step(2).await;
|
||||
};
|
||||
let second = ask("Run make test", Some(token.clone()));
|
||||
// Polled in order, so the first request is sent first.
|
||||
let _ = tokio::runtime::Handle::current().block_on(async { tokio::join!(biased; first, second, take_back) });
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler for FakeAgent {
|
||||
@@ -372,6 +487,17 @@ impl Handler for FakeAgent {
|
||||
self.delegate(&session);
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if let Some(then) = text.strip_prefix("subagent asks, then ") {
|
||||
return Ok(self.subagent_asks(&session, then));
|
||||
}
|
||||
if text == "ask, then withdraw" {
|
||||
self.asks_then_withdraws(&session);
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if let Some(reason) = text.strip_prefix("stop with ") {
|
||||
self.say(&session, "Here is the fix:\n```rust\nfn parse(input: &str) -> Result<");
|
||||
return Ok(json!({"stopReason": reason}));
|
||||
}
|
||||
if text == "late option" {
|
||||
// An option the session offers only once it runs.
|
||||
self.update(
|
||||
@@ -2926,6 +3052,184 @@ async fn subagents_get_their_own_conversation() {
|
||||
check(&manager(tmp.path(), Arc::new(FakeAgent::default())));
|
||||
}
|
||||
|
||||
/// A task started with `prompt` against a fake agent of its own.
|
||||
async fn started(dir: &Path, prompt: &str) -> (Arc<FakeAgent>, AgentManager, String) {
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(dir, agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text(prompt), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
(agent, mgr, task.id)
|
||||
}
|
||||
|
||||
/// The ids of the requests task `id` shows unanswered, once there are `n`.
|
||||
async fn open_requests(mgr: &AgentManager, id: &str, n: usize) -> Vec<u32> {
|
||||
for _ in 0..500 {
|
||||
let open: Vec<u32> = mgr
|
||||
.entries(id, None)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter_map(|e| match e {
|
||||
AgentEntry::Permission { id, chosen: None, .. } => Some(id),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if open.len() == n {
|
||||
return open;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
panic!("task never showed {n} open requests");
|
||||
}
|
||||
|
||||
/// What the card of request `request` records as chosen.
|
||||
fn chosen(mgr: &AgentManager, id: &str, request: u32) -> Option<String> {
|
||||
mgr.entries(id, None)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find_map(|e| match e {
|
||||
AgentEntry::Permission { id, chosen, .. } if id == request => Some(chosen),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Waits up to 5 s for `done`.
|
||||
async fn until(done: impl Fn() -> bool) {
|
||||
for _ in 0..500 {
|
||||
if done() {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The agent's answers to the requests it sent aside, by label.
|
||||
fn aside_answers(agent: &FakeAgent) -> Vec<(String, Value)> {
|
||||
let mut answers = agent.aside.lock().clone();
|
||||
answers.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
answers
|
||||
}
|
||||
|
||||
fn cancelled() -> Value {
|
||||
json!({"outcome": {"outcome": "cancelled"}})
|
||||
}
|
||||
|
||||
/// Stopping a subagent answers what it asked as cancelled, before the agent reports it stopped.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn stopping_a_subagent_cancels_its_open_requests() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (agent, mgr, task) = started(tmp.path(), "subagent asks, then the user stops it").await;
|
||||
let requests = open_requests(&mgr, &task, 2).await;
|
||||
mgr.cancel(&task, Some("c1".into())).unwrap();
|
||||
until(|| agent.aside.lock().len() == 2).await;
|
||||
let answers = aside_answers(&agent);
|
||||
wait_for(&mgr, &task, AgentStatus::Ready).await;
|
||||
let cards: Vec<_> = requests.iter().map(|&r| chosen(&mgr, &task, r)).collect();
|
||||
shut_down(&mgr, &agent).await;
|
||||
assert_eq!(answers, [("form".to_owned(), json!({"action": "cancel"})), ("permission".to_owned(), cancelled())]);
|
||||
assert_eq!(cards, [Some("Cancelled".to_owned()), Some("Cancelled".to_owned())]);
|
||||
}
|
||||
|
||||
/// A subagent that works on keeps its request when the task's turn is stopped and ends: the
|
||||
/// user can still answer it.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_subagent_keeps_its_open_request_past_the_stopped_turn() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (agent, mgr, task) = started(tmp.path(), "subagent asks, then the user stops the task").await;
|
||||
let request = open_requests(&mgr, &task, 1).await[0];
|
||||
mgr.cancel(&task, None).unwrap();
|
||||
wait_for(&mgr, &task, AgentStatus::Ready).await;
|
||||
let after_the_turn = (chosen(&mgr, &task, request), aside_answers(&agent));
|
||||
let answered = mgr.respond(&task, request, Some("yes".into()));
|
||||
until(|| !agent.aside.lock().is_empty()).await;
|
||||
let answers = aside_answers(&agent);
|
||||
let card = chosen(&mgr, &task, request);
|
||||
|
||||
// It asks again with no turn running; answered, the task is Ready again.
|
||||
let peer = agent.latest();
|
||||
let again = tokio::spawn(async move {
|
||||
peer.request::<_, Value>(
|
||||
"session/request_permission",
|
||||
json!({"sessionId": "c1", "toolCall": {"toolCallId": "c1-t2", "title": "Run pwd"},
|
||||
"options": [{"optionId": "yes", "name": "Allow", "kind": "allow_once"}]}),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
});
|
||||
wait_for(&mgr, &task, AgentStatus::NeedsInput).await;
|
||||
let second = open_requests(&mgr, &task, 1).await[0];
|
||||
mgr.respond(&task, second, Some("yes".into())).unwrap();
|
||||
let _ = again.await;
|
||||
let status = mgr.task(&task).unwrap().state.lock().task.status;
|
||||
shut_down(&mgr, &agent).await;
|
||||
assert_eq!(after_the_turn, (None, Vec::new()));
|
||||
assert!(answered.is_ok(), "{answered:?}");
|
||||
assert_eq!(answers, [("permission".to_owned(), json!({"outcome": {"outcome": "selected", "optionId": "yes"}}))]);
|
||||
assert_eq!(card.as_deref(), Some("Allow"));
|
||||
assert_eq!(status, AgentStatus::Ready);
|
||||
}
|
||||
|
||||
/// A subagent that stops has no use for what it still waits for: its requests are cancelled.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_subagent_that_stops_has_its_open_request_cancelled() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (agent, mgr, task) = started(tmp.path(), "subagent asks, then it stops").await;
|
||||
let request = open_requests(&mgr, &task, 1).await[0];
|
||||
agent.go.store(1, Ordering::Release);
|
||||
until(|| !agent.aside.lock().is_empty()).await;
|
||||
let answers = aside_answers(&agent);
|
||||
wait_for(&mgr, &task, AgentStatus::Ready).await;
|
||||
let card = chosen(&mgr, &task, request);
|
||||
shut_down(&mgr, &agent).await;
|
||||
assert_eq!(answers, [("permission".to_owned(), cancelled())]);
|
||||
assert_eq!(card.as_deref(), Some("Cancelled"));
|
||||
}
|
||||
|
||||
/// A request the agent takes back closes while the turn goes on, answered as cancelled.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_agent_can_withdraw_its_requests() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (agent, mgr, task) = started(tmp.path(), "ask, then withdraw").await;
|
||||
let requests = open_requests(&mgr, &task, 2).await;
|
||||
agent.go.store(1, Ordering::Release);
|
||||
let closed = || requests.iter().all(|&r| chosen(&mgr, &task, r).is_some());
|
||||
until(|| closed() && !agent.aside.lock().is_empty()).await;
|
||||
let cards: Vec<_> = requests.iter().map(|&r| chosen(&mgr, &task, r)).collect();
|
||||
let answers = aside_answers(&agent);
|
||||
agent.go.store(2, Ordering::Release);
|
||||
wait_for(&mgr, &task, AgentStatus::Ready).await;
|
||||
shut_down(&mgr, &agent).await;
|
||||
assert_eq!(cards, [Some("Cancelled".to_owned()), Some("Cancelled".to_owned())]);
|
||||
assert_eq!(answers, [("first".to_owned(), cancelled())]);
|
||||
}
|
||||
|
||||
/// A turn that ends at one of the agent's limits says so, as a refusal does.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_turn_stopped_by_a_limit_says_so() {
|
||||
for (reason, message) in [
|
||||
("max_tokens", "The reply was cut off: the agent reached its output token limit."),
|
||||
("max_turn_requests", "The turn stopped: the agent reached its limit of model requests per turn."),
|
||||
("refusal", "The agent declined to continue."),
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text(&format!("stop with {reason}")),
|
||||
provider: "claude".into(),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert_eq!(entries.last(), Some(&AgentEntry::Error { message: message.into() }), "{reason}: {entries:?}");
|
||||
mgr.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_blocks_declare_the_type_of_their_bytes() {
|
||||
let image = |mime: &str, data: &str| AgentImage {
|
||||
@@ -3466,7 +3770,7 @@ async fn persistent_project_trust_needs_confirmation_even_with_bypass() {
|
||||
let handle = handle.clone();
|
||||
let params = params.clone();
|
||||
let epoch = handle.shared.shutdown_epoch();
|
||||
tokio::task::spawn_blocking(move || handle.ask_permission(¶ms, epoch))
|
||||
tokio::task::spawn_blocking(move || handle.ask_permission(¶ms, None, epoch))
|
||||
};
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
assert!(!asking.is_finished());
|
||||
@@ -4151,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")] {
|
||||
@@ -6684,6 +7038,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
worktree_path: None,
|
||||
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
@@ -6717,25 +7072,28 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cursor_and_hermes() {
|
||||
async fn per_session_memory_overrides_deliver_only_for_native_claude_and_codex() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::write(root.join("AGENTS.md"), "# Workspace Rules\nRun vitest first.\n").unwrap();
|
||||
std::fs::write(root.join("CLAUDE.local.md"), "Noisy local draft\n").unwrap();
|
||||
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(root, agent.clone());
|
||||
mgr.set_memory_policy_hook(Box::new({
|
||||
let root = root.to_path_buf();
|
||||
move || memory::MemoryPolicy {
|
||||
user: AgentMemorySettings { auto_memory: AutoMemoryMode::ReadWrite, ..Default::default() },
|
||||
user: AgentMemorySettings {
|
||||
providers: BTreeMap::from([
|
||||
("claude".into(), AgentProviderMemoryPolicy { auto_memory: AutoMemoryMode::ReadWrite }),
|
||||
("codex".into(), AgentProviderMemoryPolicy { auto_memory: AutoMemoryMode::ReadWrite }),
|
||||
]),
|
||||
},
|
||||
workspace: AgentMemorySettings::default(),
|
||||
workspace_trusted: true,
|
||||
workspace_roots: vec![root.clone()],
|
||||
}
|
||||
}));
|
||||
|
||||
// 1. Claude task with initial `ReadOnly` + muted `CLAUDE.local.md`, then updated while idle, forked, and deleted.
|
||||
// 1. Native Claude task with initial `Off`, then updated while idle, then forked.
|
||||
let claude_task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
@@ -6744,12 +7102,10 @@ async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cu
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
worktree_path: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
skill_overrides: BTreeMap::new(),
|
||||
memory_overrides: Some(AgentMemoryOverrides {
|
||||
auto_memory: Some(AutoMemoryMode::ReadOnly),
|
||||
entries: BTreeMap::from([("claudeWorkspace::CLAUDE.local.md".into(), AgentMemoryMode::Off)]),
|
||||
}),
|
||||
memory_overrides: Some(AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off) }),
|
||||
idle: false,
|
||||
ephemeral: false,
|
||||
})
|
||||
@@ -6760,51 +7116,64 @@ async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cu
|
||||
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
|
||||
assert_eq!(method, "session/new");
|
||||
let mem = payload.unwrap();
|
||||
assert_eq!(mem["autoMemory"], "readOnly");
|
||||
assert_eq!(mem["autoMemory"], "off");
|
||||
assert_eq!(mem["claudeAutoMemory"], false);
|
||||
assert!(
|
||||
mem["claudeMdExcludes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|v| v.as_str().is_some_and(|s| s.ends_with("CLAUDE.local.md")))
|
||||
);
|
||||
}
|
||||
|
||||
// Updating `set_memory_overrides` while idle recycles the session so the next turn reloads (`session/load`) with `Off`.
|
||||
// Updating `set_memory_overrides` while idle recycles the session so the next turn reloads (`session/load`) with `ReadWrite`.
|
||||
let updated = mgr
|
||||
.set_memory_overrides(
|
||||
&claude_task.id,
|
||||
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
|
||||
)
|
||||
.set_memory_overrides(&claude_task.id, AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::ReadWrite) })
|
||||
.unwrap();
|
||||
assert_eq!(updated.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::Off));
|
||||
assert_eq!(updated.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::ReadWrite));
|
||||
mgr.prompt(&claude_task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &claude_task.id, AgentStatus::Ready).await;
|
||||
{
|
||||
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
|
||||
assert_eq!(method, "session/load");
|
||||
assert_eq!(payload.unwrap()["autoMemory"], "off");
|
||||
let mem = payload.unwrap();
|
||||
assert_eq!(mem["autoMemory"], "readWrite");
|
||||
assert_eq!(mem["claudeAutoMemory"], true);
|
||||
}
|
||||
|
||||
// Forking carries `memory_overrides` onto the forked task and sends `_meta.openidea.memory` on `session/fork`.
|
||||
let forked = mgr.fork(&claude_task.id, None).await.unwrap();
|
||||
assert_eq!(forked.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::Off));
|
||||
assert_eq!(forked.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::ReadWrite));
|
||||
{
|
||||
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
|
||||
assert_eq!(method, "session/fork");
|
||||
assert_eq!(payload.unwrap()["autoMemory"], "off");
|
||||
assert_eq!(payload.unwrap()["autoMemory"], "readWrite");
|
||||
}
|
||||
mgr.delete(&claude_task.id, false).await.unwrap();
|
||||
assert!(!memory::farm_dir(&mgr.shared.paths.store_dir, &claude_task.id).exists());
|
||||
|
||||
// 2. Codex, Copilot, Cursor (ACP), and Hermes (ACP) each receive their normalized `_meta.openidea.memory`.
|
||||
for (provider, expected_field) in [
|
||||
("codex", Some("codexUseMemories")),
|
||||
("copilot", Some("copilotEnableMemory")),
|
||||
("cursor", None),
|
||||
("hermes", None),
|
||||
] {
|
||||
// 2. Native Codex delivers `codexUseMemories` / `codexGenerateMemories`.
|
||||
let codex_task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "codex".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
worktree_path: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
skill_overrides: BTreeMap::new(),
|
||||
memory_overrides: Some(AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::ReadOnly) }),
|
||||
idle: false,
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &codex_task.id, AgentStatus::Ready).await;
|
||||
{
|
||||
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
|
||||
assert_eq!(method, "session/new");
|
||||
let mem = payload.unwrap();
|
||||
assert_eq!(mem["autoMemory"], "readOnly");
|
||||
assert_eq!(mem["codexUseMemories"], true);
|
||||
assert_eq!(mem["codexGenerateMemories"], false);
|
||||
}
|
||||
|
||||
// 3. ACP and non-native providers (copilot, cursor, hermes, claude-acp) receive NO `_meta.openidea.memory`.
|
||||
for provider in ["copilot", "cursor", "hermes", "claude-acp"] {
|
||||
let t = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
@@ -6813,12 +7182,10 @@ async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cu
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
worktree_path: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
skill_overrides: BTreeMap::new(),
|
||||
memory_overrides: Some(AgentMemoryOverrides {
|
||||
auto_memory: Some(AutoMemoryMode::ReadOnly),
|
||||
entries: BTreeMap::new(),
|
||||
}),
|
||||
memory_overrides: Some(AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off) }),
|
||||
idle: false,
|
||||
ephemeral: false,
|
||||
})
|
||||
@@ -6827,11 +7194,7 @@ async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cu
|
||||
wait_for(&mgr, &t.id, AgentStatus::Ready).await;
|
||||
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
|
||||
assert_eq!(method, "session/new", "provider {provider}");
|
||||
let mem = payload.expect("memory delivery present");
|
||||
assert_eq!(mem["autoMemory"], "readOnly", "provider {provider}");
|
||||
if let Some(field) = expected_field {
|
||||
assert!(mem.get(field).is_some(), "provider {provider} missing {field}: {mem}");
|
||||
}
|
||||
assert!(payload.is_none(), "provider {provider} should not receive memory delivery: {payload:?}");
|
||||
}
|
||||
|
||||
mgr.shutdown();
|
||||
@@ -6866,6 +7229,7 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
worktree_path: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::from([
|
||||
@@ -7015,6 +7379,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
|
||||
config: vec![AgentConfigChoice { id: "context_tier".into(), value: "long_context".into() }],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
worktree_path: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
@@ -7043,6 +7408,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
worktree_path: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
@@ -7745,12 +8111,8 @@ async fn metadata_edits_do_not_bump_updated_ms() {
|
||||
mgr.set_skill_overrides(&task.id, BTreeMap::from([("triage".into(), AgentSkillMode::Off)])).unwrap();
|
||||
assert_eq!(after_skill.updated_ms, fixed_ms);
|
||||
|
||||
let after_memory = mgr
|
||||
.set_memory_overrides(
|
||||
&task.id,
|
||||
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
|
||||
)
|
||||
.unwrap();
|
||||
let after_memory =
|
||||
mgr.set_memory_overrides(&task.id, AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off) }).unwrap();
|
||||
assert_eq!(after_memory.updated_ms, fixed_ms);
|
||||
}
|
||||
|
||||
@@ -7772,3 +8134,162 @@ async fn an_accepted_scheduled_prompt_no_longer_reads_as_ready() {
|
||||
assert_eq!(mgr.task_snapshot(&task.id).unwrap().status, AgentStatus::Starting);
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn shared_worktree_delete_preserves_checkout_across_subdirs() {
|
||||
let repo = Checkout::new(Eol::Lf);
|
||||
std::fs::create_dir_all(repo.dir.join("packages").join("app")).unwrap();
|
||||
repo.write("packages/app/a.txt", "hello\n");
|
||||
repo.commit("init");
|
||||
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
|
||||
let root_task = mgr
|
||||
.create(NewAgentTask {
|
||||
provider: "claude".into(),
|
||||
prompt: text("again"),
|
||||
isolation: Isolation::Worktree,
|
||||
idle: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Reuse the same worktree for a task rooted in a subdirectory of the repository.
|
||||
let sub_task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: Some(IpcPath(repo.dir.join("packages").join("app"))),
|
||||
provider: "claude".into(),
|
||||
prompt: text("again"),
|
||||
isolation: Isolation::Worktree,
|
||||
worktree_path: Some(root_task.cwd.clone()),
|
||||
idle: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_ne!(root_task.cwd.0, sub_task.cwd.0);
|
||||
assert!(sub_task.cwd.0.starts_with(&root_task.cwd.0));
|
||||
|
||||
// Deleting the root task with `remove_worktree = true` MUST keep the shared worktree intact.
|
||||
mgr.delete(&root_task.id, true).await.unwrap();
|
||||
assert!(sub_task.cwd.0.exists(), "shared worktree was deleted while subdir sibling still exists");
|
||||
|
||||
// Deleting the final surviving task removes the worktree.
|
||||
mgr.delete(&sub_task.id, true).await.unwrap();
|
||||
assert!(!root_task.cwd.0.exists(), "worktree should be removed once no tasks share it");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn checkout_branch_guards_archived_untrusted_busy_siblings_and_updates_base_commit() {
|
||||
let repo = Checkout::new(Eol::Lf);
|
||||
repo.write("a.txt", "base\n");
|
||||
repo.commit("init");
|
||||
// Create a diverged branch with its own commit.
|
||||
repo.git(&["checkout", "-q", "-b", "feat/diverged"]);
|
||||
repo.write("diverged.txt", "from diverged\n");
|
||||
repo.commit("diverged commit");
|
||||
let diverged_head = worktree::head_of(&repo.dir).unwrap().1;
|
||||
repo.git(&["checkout", "-q", "main"]);
|
||||
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
|
||||
let wt_a = mgr
|
||||
.create(NewAgentTask {
|
||||
provider: "claude".into(),
|
||||
prompt: text("again"),
|
||||
isolation: Isolation::Worktree,
|
||||
idle: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let wt_b = mgr
|
||||
.create(NewAgentTask {
|
||||
provider: "claude".into(),
|
||||
prompt: text("again"),
|
||||
isolation: Isolation::Worktree,
|
||||
worktree_path: Some(wt_a.cwd.clone()),
|
||||
idle: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let original_base_commit = wt_a.base_commit.clone();
|
||||
|
||||
// 1. Busy sibling blocks checkout on the shared worktree.
|
||||
mgr.task(&wt_b.id).unwrap().state.lock().busy = true;
|
||||
let err = mgr.checkout_branch(&wt_a.id, "feat/diverged", false).await.unwrap_err();
|
||||
assert!(err.to_string().contains("running"), "unexpected error: {err}");
|
||||
mgr.task(&wt_b.id).unwrap().state.lock().busy = false;
|
||||
|
||||
// 2. Creating a new branch (`create == true`) updates `branch` on both siblings while preserving `base_commit`.
|
||||
let out = mgr.checkout_branch(&wt_a.id, "feat/new-from-wt", true).await.unwrap();
|
||||
assert_eq!(out, ide_vcs::CheckoutOutcome::Done);
|
||||
let snap_a = mgr.task_snapshot(&wt_a.id).unwrap();
|
||||
let snap_b = mgr.task_snapshot(&wt_b.id).unwrap();
|
||||
assert_eq!(snap_a.branch.as_deref(), Some("feat/new-from-wt"));
|
||||
assert_eq!(snap_b.branch.as_deref(), Some("feat/new-from-wt"));
|
||||
assert_eq!(snap_a.base_commit, original_base_commit);
|
||||
assert_eq!(snap_b.base_commit, original_base_commit);
|
||||
|
||||
// 3. Switching to an existing diverged branch (`create == false`) updates `branch`, `base`,
|
||||
// and `base_commit` on both siblings so unrelated commits don't pollute Changes.
|
||||
let out = mgr.checkout_branch(&wt_a.id, "feat/diverged", false).await.unwrap();
|
||||
assert_eq!(out, ide_vcs::CheckoutOutcome::Done);
|
||||
let snap_a = mgr.task_snapshot(&wt_a.id).unwrap();
|
||||
let snap_b = mgr.task_snapshot(&wt_b.id).unwrap();
|
||||
assert_eq!(snap_a.branch.as_deref(), Some("feat/diverged"));
|
||||
assert_eq!(snap_b.branch.as_deref(), Some("feat/diverged"));
|
||||
assert_eq!(snap_a.base.as_deref(), Some("feat/diverged"));
|
||||
assert_eq!(snap_a.base_commit.as_deref(), Some(diverged_head.as_str()));
|
||||
assert_eq!(snap_b.base_commit.as_deref(), Some(diverged_head.as_str()));
|
||||
let grouped = mgr.grouped_changes(&wt_a.id).await.unwrap();
|
||||
assert!(grouped.commits.is_empty(), "unrelated commits on switched branch leaked into Changes");
|
||||
assert!(grouped.uncommitted.is_empty());
|
||||
|
||||
// 4. Archived task rejects branch checkout.
|
||||
mgr.archive(&wt_a.id).unwrap();
|
||||
let err = mgr.checkout_branch(&wt_a.id, "feat/new-from-wt", false).await.unwrap_err();
|
||||
assert!(err.to_string().contains("archived"), "unexpected error: {err}");
|
||||
|
||||
// 5. Untrusted local repo rejects `checkout_branch`.
|
||||
let local_task = mgr
|
||||
.create(NewAgentTask {
|
||||
provider: "claude".into(),
|
||||
prompt: text("again"),
|
||||
isolation: Isolation::Local,
|
||||
idle: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
mgr.set_repo_trust_hook(Arc::new(|_| false));
|
||||
let err = mgr.checkout_branch(&local_task.id, "feat/diverged", false).await.unwrap_err();
|
||||
assert!(err.to_string().contains("not trusted"), "unexpected error: {err}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn rollback_clears_prompt_suggestions() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
|
||||
let task = mgr
|
||||
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
{
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
*handle.state.lock().task.prompt_suggestions = vec!["Follow up".into()];
|
||||
}
|
||||
assert_eq!(mgr.task_snapshot(&task.id).unwrap().prompt_suggestions.as_slice(), ["Follow up"]);
|
||||
|
||||
mgr.rollback(&task.id, 0, false).await.unwrap();
|
||||
assert!(mgr.task_snapshot(&task.id).unwrap().prompt_suggestions.is_empty());
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
use crate::model::{AgentEntry, AgentImage, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
|
||||
use ide_core::IpcPath;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Tool output kept per call; longer output keeps its tail.
|
||||
const MAX_OUTPUT: usize = 64 * 1024;
|
||||
@@ -316,9 +316,9 @@ impl Timeline {
|
||||
changed
|
||||
}
|
||||
|
||||
/// Settles what an ended turn left open: running tools and pending permissions,
|
||||
/// and records when the turn ended (`done`) on the message that started it.
|
||||
pub fn end_turn(&mut self, done: Option<f64>) -> Vec<usize> {
|
||||
/// Settles what an ended turn left open: running tools and pending permissions (but the
|
||||
/// requests in `open`), and records when the turn ended (`done`) on the message that started it.
|
||||
pub fn end_turn(&mut self, done: Option<f64>, open: &HashSet<u32>) -> Vec<usize> {
|
||||
let mut changed = Vec::new();
|
||||
// A steered message rides along in a running turn; the one that started it owns its end.
|
||||
let started = self.entries.iter().rposition(|e| matches!(e, AgentEntry::User { steered: false, .. }));
|
||||
@@ -334,7 +334,7 @@ impl Timeline {
|
||||
*status = AgentToolStatus::Failed;
|
||||
changed.push(i);
|
||||
}
|
||||
AgentEntry::Permission { chosen, .. } if chosen.is_none() => {
|
||||
AgentEntry::Permission { id, chosen, .. } if chosen.is_none() && !open.contains(id) => {
|
||||
*chosen = Some("Cancelled".into());
|
||||
changed.push(i);
|
||||
}
|
||||
@@ -366,7 +366,8 @@ fn subagent_status(state: &Value) -> Option<(AgentSubagentStatus, Option<String>
|
||||
})
|
||||
}
|
||||
|
||||
/// Folds a tool update's content into its output, diffs and images.
|
||||
/// Replaces a tool's output, diffs and images with `content`: an update's `content` replaces the
|
||||
/// whole array, so what it leaves out is gone.
|
||||
fn merge_content(
|
||||
content: &[Value],
|
||||
output: &mut Option<String>,
|
||||
@@ -398,20 +399,14 @@ fn merge_content(
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !text.is_empty() {
|
||||
// The command a call announced (`$ cmd`) stays above the result that replaces it.
|
||||
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
|
||||
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
|
||||
text = format!("{command}\n{text}");
|
||||
}
|
||||
*output = Some(tail(text));
|
||||
}
|
||||
if !new_diffs.is_empty() {
|
||||
*diffs = new_diffs;
|
||||
}
|
||||
if !new_images.is_empty() {
|
||||
*images = new_images;
|
||||
// The command a call announced (`$ cmd`) stays above the result that replaces it.
|
||||
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
|
||||
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
|
||||
text = if text.is_empty() { command.to_owned() } else { format!("{command}\n{text}") };
|
||||
}
|
||||
*output = (!text.is_empty()).then(|| tail(text));
|
||||
*diffs = new_diffs;
|
||||
*images = new_images;
|
||||
}
|
||||
|
||||
/// The text of a list of content blocks, one per line.
|
||||
@@ -473,7 +468,7 @@ mod tests {
|
||||
let update = json!({"sessionUpdate":"user_question","id":"call-1","title":"Which?",
|
||||
"questions":[{"answerKey":"q1","question":"Which?","options":[]}]});
|
||||
assert_eq!(t.apply(&update).changed, vec![0]);
|
||||
assert!(t.end_turn(None).is_empty());
|
||||
assert!(t.end_turn(None, &HashSet::new()).is_empty());
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: None, .. }));
|
||||
let saved = serde_json::to_string(&t.entries).unwrap();
|
||||
let mut t = Timeline::from_entries(serde_json::from_str(&saved).unwrap());
|
||||
@@ -621,6 +616,42 @@ mod tests {
|
||||
assert!(t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "zz"})).changed.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_update_with_content_replaces_all_of_the_calls_content() {
|
||||
let text = |t: &str| json!({"type": "content", "content": {"type": "text", "text": t}});
|
||||
let update = |id: &str, content: Value| json!({"sessionUpdate": "tool_call_update", "toolCallId": id, "content": content});
|
||||
let mut t = Timeline::default();
|
||||
// An edit announced with its diff that fails: the error replaces the diff.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "e1", "title": "Edit a.txt", "kind": "edit",
|
||||
"status": "pending",
|
||||
"content": [{"type": "diff", "path": "/p/a.txt", "oldText": "one\n", "newText": "two\nthree\n"}]}));
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "e1", "status": "failed",
|
||||
"content": [text("old_string not found in a.txt")]}));
|
||||
let AgentEntry::Tool { diffs, output, .. } = &t.entries[0] else { panic!() };
|
||||
assert!(diffs.is_empty(), "{diffs:?}");
|
||||
assert_eq!(output.as_deref(), Some("old_string not found in a.txt"));
|
||||
// Text replaces images, and no content clears the output.
|
||||
let image =
|
||||
json!({"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": "iVBORw0KGgo="}});
|
||||
t.apply(&update("e1", json!([image])));
|
||||
t.apply(&update("e1", json!([text("done")])));
|
||||
let AgentEntry::Tool { images, output, .. } = &t.entries[0] else { panic!() };
|
||||
assert!(images.is_empty());
|
||||
assert_eq!(output.as_deref(), Some("done"));
|
||||
t.apply(&update("e1", json!([])));
|
||||
let AgentEntry::Tool { output, .. } = &t.entries[0] else { panic!() };
|
||||
assert_eq!(*output, None);
|
||||
// The command a call announced (`$ cmd`) stays above what replaces its output.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "r1", "title": "Run make", "kind": "execute",
|
||||
"content": [text("$ make")]}));
|
||||
t.apply(&update("r1", json!([text("building")])));
|
||||
let AgentEntry::Tool { output, .. } = &t.entries[1] else { panic!() };
|
||||
assert_eq!(output.as_deref(), Some("$ make\nbuilding"));
|
||||
t.apply(&update("r1", json!([])));
|
||||
let AgentEntry::Tool { output, .. } = &t.entries[1] else { panic!() };
|
||||
assert_eq!(output.as_deref(), Some("$ make"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_is_one_entry_and_end_turn_settles_open_items() {
|
||||
let mut t = Timeline::default();
|
||||
@@ -630,16 +661,20 @@ mod tests {
|
||||
t.push(AgentEntry::Agent { text: "between".into() });
|
||||
assert_eq!(t.apply(&plan("completed")).changed, vec![0]);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "title": "Run", "status": "in_progress"}));
|
||||
t.push(AgentEntry::Permission {
|
||||
id: 1,
|
||||
let permission = |id| AgentEntry::Permission {
|
||||
id,
|
||||
title: "Run?".into(),
|
||||
command: None,
|
||||
options: vec![],
|
||||
questions: vec![],
|
||||
form: None,
|
||||
chosen: None,
|
||||
});
|
||||
assert_eq!(t.end_turn(None), vec![2, 3]);
|
||||
};
|
||||
t.push(permission(1));
|
||||
// A request that stays open (a subagent's that works on) keeps its card.
|
||||
t.push(permission(2));
|
||||
assert_eq!(t.end_turn(None, &HashSet::from([2])), vec![2, 3]);
|
||||
assert!(matches!(t.entries[4], AgentEntry::Permission { chosen: None, .. }));
|
||||
let again = Timeline::from_entries(t.entries.clone());
|
||||
assert_eq!(again.plan, Some(0));
|
||||
assert_eq!(again.tools.get("c"), Some(&2));
|
||||
@@ -661,11 +696,11 @@ mod tests {
|
||||
t.push(user(1.0));
|
||||
t.push(AgentEntry::Agent { text: "a".into() });
|
||||
t.push(user(2.0));
|
||||
assert_eq!(t.end_turn(Some(5.0)), vec![2]);
|
||||
assert_eq!(t.end_turn(Some(5.0), &HashSet::new()), vec![2]);
|
||||
assert!(matches!(t.entries[0], AgentEntry::User { done_ms: None, .. }));
|
||||
assert!(matches!(t.entries[2], AgentEntry::User { done_ms: Some(5.0), .. }));
|
||||
// Settled once: a later end (a restart) doesn't move it.
|
||||
assert_eq!(t.end_turn(Some(9.0)), Vec::<usize>::new());
|
||||
assert_eq!(t.end_turn(Some(9.0), &HashSet::new()), Vec::<usize>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -686,7 +721,7 @@ mod tests {
|
||||
t.push(user(2.0, true));
|
||||
// The steered message rides along in the turn: the reply's time belongs to the
|
||||
// message that started it.
|
||||
assert_eq!(t.end_turn(Some(5.0)), vec![0]);
|
||||
assert_eq!(t.end_turn(Some(5.0), &HashSet::new()), vec![0]);
|
||||
assert!(matches!(t.entries[0], AgentEntry::User { done_ms: Some(5.0), .. }));
|
||||
assert!(matches!(t.entries[2], AgentEntry::User { done_ms: None, .. }));
|
||||
}
|
||||
|
||||
@@ -287,6 +287,88 @@ pub(crate) fn create_for_task(
|
||||
Ok(Created { path, cwd: canon_cwd, branch, base, base_commit })
|
||||
}
|
||||
|
||||
/// Validates and opens an existing managed worktree under `worktrees_dir` so a new task can
|
||||
/// reuse it. Rejects paths outside `worktrees_dir`, non-directories, non-linked repositories,
|
||||
/// or worktrees belonging to a different Git repository than `project_root`. Preserves any
|
||||
/// project-relative subdirectory inside `project_root` just like [`create_for_task`].
|
||||
pub(crate) fn reuse_for_task(project_root: &Path, worktrees_dir: &Path, worktree_path: &Path) -> IdeResult<Created> {
|
||||
let canon_input = verify_confined_worktree_cwd(worktrees_dir, worktree_path)?;
|
||||
if !canon_input.is_dir() {
|
||||
return Err(IdeError::not_found(format!("worktree {} does not exist", worktree_path.display())));
|
||||
}
|
||||
let project_repo = repo_at(project_root)?;
|
||||
let wt_repo = repo_at(&canon_input)?;
|
||||
let [_, project_common] = project_repo.metadata_dirs()?;
|
||||
let [wt_git_dir, wt_common] = wt_repo.metadata_dirs()?;
|
||||
let canon_wt_git_dir = dunce::canonicalize(&wt_git_dir)?;
|
||||
let canon_wt_common = dunce::canonicalize(&wt_common)?;
|
||||
let canon_project_common = dunce::canonicalize(&project_common)?;
|
||||
if canon_wt_git_dir == canon_wt_common || canon_wt_common != canon_project_common {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"worktree {} is not a linked worktree of this repository",
|
||||
worktree_path.display()
|
||||
)));
|
||||
}
|
||||
let canon_wt_root = dunce::canonicalize(wt_repo.root())?;
|
||||
let canon_wt_dir = dunce::canonicalize(worktrees_dir)?;
|
||||
if !canon_wt_root.starts_with(&canon_wt_dir)
|
||||
|| canon_wt_root == canon_wt_dir
|
||||
|| canon_wt_root.parent() != Some(canon_wt_dir.as_path())
|
||||
{
|
||||
return Err(IdeError::invalid("worktree root does not match managed worktrees directory"));
|
||||
}
|
||||
let canon_repo = dunce::canonicalize(project_repo.root())?;
|
||||
let canon_proj = dunce::canonicalize(project_root)?;
|
||||
let rel_subdir = if canon_proj != canon_repo {
|
||||
canon_proj
|
||||
.strip_prefix(&canon_repo)
|
||||
.map_err(|_| {
|
||||
IdeError::invalid(format!(
|
||||
"{} is outside git repository {}",
|
||||
canon_proj.display(),
|
||||
canon_repo.display()
|
||||
))
|
||||
})?
|
||||
.to_path_buf()
|
||||
} else {
|
||||
PathBuf::new()
|
||||
};
|
||||
let raw_cwd =
|
||||
if rel_subdir.as_os_str().is_empty() { canon_wt_root.clone() } else { canon_wt_root.join(&rel_subdir) };
|
||||
if !raw_cwd.is_dir() {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"project folder {} does not exist in worktree {}",
|
||||
rel_subdir.display(),
|
||||
canon_wt_root.display()
|
||||
)));
|
||||
}
|
||||
let canon_cwd = verify_confined_worktree_subdir(&canon_wt_root, &raw_cwd)?;
|
||||
let (branch, base_commit) = head_of(&canon_cwd)?;
|
||||
Ok(Created { path: canon_wt_root, cwd: canon_cwd, branch: branch.clone(), base: branch, base_commit })
|
||||
}
|
||||
|
||||
/// Checks out (or creates and checks out) `branch` in `cwd` using Smart checkout so uncommitted
|
||||
/// edits are stashed and restored across the switch. Returns the resulting branch name, HEAD
|
||||
/// commit (when available), and checkout outcome.
|
||||
pub(crate) fn checkout_branch(
|
||||
cwd: &Path,
|
||||
branch: &str,
|
||||
create: bool,
|
||||
) -> IdeResult<(String, Option<String>, ide_vcs::CheckoutOutcome)> {
|
||||
let name = branch.trim();
|
||||
if name.is_empty() {
|
||||
return Err(IdeError::invalid("branch name cannot be empty"));
|
||||
}
|
||||
let repo = repo_at(cwd)?;
|
||||
let options = ide_vcs::CheckoutOptions { mode: ide_vcs::CheckoutMode::Smart, ..Default::default() };
|
||||
let outcome = repo.checkout_with(name, create, &options)?;
|
||||
let (current, head_commit) = match head_of(cwd) {
|
||||
Ok((b, commit)) => (b, Some(commit)),
|
||||
Err(_) => (name.to_owned(), None),
|
||||
};
|
||||
Ok((current, head_commit, outcome))
|
||||
}
|
||||
|
||||
fn verify_confined_worktree_subdir(canon_wt_root: &Path, target_cwd: &Path) -> IdeResult<PathBuf> {
|
||||
let canon_cwd = dunce::canonicalize(target_cwd)?;
|
||||
let real_wt = ide_core::real_path::resolve_real(canon_wt_root);
|
||||
@@ -327,23 +409,60 @@ pub(crate) fn verify_confined_worktree_cwd(worktrees_dir: &Path, cwd: &Path) ->
|
||||
verify_confined_worktree_subdir(&canon_wt_root, cwd)
|
||||
}
|
||||
|
||||
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
|
||||
if let Ok(rel) = path.strip_prefix(worktrees_dir)
|
||||
/// Returns a canonical comparison key for the managed worktree checkout root containing `path`,
|
||||
/// so two tasks pointing to different subdirs or path casings of the same worktree match.
|
||||
pub(crate) fn shared_worktree_root(worktrees_dir: &Path, path: &Path) -> PathBuf {
|
||||
let (root, _) = worktree_checkout_root(worktrees_dir, path);
|
||||
let resolved = dunce::canonicalize(&root).unwrap_or(root);
|
||||
normalize_path_key(resolved)
|
||||
}
|
||||
|
||||
pub(crate) fn normalize_path_key(path: PathBuf) -> PathBuf {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
PathBuf::from(path.to_string_lossy().replace('/', "\\").to_lowercase())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
fn first_child_under(base: &Path, path: &Path) -> Option<PathBuf> {
|
||||
if let Ok(rel) = path.strip_prefix(base)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (worktrees_dir.join(first), worktrees_dir.to_path_buf());
|
||||
return Some(base.join(first));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let base_comps: Vec<String> =
|
||||
base.components().map(|c| c.as_os_str().to_string_lossy().to_lowercase()).collect();
|
||||
let path_comps: Vec<std::path::Component<'_>> = path.components().collect();
|
||||
if path_comps.len() > base_comps.len()
|
||||
&& base_comps
|
||||
.iter()
|
||||
.zip(path_comps.iter())
|
||||
.all(|(a, b)| a == &b.as_os_str().to_string_lossy().to_lowercase())
|
||||
{
|
||||
return Some(base.join(path_comps[base_comps.len()]));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
|
||||
if let Some(child) = first_child_under(worktrees_dir, path) {
|
||||
return (child, worktrees_dir.to_path_buf());
|
||||
}
|
||||
if let Ok(canon_wt_dir) = dunce::canonicalize(worktrees_dir) {
|
||||
if let Ok(rel) = path.strip_prefix(&canon_wt_dir)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (canon_wt_dir.join(first), canon_wt_dir);
|
||||
if let Some(child) = first_child_under(&canon_wt_dir, path) {
|
||||
return (child, canon_wt_dir);
|
||||
}
|
||||
if let Ok(canon_path) = dunce::canonicalize(path)
|
||||
&& let Ok(rel) = canon_path.strip_prefix(&canon_wt_dir)
|
||||
&& let Some(first) = rel.components().next()
|
||||
&& let Some(child) = first_child_under(&canon_wt_dir, &canon_path)
|
||||
{
|
||||
return (canon_wt_dir.join(first), canon_wt_dir);
|
||||
return (child, canon_wt_dir);
|
||||
}
|
||||
}
|
||||
(path.to_path_buf(), worktrees_dir.to_path_buf())
|
||||
@@ -2314,4 +2433,109 @@ mod tests {
|
||||
"symlink swap on worktree reuse must be rejected: {reuse_err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reuse_for_task_validates_confinement_and_repo_membership() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "hello\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let other = tmp.path().join("other");
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
git(&other, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(other.join("b.txt"), "world\n").unwrap();
|
||||
git(&other, &["add", "."]);
|
||||
git(&other, &["commit", "-q", "-m", "init other"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
let created = create_for_task(&repo, &wt_dir, "task-1", "Feature work", None).unwrap();
|
||||
|
||||
// Reusing a managed worktree of the same repository succeeds and reports its live branch.
|
||||
let reused = super::reuse_for_task(&repo, &wt_dir, &created.cwd).unwrap();
|
||||
assert_eq!(reused.cwd, created.cwd);
|
||||
assert_eq!(reused.branch, created.branch);
|
||||
assert_eq!(reused.base_commit, created.base_commit);
|
||||
|
||||
// Paths outside `worktrees_dir` are rejected.
|
||||
assert!(super::reuse_for_task(&repo, &wt_dir, &repo).is_err());
|
||||
|
||||
// Worktrees belonging to a different repository are rejected.
|
||||
let other_wt = create_for_task(&other, &wt_dir, "task-2", "Other work", None).unwrap();
|
||||
assert!(super::reuse_for_task(&repo, &wt_dir, &other_wt.cwd).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkout_branch_creates_and_switches_branches_in_worktree() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "hello\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
let created = create_for_task(&repo, &wt_dir, "task-1", "Feature work", None).unwrap();
|
||||
|
||||
let (branch, head_commit, outcome) = super::checkout_branch(&created.cwd, "feat/follow-up", true).unwrap();
|
||||
assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done);
|
||||
assert_eq!(branch, "feat/follow-up");
|
||||
assert_eq!(head_commit.as_deref(), Some(created.base_commit.as_str()));
|
||||
|
||||
let (back, back_commit, outcome) = super::checkout_branch(&created.cwd, &created.branch, false).unwrap();
|
||||
assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done);
|
||||
assert_eq!(back, created.branch);
|
||||
assert_eq!(back_commit.as_deref(), Some(created.base_commit.as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reuse_for_task_resolves_subdir_consistently_and_rejects_standalone_repo() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
let sub = repo.join("packages").join("app");
|
||||
std::fs::create_dir_all(&sub).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(sub.join("a.txt"), "hello\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
let created = create_for_task(&sub, &wt_dir, "task-sub", "Subdir work", None).unwrap();
|
||||
assert!(created.cwd.ends_with(Path::new("packages").join("app")));
|
||||
|
||||
// Passing either the worktree root or the subdir cwd resolves to the same subdir cwd.
|
||||
let reused_from_root = super::reuse_for_task(&sub, &wt_dir, &created.path).unwrap();
|
||||
assert_eq!(reused_from_root.cwd, created.cwd);
|
||||
assert_eq!(reused_from_root.path, dunce::canonicalize(&created.path).unwrap());
|
||||
|
||||
let reused_from_sub = super::reuse_for_task(&sub, &wt_dir, &created.cwd).unwrap();
|
||||
assert_eq!(reused_from_sub.cwd, created.cwd);
|
||||
|
||||
// `shared_worktree_root` matches root and subdir (and mixed casing on Windows).
|
||||
assert_eq!(
|
||||
super::shared_worktree_root(&wt_dir, &created.path),
|
||||
super::shared_worktree_root(&wt_dir, &created.cwd)
|
||||
);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let upper = PathBuf::from(created.cwd.to_string_lossy().to_uppercase());
|
||||
assert_eq!(
|
||||
super::shared_worktree_root(&wt_dir, &created.path),
|
||||
super::shared_worktree_root(&wt_dir, &upper)
|
||||
);
|
||||
}
|
||||
|
||||
// A standalone repo placed directly inside `worktrees_dir` (not a linked worktree) is rejected.
|
||||
let standalone = wt_dir.join("standalone");
|
||||
std::fs::create_dir_all(&standalone).unwrap();
|
||||
git(&standalone, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(standalone.join("x.txt"), "x\n").unwrap();
|
||||
git(&standalone, &["add", "."]);
|
||||
git(&standalone, &["commit", "-q", "-m", "standalone"]);
|
||||
assert!(super::reuse_for_task(&standalone, &wt_dir, &standalone).is_err());
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
|
||||
let repo = crate::maven::local_repository_for(&p.options);
|
||||
args.extend([
|
||||
"process-resources".into(),
|
||||
crate::maven::plugin_goal("help:evaluate", repo.as_deref()),
|
||||
crate::maven::plugin_goal("help:evaluate", repo.as_deref(), crate::maven::maven_version(&p.command)),
|
||||
"-Dexpression=project.build.outputDirectory".into(),
|
||||
format!("-Doutput={}", manifest.display()),
|
||||
]);
|
||||
|
||||
@@ -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)");
|
||||
|
||||
@@ -64,6 +64,7 @@ pub(super) fn build_javac_step(
|
||||
cwd: &Path,
|
||||
out_dir: &Path,
|
||||
classpath: &str,
|
||||
encoding: &str,
|
||||
sources: &[PathBuf],
|
||||
release: Vec<String>,
|
||||
file: &Path,
|
||||
@@ -73,7 +74,7 @@ pub(super) fn build_javac_step(
|
||||
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", out_dir.display())))?;
|
||||
// Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
|
||||
let mut step = BuildStep::new(javac, &[], cwd, Format::Gradle);
|
||||
step.args.extend(["-encoding".into(), "UTF-8".into(), "-g".into()]);
|
||||
step.args.extend(["-encoding".into(), encoding.to_owned(), "-g".into()]);
|
||||
step.args.extend(["-d".into(), out_dir.to_string_lossy().into_owned()]);
|
||||
if !classpath.is_empty() {
|
||||
step.args.extend(["-cp".into(), classpath.to_owned()]);
|
||||
@@ -118,6 +119,8 @@ pub struct SingleFileTarget {
|
||||
pub pl: String,
|
||||
/// `maven.compiler.release` (or equivalent) of the module's project.
|
||||
pub java_version: Option<u32>,
|
||||
/// `project.build.sourceEncoding` of the module's project, as the POM spells it.
|
||||
pub source_encoding: Option<String>,
|
||||
}
|
||||
|
||||
/// Locates the linked Maven module owning a `.java` source file.
|
||||
@@ -147,7 +150,15 @@ pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeRe
|
||||
// Test sources see the test classpath and compile into test classes.
|
||||
let test = is_test_source(&rel);
|
||||
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
|
||||
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
|
||||
Ok(SingleFileTarget {
|
||||
module,
|
||||
test,
|
||||
out_dir,
|
||||
top: top.clone(),
|
||||
pl,
|
||||
java_version: project.java_version,
|
||||
source_encoding: project.source_encoding.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The Maven reactor target for a launch module whose source file is not known yet.
|
||||
@@ -165,7 +176,15 @@ fn module_target(root: &Path, model: &BuildModel, module: &Path, test: bool) ->
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven reactor found for module"))?;
|
||||
let pl = maven::module_selector(root, top, project).unwrap_or_default();
|
||||
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
|
||||
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
|
||||
Ok(SingleFileTarget {
|
||||
module,
|
||||
test,
|
||||
out_dir,
|
||||
top: top.clone(),
|
||||
pl,
|
||||
java_version: project.java_version,
|
||||
source_encoding: project.source_encoding.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// `javac` for the module: its `JAVA_HOME`, else `PATH`.
|
||||
@@ -405,8 +424,11 @@ fn classpaths(
|
||||
if compile_first {
|
||||
args.push("compile");
|
||||
}
|
||||
let build_classpath =
|
||||
maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref());
|
||||
let build_classpath = maven::plugin_goal(
|
||||
"dependency:build-classpath",
|
||||
maven::local_repository_for(&top.options).as_deref(),
|
||||
maven::maven_version(&top.command),
|
||||
);
|
||||
args.extend([build_classpath.as_str(), output_arg.as_str(), scope_arg.as_str(), "-q"]);
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
|
||||
@@ -468,7 +490,17 @@ fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget)
|
||||
pub fn javac_step(target: &SingleFileTarget, file: &Path, classpath: &str, javac: &str) -> IdeResult<BuildStep> {
|
||||
let sources = source_roots(target);
|
||||
let release = release_args(target.java_version, java_home_major(&target.top.env));
|
||||
build_javac_step(javac, &target.module, &target.out_dir, classpath, &sources, release, file, target.top.env.clone())
|
||||
build_javac_step(
|
||||
javac,
|
||||
&target.module,
|
||||
&target.out_dir,
|
||||
classpath,
|
||||
target.source_encoding.as_deref().unwrap_or("UTF-8"),
|
||||
&sources,
|
||||
release,
|
||||
file,
|
||||
target.top.env.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The module's Java source folders that exist, generated ones included; test sources see
|
||||
@@ -571,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") {
|
||||
@@ -644,8 +675,17 @@ pub fn gradle_compile_file_plan(
|
||||
}
|
||||
let javac = find_javac(&gradle.env);
|
||||
let release = release_args(cp.release.or(gradle.java_version), java_home_major(&gradle.env));
|
||||
let step =
|
||||
build_javac_step(&javac, &module_dir, &out_dir, &classpath, &sources, release, file, gradle.env.clone())?;
|
||||
let step = build_javac_step(
|
||||
&javac,
|
||||
&module_dir,
|
||||
&out_dir,
|
||||
&classpath,
|
||||
"UTF-8",
|
||||
&sources,
|
||||
release,
|
||||
file,
|
||||
gradle.env.clone(),
|
||||
)?;
|
||||
Ok(BuildPlan { system: BuildSystem::Gradle, title: format!("Compile {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
@@ -706,6 +746,28 @@ mod tests {
|
||||
assert_eq!(test.out_dir, root.join("app/target/test-classes"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_reads_sources_in_the_encoding_of_the_module_pom() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
fixture(root);
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
|
||||
<artifactId>app</artifactId>
|
||||
<properties><project.build.sourceEncoding>ISO-8859-15</project.build.sourceEncoding></properties></project>"#,
|
||||
);
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
let file = root.join("app/src/main/java/demo/Main.java");
|
||||
let target = single_file_target(root, &model, &file).unwrap();
|
||||
let step = javac_step(&target, &file, "", "javac").unwrap();
|
||||
let at = step.args.iter().position(|a| a == "-encoding").expect("an -encoding");
|
||||
assert_eq!(step.args[at + 1], "ISO-8859-15");
|
||||
assert_eq!(target.source_encoding.as_deref(), Some("ISO-8859-15"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_rejects_non_java_missing_and_unlinked_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -373,7 +373,7 @@ pub fn structure_compile_file_plan(
|
||||
|
||||
let (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
|
||||
let release = single::release_args(level, jdk.map(|j| j.major));
|
||||
let step = single::build_javac_step(&javac, root, out_dir, &cp, &src_roots, release, file, env)?;
|
||||
let step = single::build_javac_step(&javac, root, out_dir, &cp, "UTF-8", &src_roots, release, file, env)?;
|
||||
Ok(BuildPlan { system: BuildSystem::Javac, title: format!("Compile {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,15 @@ def describe = { Project p ->
|
||||
try { p.extensions.findByName('testing')?.suites?.each { suites << it.sources.name } } catch (ignored) {}
|
||||
def ideaTests = [] as Set
|
||||
try { p.extensions.findByName('idea')?.module?.testSources?.files?.each { ideaTests << canon(it) } } catch (ignored) {}
|
||||
// The `Test` tasks running each classes folder, as IDEA maps tests to tasks: a JVM test
|
||||
// suite's tests run with its own task (`integrationTest`), not with `test`.
|
||||
def testTasks = [:]
|
||||
try {
|
||||
p.tasks.withType(Test).each { t ->
|
||||
def dirs = t.hasProperty('testClassesDirs') ? t.testClassesDirs.files : [t.testClassesDir]
|
||||
dirs.findAll { it != null }.each { testTasks.get(canon(it), []) << t.name }
|
||||
}
|
||||
} catch (ignored) {}
|
||||
m.sourceSets = sets.collect { s ->
|
||||
def res = s.resources.srcDirs.collect(canon)
|
||||
def src = s.allSource.srcDirs.collect(canon) - res
|
||||
@@ -49,6 +58,11 @@ def describe = { Project p ->
|
||||
def set = [name: s.name, test: test, src: src, res: res]
|
||||
def processed = processedResources(p, s)
|
||||
if (processed != null) set.processed = processed
|
||||
try {
|
||||
def classes = s.output.hasProperty('classesDirs') ? s.output.classesDirs.files : [s.output.classesDir]
|
||||
def tasks = classes.findAll { it != null }.collectMany { testTasks[canon(it)] ?: [] }.unique()
|
||||
if (!tasks.isEmpty()) set.testTasks = tasks
|
||||
} catch (ignored) {}
|
||||
set
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,47 @@ 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)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -51,6 +92,20 @@ pub struct GradleProject {
|
||||
/// `:buildSrc`); null for the opened build.
|
||||
#[serde(default)]
|
||||
pub build: Option<String>,
|
||||
/// The project's `Test` tasks, or null before Gradle reports the project.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub test_tasks: Option<Vec<GradleTestTask>>,
|
||||
}
|
||||
|
||||
/// A `Test` task and the source folders of the source sets whose test classes it runs.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GradleTestTask {
|
||||
/// Name in its project (`test`, `integrationTest`).
|
||||
pub name: String,
|
||||
/// Project-relative.
|
||||
pub source_folders: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -341,6 +396,7 @@ fn project_at(root: &Path, path: String, name: String, pdir: &Path) -> GradlePro
|
||||
tasks,
|
||||
resolvable_configurations: None,
|
||||
build: None,
|
||||
test_tasks: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -380,6 +436,9 @@ pub struct ReportedSourceSet {
|
||||
/// includes / excludes, extra sources), which the Java language server's copy does not.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub processed: Option<ProcessedResources>,
|
||||
/// The `Test` tasks whose `testClassesDirs` hold the set's classes.
|
||||
#[serde(default, rename = "testTasks", skip_serializing_if = "Vec::is_empty")]
|
||||
pub test_tasks: Vec<String>,
|
||||
}
|
||||
|
||||
/// The task that copies a source set's resources, and where it writes them.
|
||||
@@ -455,6 +514,7 @@ pub fn merge_reported_projects(root: &Path, model: &mut GradleModel, reported: &
|
||||
}
|
||||
project.resolvable_configurations = p.resolvable_configurations.clone();
|
||||
project.build = p.build.clone();
|
||||
project.test_tasks = Some(test_tasks(root, p));
|
||||
project
|
||||
})
|
||||
.collect();
|
||||
@@ -466,6 +526,20 @@ pub fn merge_reported_projects(root: &Path, model: &mut GradleModel, reported: &
|
||||
}
|
||||
}
|
||||
|
||||
fn test_tasks(root: &Path, p: &ReportedProject) -> Vec<GradleTestTask> {
|
||||
let mut out: Vec<GradleTestTask> = Vec::new();
|
||||
for set in &p.source_sets {
|
||||
for name in &set.test_tasks {
|
||||
let folders = set.src.iter().map(|dir| rel(root, Path::new(dir)));
|
||||
match out.iter_mut().find(|t| t.name == *name) {
|
||||
Some(task) => task.source_folders.extend(folders),
|
||||
None => out.push(GradleTestTask { name: name.clone(), source_folders: folders.collect() }),
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Project directories outside `root`, outermost only (`../svc`, not also `../svc/sources/app`):
|
||||
/// the folders IDEA shows as extra top-level module roots.
|
||||
pub fn external_roots<'a>(root: &Path, dirs: impl IntoIterator<Item = &'a str>) -> Vec<PathBuf> {
|
||||
@@ -1545,6 +1619,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#"
|
||||
@@ -1748,4 +1869,48 @@ Pattern: clean<TaskName>: Cleans the output files of a task.
|
||||
assert!(!model.projects[4].tasks.is_empty());
|
||||
assert!(build_files(&root, &model).contains(&ws.join("lib/settings.gradle")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reported_test_tasks_carry_the_source_folders_they_run() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let src = |dir: &str| root.join(dir).to_string_lossy().into_owned();
|
||||
let set = |name: &str, dirs: &[&str], tasks: &[&str]| ReportedSourceSet {
|
||||
name: name.into(),
|
||||
test: !tasks.is_empty(),
|
||||
src: dirs.iter().map(|d| src(d)).collect(),
|
||||
test_tasks: tasks.iter().map(|t| (*t).into()).collect(),
|
||||
..ReportedSourceSet::default()
|
||||
};
|
||||
// As `gradle-model.gradle` prints a project with a JVM test suite.
|
||||
let reported = ReportedProject {
|
||||
path: ":app".into(),
|
||||
dir: src("app"),
|
||||
source_sets: vec![
|
||||
set("main", &["app/src/main/java"], &[]),
|
||||
set("test", &["app/src/test/java"], &["test"]),
|
||||
set(
|
||||
"integrationTest",
|
||||
&["app/src/integrationTest/java", "app/src/integrationTest/kotlin"],
|
||||
&["integrationTest"],
|
||||
),
|
||||
],
|
||||
..ReportedProject::default()
|
||||
};
|
||||
let line = format!("{MODEL_LINE}{}\n", serde_json::to_string(&reported).unwrap());
|
||||
assert!(line.contains(r#""testTasks":["integrationTest"]"#), "{line}");
|
||||
let mut model = GradleModel::default();
|
||||
merge_reported_projects(&root, &mut model, &parse_reported_projects(&line));
|
||||
let task = |name: &str, folders: &[&str]| GradleTestTask {
|
||||
name: name.into(),
|
||||
source_folders: folders.iter().map(|f| (*f).into()).collect(),
|
||||
};
|
||||
assert_eq!(
|
||||
model.projects[0].test_tasks,
|
||||
Some(vec![
|
||||
task("test", &["app/src/test/java"]),
|
||||
task("integrationTest", &["app/src/integrationTest/java", "app/src/integrationTest/kotlin"]),
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -113,12 +113,15 @@ impl JavaBuildService {
|
||||
|
||||
let had_state = previous.is_some();
|
||||
let previous = previous.unwrap_or_default();
|
||||
let force_canonical: HashSet<PathBuf> = set.force.iter().filter_map(|p| dunce::canonicalize(p).ok()).collect();
|
||||
let mut changed: BTreeSet<PathBuf> = source_stamps
|
||||
.iter()
|
||||
.filter(|(path, stamp)| {
|
||||
previous.sources.get(*path) != Some(*stamp)
|
||||
|| previous.dirty.contains(*path)
|
||||
|| set.force.contains(*path)
|
||||
|| (!force_canonical.is_empty()
|
||||
&& dunce::canonicalize(path).ok().is_some_and(|c| force_canonical.contains(&c)))
|
||||
})
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
@@ -507,42 +510,111 @@ fn ant_match(pattern: &str, path: &str) -> bool {
|
||||
segments(&p, &s)
|
||||
}
|
||||
|
||||
/// The `.java` files of a source set, filtered by the compiler's includes and excludes.
|
||||
/// The `.java` files of a source set, filtered by the compiler's includes and excludes. A file
|
||||
/// reached through several links is listed once: javac 8 fails on a class named twice, and newer
|
||||
/// ones record a single source for it, whose removal would leave the other spelling uncompiled.
|
||||
/// Deduplication runs after includes/excludes so an excluded alias cannot hide a valid path, and
|
||||
/// prefers a path that passes through no symlink over a linked one.
|
||||
fn java_sources(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<Vec<PathBuf>> {
|
||||
let config = set.compiler.as_ref();
|
||||
let includes = config.map(|c| c.includes.as_slice()).unwrap_or_default();
|
||||
let excludes = config.map(|c| c.excludes.as_slice()).unwrap_or_default();
|
||||
let mut out = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let mut kept: HashMap<PathBuf, (PathBuf, bool)> = HashMap::new();
|
||||
for root in &set.source_roots {
|
||||
if model::is_processor_output(set, root) || !root.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let mut pending = vec![root.clone()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
walk_files(root, cancel, &mut |path, canonical, via_link| {
|
||||
if path.extension().is_none_or(|e| e != "java") {
|
||||
return;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let Ok(kind) = entry.file_type() else { continue };
|
||||
if kind.is_dir() {
|
||||
pending.push(path);
|
||||
} else if path.extension().is_some_and(|e| e == "java") {
|
||||
let rel = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let included = includes.is_empty() || includes.iter().any(|p| ant_match(p, &rel));
|
||||
if included && !excludes.iter().any(|p| ant_match(p, &rel)) && seen.insert(path.clone()) {
|
||||
out.push(path);
|
||||
let rel = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let included = includes.is_empty() || includes.iter().any(|p| ant_match(p, &rel));
|
||||
if !included || excludes.iter().any(|p| ant_match(p, &rel)) {
|
||||
return;
|
||||
}
|
||||
match kept.entry(canonical) {
|
||||
std::collections::hash_map::Entry::Vacant(slot) => {
|
||||
slot.insert((path, via_link));
|
||||
}
|
||||
std::collections::hash_map::Entry::Occupied(mut slot) => {
|
||||
if slot.get().1 && !via_link {
|
||||
slot.insert((path, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})?;
|
||||
}
|
||||
let mut out: Vec<PathBuf> = kept.into_values().map(|(path, _)| path).collect();
|
||||
out.sort();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Reports the files under `root` with their canonical paths and whether the path passed through
|
||||
/// any symlink, following links to folders: a module can link a shared source folder into its own,
|
||||
/// and Maven's resources plugin copies through such links too. Files keep the spelling under
|
||||
/// `root`, so javac's messages and the debugger name the path the user opened. Only links back to
|
||||
/// an ancestor on the current descent path (cycles) are skipped. Each folder is read in full
|
||||
/// before its subfolders, so a deep tree holds one open directory at a time; real entries come
|
||||
/// before links, by name, so the walk order does not depend on the file system's order.
|
||||
fn walk_files(root: &Path, cancel: &CancellationToken, found: &mut dyn FnMut(PathBuf, PathBuf, bool)) -> IdeResult<()> {
|
||||
type DirEntry = (bool, std::ffi::OsString, PathBuf, bool);
|
||||
struct Frame {
|
||||
canonical: std::rc::Rc<PathBuf>,
|
||||
via_link: bool,
|
||||
entries: std::vec::IntoIter<DirEntry>,
|
||||
}
|
||||
|
||||
fn read_sorted_entries(dir: &Path, cancel: &CancellationToken) -> IdeResult<Option<std::vec::IntoIter<DirEntry>>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let Ok(read) = std::fs::read_dir(dir) else { return Ok(None) };
|
||||
let mut entries: Vec<DirEntry> = read
|
||||
.flatten()
|
||||
.filter_map(|e| {
|
||||
let kind = e.file_type().ok()?;
|
||||
Some((kind.is_symlink(), e.file_name(), e.path(), kind.is_dir()))
|
||||
})
|
||||
.collect();
|
||||
entries.sort();
|
||||
Ok(Some(entries.into_iter()))
|
||||
}
|
||||
|
||||
let Ok(canonical) = dunce::canonicalize(root) else { return Ok(()) };
|
||||
let via_link = std::fs::symlink_metadata(root).is_ok_and(|m| m.file_type().is_symlink());
|
||||
let Some(entries) = read_sorted_entries(root, cancel)? else { return Ok(()) };
|
||||
|
||||
let root_canonical = std::rc::Rc::new(canonical);
|
||||
let mut ancestors: HashSet<std::rc::Rc<PathBuf>> = HashSet::from([std::rc::Rc::clone(&root_canonical)]);
|
||||
let mut stack = vec![Frame { canonical: root_canonical, via_link, entries }];
|
||||
|
||||
while let Some(frame) = stack.last_mut() {
|
||||
let Some((linked, name, path, is_dir)) = frame.entries.next() else {
|
||||
let done = stack.pop().expect("top frame");
|
||||
ancestors.remove(&done.canonical);
|
||||
continue;
|
||||
};
|
||||
let (is_dir, real) = if linked {
|
||||
let (Ok(meta), Ok(target)) = (std::fs::metadata(&path), dunce::canonicalize(&path)) else { continue };
|
||||
(meta.is_dir(), target)
|
||||
} else {
|
||||
(is_dir, frame.canonical.join(&name))
|
||||
};
|
||||
let entry_via_link = frame.via_link || linked;
|
||||
if !is_dir {
|
||||
found(path, real, entry_via_link);
|
||||
} else if !ancestors.contains(&real)
|
||||
&& let Some(children) = read_sorted_entries(&path, cancel)?
|
||||
{
|
||||
let real = std::rc::Rc::new(real);
|
||||
ancestors.insert(std::rc::Rc::clone(&real));
|
||||
stack.push(Frame { canonical: real, via_link: entry_via_link, entries: children });
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A javac debug-info option (`-g`, `-g:none`, `-g:lines,vars`). The IDE's build always
|
||||
/// compiles with `-g`: breakpoints need line numbers and local variables, whatever
|
||||
/// maven-compiler-plugin's `<debug>` / `<debuglevel>` ask of Maven's own build (#7786).
|
||||
@@ -1241,21 +1313,11 @@ fn remove_classes(dir: &Path) {
|
||||
fn resource_stamp(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTreeMap<PathBuf, FileStamp>> {
|
||||
let mut out = BTreeMap::new();
|
||||
for root in &set.resources {
|
||||
let mut pending = vec![root.directory.clone()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
walk_files(&root.directory, cancel, &mut |path, _, _| {
|
||||
if let Some(stamp) = file_stamp(&path) {
|
||||
out.insert(path, stamp);
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
pending.push(path);
|
||||
} else if let Some(stamp) = file_stamp(&path) {
|
||||
out.insert(path, stamp);
|
||||
}
|
||||
}
|
||||
}
|
||||
})?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -1265,27 +1327,15 @@ fn resource_stamp(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTre
|
||||
fn resource_outputs(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTreeSet<PathBuf>> {
|
||||
let mut out = BTreeSet::new();
|
||||
for root in &set.resources {
|
||||
let mut pending = vec![root.directory.clone()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
walk_files(&root.directory, cancel, &mut |path, _, _| {
|
||||
let rel = path.strip_prefix(&root.directory).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let included = root.includes.is_empty() || root.includes.iter().any(|p| ant_match(p, &rel));
|
||||
if !included || root.excludes.iter().any(|p| ant_match(p, &rel)) {
|
||||
return;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
pending.push(path);
|
||||
continue;
|
||||
}
|
||||
let rel = path.strip_prefix(&root.directory).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let included = root.includes.is_empty() || root.includes.iter().any(|p| ant_match(p, &rel));
|
||||
if !included || root.excludes.iter().any(|p| ant_match(p, &rel)) {
|
||||
continue;
|
||||
}
|
||||
let target = root.target_path.as_deref().unwrap_or("").replace('\\', "/");
|
||||
out.insert(set.output.join(target.trim_matches('/')).join(&rel));
|
||||
}
|
||||
}
|
||||
let target = root.target_path.as_deref().unwrap_or("").replace('\\', "/");
|
||||
out.insert(set.output.join(target.trim_matches('/')).join(&rel));
|
||||
})?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -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(&[
|
||||
@@ -819,3 +835,314 @@ fn leaves_gradle_projects_with_other_compilers_to_gradle() {
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `.java` files `java_sources` lists for one source root.
|
||||
#[cfg(unix)]
|
||||
fn sources_of(root: &Path) -> Vec<PathBuf> {
|
||||
let set = SourceSet { source_roots: vec![root.to_path_buf()], ..Default::default() };
|
||||
java_sources(&set, &CancellationToken::new()).unwrap()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_follow_directory_links_and_keep_the_linked_spelling() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("app/src/main/java");
|
||||
write(&root, "a/A.java", "package a;\nclass A {}\n");
|
||||
write(&base, "shared/b/B.java", "package b;\npublic class B {}\n");
|
||||
write(&base, "shared/b/c/C.java", "package b.c;\npublic class C {}\n");
|
||||
symlink(base.join("shared/b"), root.join("b")).unwrap();
|
||||
// A link to a file was already listed; it stays listed.
|
||||
write(&base, "shared/D.java", "package d;\npublic class D {}\n");
|
||||
fs::create_dir_all(root.join("d")).unwrap();
|
||||
symlink(base.join("shared/D.java"), root.join("d/D.java")).unwrap();
|
||||
// A broken link is skipped.
|
||||
symlink(base.join("missing"), root.join("gone")).unwrap();
|
||||
// javac and the debugger get the path the user opened, not the link's target.
|
||||
assert_eq!(
|
||||
sources_of(&root),
|
||||
[root.join("a/A.java"), root.join("b/B.java"), root.join("b/c/C.java"), root.join("d/D.java")]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_stop_at_link_cycles() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("src");
|
||||
write(&root, "a/A.java", "package a;\nclass A {}\n");
|
||||
write(&base, "shared/b/B.java", "package b;\npublic class B {}\n");
|
||||
symlink(&root, root.join("a/up")).unwrap();
|
||||
symlink(".", root.join("a/here")).unwrap();
|
||||
symlink(base.join("shared/b"), root.join("b")).unwrap();
|
||||
symlink(base.join("shared"), base.join("shared/b/back")).unwrap();
|
||||
assert_eq!(sources_of(&root), [root.join("a/A.java"), root.join("b/B.java")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_follow_links_that_share_a_folder() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
write(&base, "shared/s/S.java", "package s;\npublic class S {}\n");
|
||||
let shared = base.join("shared/s");
|
||||
// Each module links the same folder into its own sources: every one of them compiles it.
|
||||
let (one, two) = (base.join("one/src"), base.join("two/src"));
|
||||
for root in [&one, &two] {
|
||||
fs::create_dir_all(root).unwrap();
|
||||
symlink(&shared, root.join("s")).unwrap();
|
||||
}
|
||||
assert_eq!(sources_of(&one), [one.join("s/S.java")]);
|
||||
assert_eq!(sources_of(&two), [two.join("s/S.java")]);
|
||||
// Within one source set a file reached through two links is listed once, real entries before links, then by name.
|
||||
let three = base.join("three/src");
|
||||
fs::create_dir_all(three.join("x")).unwrap();
|
||||
symlink(&shared, three.join("s")).unwrap();
|
||||
symlink(&shared, three.join("x/s")).unwrap();
|
||||
assert_eq!(sources_of(&three), [three.join("x/s/S.java")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_list_a_file_reached_through_two_paths_once() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("src");
|
||||
write(&root, "p/C.java", "package p;\npublic class C {}\n");
|
||||
symlink(root.join("p"), root.join("alias")).unwrap();
|
||||
symlink(root.join("p/C.java"), root.join("C.java")).unwrap();
|
||||
// The real folder comes before the links to it.
|
||||
assert_eq!(sources_of(&root), [root.join("p/C.java")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_sources_match_each_nested_root_against_its_own_paths() {
|
||||
// Without links the listing is what it was before links were followed: a file the outer
|
||||
// root's relative path excludes is still listed through the inner root.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let outer = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let inner = outer.join("inner");
|
||||
write(&outer, "inner/X.java", "class X {}\n");
|
||||
write(&outer, "Y.java", "class Y {}\n");
|
||||
let set = SourceSet {
|
||||
source_roots: vec![outer.clone(), inner.clone()],
|
||||
compiler: Some(CompilerConfig { excludes: vec!["inner/**".into()], ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(java_sources(&set, &CancellationToken::new()).unwrap(), [outer.join("Y.java"), inner.join("X.java")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_sources_find_a_file_deep_in_plain_folders() {
|
||||
// Iterative walk with one folder open at a time: avoids exhausting file descriptors under
|
||||
// macOS's default limit of 256 and avoids overflowing Windows' 1-2 MB thread stack in deep
|
||||
// trees. Target 3000 levels on Windows (long paths up to 32,767 chars); on Unix, cap to the
|
||||
// deepest path that fits under PATH_MAX (1024 bytes on macOS, 4096 bytes on Linux).
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let max_path_bytes: Option<usize> = if cfg!(target_os = "macos") {
|
||||
Some(1020)
|
||||
} else if cfg!(unix) {
|
||||
Some(4090)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let target_depth = 3000;
|
||||
let depth = match max_path_bytes {
|
||||
Some(limit) => target_depth.min(limit.saturating_sub(root.as_os_str().len() + "/C.java".len()) / 2),
|
||||
None => target_depth,
|
||||
};
|
||||
assert!(depth >= 300, "temp root too long for deep folder test: {}", root.display());
|
||||
|
||||
let mut dir = root.clone();
|
||||
for _ in 0..depth {
|
||||
dir.push("d");
|
||||
fs::create_dir(&dir).unwrap();
|
||||
}
|
||||
let file = dir.join("C.java");
|
||||
fs::write(&file, "class C {}\n").unwrap();
|
||||
|
||||
let set = SourceSet { source_roots: vec![root], ..Default::default() };
|
||||
let found = java_sources(&set, &CancellationToken::new()).unwrap();
|
||||
|
||||
// Remove iteratively so deep trees don't rely on recursive directory removal.
|
||||
fs::remove_file(&file).unwrap();
|
||||
for _ in 0..depth {
|
||||
fs::remove_dir(&dir).unwrap();
|
||||
dir.pop();
|
||||
}
|
||||
assert_eq!(found, [file]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn compiles_the_other_spelling_when_the_kept_link_goes() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/src/main/java/a/A.java", "package a;\nclass A { p.C c; }\n"),
|
||||
("shared/p/C.java", "package p;\npublic class C {}\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let java = f.root.join("app/src/main/java");
|
||||
symlink(f.root.join("shared/p"), java.join("p")).unwrap();
|
||||
symlink(f.root.join("shared/p"), java.join("z")).unwrap();
|
||||
f.steps_of_launch();
|
||||
let class = f.out("t.app/classes/p/C.class");
|
||||
assert!(class.is_file());
|
||||
|
||||
// The class keeps its source through the link that is left.
|
||||
fs::remove_file(java.join("p")).unwrap();
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(class.is_file(), "C.class is gone after {steps:?}");
|
||||
assert!(f.steps_of_launch().is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn builds_and_recompiles_sources_under_a_linked_folder() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return new b.B().b(); } }\n"),
|
||||
("shared/b/B.java", "package b;\npublic class B { public int b() { return 1; } }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
std::os::unix::fs::symlink(f.root.join("shared/b"), f.root.join("app/src/main/java/b")).unwrap();
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(steps.contains(&"javac app (main, 2 files)".to_owned()), "{steps:?}");
|
||||
assert!(f.steps_of_launch().is_empty());
|
||||
|
||||
// An edit behind the link is seen through it.
|
||||
f.write("shared/b/B.java", "package b;\npublic class B { public int b() { return 2; } }\n");
|
||||
assert_eq!(f.steps_of_launch(), ["javac app (main, 1 of 2 files)"]);
|
||||
|
||||
// Errors name the file as it sits under the source root.
|
||||
f.write("shared/b/B.java", "package b;\npublic class B { public int b() { return \"\"; } }\n");
|
||||
let failed = f.launch(false);
|
||||
let error = failed.messages.iter().find(|m| m.severity == Severity::Error).expect("an error");
|
||||
assert_eq!(
|
||||
error.path.as_deref(),
|
||||
Some(f.root.join("app/src/main/java/b/B.java").as_path()),
|
||||
"{:?}",
|
||||
failed.messages
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn resources_under_a_linked_folder_are_copied_refreshed_and_pruned() {
|
||||
let Some(f) =
|
||||
Fixture::new(&[("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"), ("shared/r/x.txt", "one\n")])
|
||||
else {
|
||||
return;
|
||||
};
|
||||
fs::create_dir_all(f.root.join("app/src/main/resources")).unwrap();
|
||||
std::os::unix::fs::symlink(f.root.join("shared/r"), f.root.join("app/src/main/resources/r")).unwrap();
|
||||
assert_eq!(f.launch(false).failure, None);
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/r/x.txt")).unwrap(), "one\n");
|
||||
|
||||
// An edit behind the link reaches the copy the launch reads.
|
||||
f.write("shared/r/x.txt", "two\n");
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(steps.iter().any(|s| s.contains("resources:resources")), "{steps:?}");
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/r/x.txt")).unwrap(), "two\n");
|
||||
|
||||
// So does a file deleted behind it.
|
||||
fs::remove_file(f.root.join("shared/r/x.txt")).unwrap();
|
||||
f.steps_of_launch();
|
||||
assert!(!f.out("t.app/classes/r/x.txt").exists(), "the removed resource stays on the classpath");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_keep_a_valid_link_when_an_earlier_alias_is_excluded() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("src/main/java");
|
||||
write(&base, "shared/one/p/C.java", "package p;\npublic class C {}\n");
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
symlink(base.join("shared/one"), root.join("a")).unwrap();
|
||||
symlink(base.join("shared/one"), root.join("z")).unwrap();
|
||||
let set = SourceSet {
|
||||
source_roots: vec![root.clone()],
|
||||
compiler: Some(CompilerConfig { excludes: vec!["a/**".into()], ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(java_sources(&set, &CancellationToken::new()).unwrap(), [root.join("z/p/C.java")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn excluded_link_alias_does_not_drop_compiled_classes() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let pom = APP_POM.replace(
|
||||
"</build>",
|
||||
concat!(
|
||||
"<plugins><plugin><artifactId>maven-compiler-plugin</artifactId>",
|
||||
"<configuration><excludes><exclude>a/**</exclude></excludes></configuration>",
|
||||
"</plugin></plugins></build>",
|
||||
),
|
||||
);
|
||||
let Some(f) = Fixture::new(&[("app/pom.xml", &pom), ("shared/one/p/C.java", "package p;\npublic class C {}\n")])
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let java = f.root.join("app/src/main/java");
|
||||
fs::create_dir_all(&java).unwrap();
|
||||
symlink(f.root.join("shared/one"), java.join("z")).unwrap();
|
||||
f.steps_of_launch();
|
||||
let class = f.out("t.app/classes/p/C.class");
|
||||
assert!(class.is_file());
|
||||
|
||||
// Adding an excluded link to the same folder must not hide the surviving link or delete its class.
|
||||
symlink(f.root.join("shared/one"), java.join("a")).unwrap();
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(class.is_file(), "C.class is gone after {steps:?}");
|
||||
assert!(steps.is_empty(), "{steps:?}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_prefer_a_plain_path_over_an_earlier_linked_alias() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("src/main/java");
|
||||
write(&root, "p/C.java", "package p;\npublic class C {}\n");
|
||||
fs::create_dir_all(root.join("a")).unwrap();
|
||||
symlink(root.join("p"), root.join("a/link")).unwrap();
|
||||
assert_eq!(sources_of(&root), [root.join("p/C.java")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn recompiles_a_single_file_through_either_the_plain_or_linked_spelling() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let Some(f) = Fixture::new(&[("app/src/main/java/p/C.java", "package p;\npublic class C {}\n")]) else {
|
||||
return;
|
||||
};
|
||||
f.steps_of_launch();
|
||||
let java = f.root.join("app/src/main/java");
|
||||
assert!(f.out("t.app/classes/p/C.class").is_file());
|
||||
|
||||
// Adding a link under an earlier directory keeps the plain spelling and still lets Recompile
|
||||
// hit through either spelling.
|
||||
fs::create_dir_all(java.join("a")).unwrap();
|
||||
symlink(java.join("p"), java.join("a/link")).unwrap();
|
||||
let second = f.steps_of_launch();
|
||||
|
||||
f.steps();
|
||||
assert_eq!(f.build(Target::File(&java.join("p/C.java"))).failure, None);
|
||||
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
|
||||
|
||||
f.steps();
|
||||
assert_eq!(f.build(Target::File(&java.join("a/link/C.java"))).failure, None);
|
||||
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
|
||||
|
||||
assert!(second.is_empty(), "{second:?}");
|
||||
}
|
||||
@@ -98,9 +98,10 @@ pub fn load_linked_with_jdk(
|
||||
maven_jdk_version: Option<u32>,
|
||||
) -> BuildModel {
|
||||
let maven = maven::has_projects(root, settings).then(|| {
|
||||
let profiles = settings.profiles(&sync::maven_profiles(cache_dir));
|
||||
let activation =
|
||||
maven::ProfileActivation::new(root, settings, &sync::maven_profiles(cache_dir), maven_jdk_version);
|
||||
let repo = maven_repo.or_else(maven::default_local_repo);
|
||||
let mut m = maven::load_with_linked_jdk(root, repo, &profiles, maven_jdk_version, &settings.linked_projects);
|
||||
let mut m = maven::load_with_activation(root, repo, &activation, &settings.linked_projects);
|
||||
maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m);
|
||||
// The user settings' profiles can be chosen too (`-P` applies to them as well).
|
||||
if let Some(settings_file) = maven::user_settings_file(root, settings) {
|
||||
@@ -111,12 +112,6 @@ pub fn load_linked_with_jdk(
|
||||
m.profiles.push(p);
|
||||
}
|
||||
}
|
||||
let active_in_settings = maven::settings_active_profiles(&settings_file);
|
||||
for existing in &mut m.profiles {
|
||||
if active_in_settings.iter().any(|id| id == &existing.id) {
|
||||
existing.active_by_default = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
sync::apply_maven_cache(root, cache_dir, &mut m);
|
||||
m
|
||||
@@ -167,8 +162,8 @@ pub fn maven_external_roots(
|
||||
) -> Vec<PathBuf> {
|
||||
let mut dirs = maven::external_pom_dirs(root, &settings.linked_projects);
|
||||
if trusted {
|
||||
let profiles = settings.profiles(&sync::maven_profiles(cache_dir));
|
||||
dirs.extend(maven::reactor_external_dirs(root, &profiles, &settings.unlinked_projects));
|
||||
let activation = maven::ProfileActivation::new(root, settings, &sync::maven_profiles(cache_dir), None);
|
||||
dirs.extend(maven::reactor_external_dirs(root, &activation, &settings.unlinked_projects));
|
||||
}
|
||||
let owned: Vec<String> = dirs.iter().map(|dir| dir.to_string_lossy().into_owned()).collect();
|
||||
gradle::external_roots(root, owned.iter().map(String::as_str))
|
||||
@@ -344,6 +339,47 @@ mod tests {
|
||||
assert_eq!(roots(&settings, true), [a, e]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_maven_turns_on_by_itself_is_shown_on_and_unticking_it_turns_it_off() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for module in ["extras", "it"] {
|
||||
std::fs::create_dir(root.join(module)).unwrap();
|
||||
std::fs::write(root.join(module).join("pom.xml"), "<project><artifactId>m</artifactId></project>").unwrap();
|
||||
}
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
r#"<project><artifactId>root</artifactId><packaging>pom</packaging><profiles>
|
||||
<profile><id>dev</id><activation><activeByDefault>true</activeByDefault></activation></profile>
|
||||
<profile><id>full</id><activation><property><name>!quick</name></property></activation><modules><module>extras</module></modules></profile>
|
||||
<profile><id>ci</id><modules><module>it</module></modules></profile>
|
||||
</profiles></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::create_dir(root.join(".mvn")).unwrap();
|
||||
std::fs::write(root.join(".mvn/maven.config"), "-Pci\n").unwrap();
|
||||
let cache = root.join("cache");
|
||||
let settings = ide_core::settings::MavenSettings {
|
||||
user_settings: root.join("settings.xml").to_string_lossy().into_owned(),
|
||||
..Default::default()
|
||||
};
|
||||
let load = || load_linked(root, &cache, None, &settings, &Default::default()).maven.unwrap();
|
||||
let flags =
|
||||
|m: &maven::MavenModel| m.profiles.iter().map(|p| (p.id.clone(), p.active_by_default)).collect::<Vec<_>>();
|
||||
let pair = |id: &str, on: bool| (id.to_owned(), on);
|
||||
|
||||
// On by default (the tool window's grey check), so `dev` steps aside as it does in Maven.
|
||||
let model = load();
|
||||
assert_eq!(flags(&model), [pair("dev", false), pair("full", true), pair("ci", true)]);
|
||||
assert_eq!(model.projects[0].modules, ["extras/pom.xml", "it/pom.xml"]);
|
||||
|
||||
// Unticked: off in the model, still on by default so the tool window keeps passing `-P !id`.
|
||||
save_maven_profiles(&cache, &["!full".into(), "!ci".into()]).unwrap();
|
||||
let model = load();
|
||||
assert_eq!(flags(&model), [pair("dev", true), pair("full", true), pair("ci", true)]);
|
||||
assert!(model.projects[0].modules.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_profiles_and_checkbox_choices_control_modules_before_sync() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -387,7 +423,7 @@ mod tests {
|
||||
root.join("child/pom.xml"),
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>root</artifactId><version>1.0</version></parent>
|
||||
<artifactId>child</artifactId>
|
||||
<profiles><profile><id>child-default</id><activation><activeByDefault>true</activeByDefault></activation></profile></profiles></project>"#,
|
||||
<profiles><profile><id>child-default</id><activation><activeByDefault>TRUE</activeByDefault></activation></profile></profiles></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let settings_xml = root.join("settings.xml");
|
||||
@@ -407,8 +443,9 @@ mod tests {
|
||||
flags.contains(&("test3", true)),
|
||||
"activeProfile from settings.xml marks POM profile active: {flags:?}"
|
||||
);
|
||||
assert!(flags.contains(&("dev", true)), "case-insensitive activeByDefault: {flags:?}");
|
||||
assert!(flags.contains(&("child-default", true)), "child module activeByDefault: {flags:?}");
|
||||
// As in Maven, `dev` steps aside: settings.xml turns on test3 of the same POM.
|
||||
assert!(flags.contains(&("dev", false)), "activeByDefault beside an active profile: {flags:?}");
|
||||
assert!(flags.contains(&("child-default", true)), "case-insensitive activeByDefault of a module: {flags:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,463 @@
|
||||
//! Which profiles of a POM Maven turns on for a project, decided as Maven 3.9 does
|
||||
//! (`DefaultProfileSelector` and its activators): from the `-P` entries, the `-D` properties of
|
||||
//! `.mvn/maven.config`, the JDK Maven runs on, the OS and the files of the project.
|
||||
|
||||
use super::{RawProfile, interpolate, jdk_matches};
|
||||
use crate::xml::Element;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// What decides profile activation besides the POMs and the machine. The `.mvn/maven.config`
|
||||
/// of each build is read with its POMs.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct ProfileActivation {
|
||||
/// `-P` entries of every Maven run (`!id` or `-id` turns a profile off): Settings › Maven's
|
||||
/// active profiles and the `<activeProfiles>` of the user `settings.xml`.
|
||||
pub profiles: Vec<String>,
|
||||
/// `-P` entries chosen in the Maven tool window.
|
||||
pub choices: Vec<String>,
|
||||
/// Feature version of the JDK Maven runs on.
|
||||
pub jdk: Option<u32>,
|
||||
}
|
||||
|
||||
impl ProfileActivation {
|
||||
/// For the builds under `root`, with the Maven tool window's `choices`.
|
||||
pub fn new(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::MavenSettings,
|
||||
choices: &[String],
|
||||
jdk: Option<u32>,
|
||||
) -> Self {
|
||||
let mut profiles = settings.profiles(&[]);
|
||||
if let Some(file) = super::user_settings_file(root, settings) {
|
||||
profiles.extend(super::settings_active_profiles(&file));
|
||||
}
|
||||
Self { profiles, choices: choices.to_vec(), jdk }
|
||||
}
|
||||
|
||||
/// `Some(false)` when a `-P` entry turns profile `id` off (that wins in Maven, whatever the
|
||||
/// order), `Some(true)` when one turns it on. The tool window's entries for `except` are
|
||||
/// left out.
|
||||
fn explicit(&self, config: &MavenConfig, id: &str, except: Option<&str>) -> Option<bool> {
|
||||
let choices = self.choices.iter().filter(|c| except.is_none_or(|except| entry(c).1 != except));
|
||||
let mut on = None;
|
||||
for (turns_on, entry) in self.profiles.iter().chain(&config.profiles).chain(choices).map(|e| entry(e)) {
|
||||
if entry == id {
|
||||
if !turns_on {
|
||||
return Some(false);
|
||||
}
|
||||
on = Some(true);
|
||||
}
|
||||
}
|
||||
on
|
||||
}
|
||||
}
|
||||
|
||||
/// A `-P` entry as (turns the profile on, its id): `!id` and `-id` turn it off, `+id` and
|
||||
/// Maven 3.9's optional `?id` turn it on.
|
||||
fn entry(entry: &str) -> (bool, &str) {
|
||||
let entry = entry.trim();
|
||||
let (on, id) = match entry.strip_prefix(['!', '-']) {
|
||||
Some(id) => (false, id),
|
||||
None => (true, entry.strip_prefix('+').unwrap_or(entry)),
|
||||
};
|
||||
(on, id.strip_prefix('?').unwrap_or(id).trim())
|
||||
}
|
||||
|
||||
/// The `-P` and `-D` options of the `.mvn/maven.config` Maven reads before every run.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct MavenConfig {
|
||||
profiles: Vec<String>,
|
||||
properties: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl MavenConfig {
|
||||
/// The `maven.config` of a Maven run in `dir`: in the `.mvn` folder of the nearest folder
|
||||
/// from `dir` up that has one, as the `mvn` script finds the build's base directory; else
|
||||
/// where it would be created in `dir`.
|
||||
pub(crate) fn file(dir: &Path) -> PathBuf {
|
||||
let base = dir.ancestors().find(|d| !d.as_os_str().is_empty() && d.join(".mvn").is_dir());
|
||||
base.unwrap_or(dir).join(".mvn").join("maven.config")
|
||||
}
|
||||
|
||||
pub(crate) fn read(file: &Path) -> Self {
|
||||
std::fs::read_to_string(file).map(|text| Self::parse(&text)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Since Maven 3.9 each line is one argument (`-P a` and `-P` followed by `a` both work);
|
||||
/// lines starting with `#` are comments.
|
||||
fn parse(text: &str) -> Self {
|
||||
let mut config = Self::default();
|
||||
let mut args = text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#'));
|
||||
while let Some(arg) = args.next() {
|
||||
if let Some(value) = option_value(arg, "-P", "--activate-profiles", &mut args) {
|
||||
config.profiles.extend(value.split(',').map(str::trim).filter(|p| !p.is_empty()).map(str::to_owned));
|
||||
} else if let Some(value) = option_value(arg, "-D", "--define", &mut args) {
|
||||
// `-Dname` alone sets it to `true`, as on the command line.
|
||||
let (name, value) = value.split_once('=').unwrap_or((value, "true"));
|
||||
config.properties.insert(name.trim().to_owned(), value.to_owned());
|
||||
}
|
||||
}
|
||||
config
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of the option `short` / `long` given in `arg` (`-Pa`, `-P a`, `--activate-profiles=a`)
|
||||
/// or as the next argument.
|
||||
fn option_value<'a>(
|
||||
arg: &'a str,
|
||||
short: &str,
|
||||
long: &str,
|
||||
args: &mut impl Iterator<Item = &'a str>,
|
||||
) -> Option<&'a str> {
|
||||
let value = match arg.strip_prefix(long) {
|
||||
Some(rest) if rest.is_empty() || rest.starts_with(['=', ' ', '\t']) => rest.trim_start_matches('='),
|
||||
Some(_) => return None,
|
||||
None => arg.strip_prefix(short)?,
|
||||
};
|
||||
match value.trim() {
|
||||
"" => args.next(),
|
||||
value => Some(value),
|
||||
}
|
||||
}
|
||||
|
||||
/// A profile's `<activation>`.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct Activation {
|
||||
pub(crate) by_default: bool,
|
||||
/// `<jdk>`: `21`, `1.8`, `[17,)`, `!21`.
|
||||
pub(crate) jdk: Option<String>,
|
||||
os: Option<OsCondition>,
|
||||
property: Option<PropertyCondition>,
|
||||
file: Option<FileCondition>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct OsCondition {
|
||||
family: Option<String>,
|
||||
name: Option<String>,
|
||||
arch: Option<String>,
|
||||
version: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct PropertyCondition {
|
||||
name: String,
|
||||
value: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct FileCondition {
|
||||
exists: Option<String>,
|
||||
missing: Option<String>,
|
||||
}
|
||||
|
||||
impl Activation {
|
||||
pub(crate) fn read(profile: &Element) -> Self {
|
||||
let Some(a) = profile.child("activation") else { return Self::default() };
|
||||
Self {
|
||||
by_default: a.text_of("activeByDefault").is_some_and(|v| v.eq_ignore_ascii_case("true")),
|
||||
// Present but empty, Maven's prefix match takes any JDK.
|
||||
jdk: a.child("jdk").map(|jdk| jdk.text.trim().to_owned()),
|
||||
os: a.child("os").map(|os| OsCondition {
|
||||
family: os.text_of("family"),
|
||||
name: os.text_of("name"),
|
||||
arch: os.text_of("arch"),
|
||||
version: os.text_of("version"),
|
||||
}),
|
||||
property: a
|
||||
.child("property")
|
||||
.map(|p| PropertyCondition { name: p.text_of("name").unwrap_or_default(), value: p.text_of("value") }),
|
||||
file: a.child("file").map(|f| FileCondition { exists: f.text_of("exists"), missing: f.text_of("missing") }),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn checks_files(&self) -> bool {
|
||||
self.file.is_some()
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
self.jdk.is_none() && self.os.is_none() && self.property.is_none() && self.file.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// What the profiles of one project are activated with.
|
||||
pub(crate) struct Env<'a> {
|
||||
pub(crate) activation: &'a ProfileActivation,
|
||||
pub(crate) config: &'a MavenConfig,
|
||||
/// The folder of the project being built, also for the profiles its parents declare.
|
||||
pub(crate) basedir: &'a Path,
|
||||
}
|
||||
|
||||
impl Env<'_> {
|
||||
/// Whether the `<activation>` conditions of each profile hold; the files they look at are
|
||||
/// added to `files`. `properties` are the own `<properties>` of the POM declaring them.
|
||||
pub(crate) fn conditions(
|
||||
&self,
|
||||
profiles: &[RawProfile],
|
||||
properties: &[(String, String)],
|
||||
files: &mut Vec<PathBuf>,
|
||||
) -> Vec<bool> {
|
||||
if profiles.iter().all(|p| p.activation.is_empty()) {
|
||||
return vec![false; profiles.len()];
|
||||
}
|
||||
let props = self.interpolation(properties);
|
||||
profiles.iter().map(|p| self.holds(&p.activation, &props, files)).collect()
|
||||
}
|
||||
|
||||
/// Which profiles are on: those a `-P` entry turns on or whose `conditions` hold, unless one
|
||||
/// turns them off; the `activeByDefault` ones only when no other profile of the POM is on.
|
||||
/// The tool window's choice for profile `except` is left out.
|
||||
pub(crate) fn select(&self, profiles: &[RawProfile], conditions: &[bool], except: Option<&str>) -> Vec<bool> {
|
||||
let explicit: Vec<Option<bool>> =
|
||||
profiles.iter().map(|p| self.activation.explicit(self.config, &p.id, except)).collect();
|
||||
let mut on: Vec<bool> = explicit.iter().zip(conditions).map(|(e, &holds)| e.unwrap_or(holds)).collect();
|
||||
if !on.contains(&true) {
|
||||
for ((on, p), e) in on.iter_mut().zip(profiles).zip(&explicit) {
|
||||
*on = p.activation.by_default && *e != Some(false);
|
||||
}
|
||||
}
|
||||
on
|
||||
}
|
||||
|
||||
/// Whether each profile is on unless the Maven tool window turns it off: what the tool
|
||||
/// window shows as on by default, so that unticking it passes `-P!id`.
|
||||
pub(crate) fn implicit(&self, profiles: &[RawProfile], conditions: &[bool]) -> Vec<bool> {
|
||||
profiles.iter().enumerate().map(|(i, p)| self.select(profiles, conditions, Some(&p.id))[i]).collect()
|
||||
}
|
||||
|
||||
/// Values for `${…}` in activation conditions: the declaring POM's own properties, then the
|
||||
/// `-D` ones, then the JVM's; `${basedir}` is the project's.
|
||||
fn interpolation(&self, properties: &[(String, String)]) -> HashMap<String, String> {
|
||||
let mut props: HashMap<String, String> = ["os.name", "os.arch", "user.home"]
|
||||
.into_iter()
|
||||
.filter_map(|k| Some((k.to_owned(), system_property(k)?)))
|
||||
.collect();
|
||||
props.extend(self.config.properties.iter().map(|(k, v)| (k.clone(), v.clone())));
|
||||
props.extend(properties.iter().cloned());
|
||||
let basedir = self.basedir.to_string_lossy().into_owned();
|
||||
props.insert("project.basedir".into(), basedir.clone());
|
||||
props.insert("basedir".into(), basedir);
|
||||
props
|
||||
}
|
||||
|
||||
/// Since Maven 3.2.2 every condition present has to hold, and one at least has to be present.
|
||||
fn holds(&self, a: &Activation, props: &HashMap<String, String>, files: &mut Vec<PathBuf>) -> bool {
|
||||
let jdk = self.activation.jdk;
|
||||
let results = [
|
||||
a.jdk.as_ref().map(|spec| jdk.is_some() && (spec.is_empty() || jdk_matches(spec, jdk))),
|
||||
a.os.as_ref().map(|os| os_matches(os, props)),
|
||||
a.property.as_ref().map(|p| self.property_matches(p, props)),
|
||||
a.file.as_ref().map(|f| self.file_matches(f, props, files)),
|
||||
];
|
||||
let mut present = results.into_iter().flatten().peekable();
|
||||
present.peek().is_some() && present.all(|holds| holds)
|
||||
}
|
||||
|
||||
fn property_matches(&self, p: &PropertyCondition, props: &HashMap<String, String>) -> bool {
|
||||
let name = interpolate(&p.name, props);
|
||||
let (negated, name) = negation(&name);
|
||||
if name.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let actual = self.config.properties.get(name).cloned().or_else(|| system_property(name));
|
||||
match p.value.as_deref().map(|v| interpolate(v, props)) {
|
||||
Some(value) => {
|
||||
let (negated, value) = negation(&value);
|
||||
negated != (actual.as_deref() == Some(value))
|
||||
}
|
||||
None => negated != actual.is_some_and(|v| !v.is_empty()),
|
||||
}
|
||||
}
|
||||
|
||||
fn file_matches(&self, f: &FileCondition, props: &HashMap<String, String>, files: &mut Vec<PathBuf>) -> bool {
|
||||
let (path, missing) = match (&f.exists, &f.missing) {
|
||||
(Some(path), _) => (path, false),
|
||||
(None, Some(path)) => (path, true),
|
||||
(None, None) => return false,
|
||||
};
|
||||
let path = crate::gradle::normalize(&self.basedir.join(interpolate(path, props)));
|
||||
let exists = path.exists();
|
||||
files.push(path);
|
||||
exists != missing
|
||||
}
|
||||
}
|
||||
|
||||
fn negation(value: &str) -> (bool, &str) {
|
||||
match value.strip_prefix('!') {
|
||||
Some(rest) => (true, rest),
|
||||
None => (false, value),
|
||||
}
|
||||
}
|
||||
|
||||
/// `<os>` as Maven 3.9 matches it (`org.apache.maven.utils.Os`) against what Java reports for
|
||||
/// this machine.
|
||||
fn os_matches(os: &OsCondition, props: &HashMap<String, String>) -> bool {
|
||||
let name = os_name().to_lowercase();
|
||||
let test = |value: &Option<String>, matches: &dyn Fn(&str) -> bool| {
|
||||
value.as_deref().is_none_or(|v| {
|
||||
let v = interpolate(v, props).to_lowercase();
|
||||
let (negated, v) = negation(&v);
|
||||
negated != matches(v)
|
||||
})
|
||||
};
|
||||
(os.family.is_some() || os.name.is_some() || os.arch.is_some())
|
||||
// The OS version Java reports is not known here.
|
||||
&& os.version.is_none()
|
||||
&& test(&os.family, &|family| family_matches(family, &name))
|
||||
&& test(&os.name, &|n| n == name)
|
||||
&& test(&os.arch, &|arch| arch == os_arch())
|
||||
}
|
||||
|
||||
fn family_matches(family: &str, os_name: &str) -> bool {
|
||||
let windows = os_name.contains("windows");
|
||||
let win9x = windows && ["95", "98", "me", "ce"].iter().any(|v| os_name.contains(v));
|
||||
let mac = os_name.contains("mac") || os_name.contains("darwin");
|
||||
match family {
|
||||
"windows" => windows,
|
||||
"win9x" => win9x,
|
||||
"winnt" => windows && !win9x,
|
||||
"dos" => cfg!(windows) && !os_name.contains("netware"),
|
||||
"mac" => mac,
|
||||
"unix" => !cfg!(windows) && !os_name.contains("openvms") && (!mac || os_name.ends_with('x')),
|
||||
"tandem" => os_name.contains("nonstop_kernel"),
|
||||
"z/os" => os_name.contains("z/os") || os_name.contains("os/390"),
|
||||
family => os_name.contains(family),
|
||||
}
|
||||
}
|
||||
|
||||
/// `os.name` as Java reports it; on Windows it also names the version, which is not known here.
|
||||
fn os_name() -> &'static str {
|
||||
match std::env::consts::OS {
|
||||
"macos" => "Mac OS X",
|
||||
"windows" => "Windows",
|
||||
"linux" => "Linux",
|
||||
"freebsd" => "FreeBSD",
|
||||
"openbsd" => "OpenBSD",
|
||||
"netbsd" => "NetBSD",
|
||||
"solaris" | "illumos" => "SunOS",
|
||||
"aix" => "AIX",
|
||||
os => os,
|
||||
}
|
||||
}
|
||||
|
||||
/// `os.arch` as Java reports it.
|
||||
fn os_arch() -> &'static str {
|
||||
match std::env::consts::ARCH {
|
||||
"x86_64" if cfg!(target_os = "macos") => "x86_64",
|
||||
"x86_64" => "amd64",
|
||||
"x86" if cfg!(windows) => "x86",
|
||||
"x86" => "i386",
|
||||
"powerpc64" if cfg!(target_endian = "little") => "ppc64le",
|
||||
"powerpc64" => "ppc64",
|
||||
arch => arch,
|
||||
}
|
||||
}
|
||||
|
||||
/// The system properties of Maven's JVM that conditions use: the environment as `env.*`, and
|
||||
/// those of the JVM's own that are known here.
|
||||
fn system_property(name: &str) -> Option<String> {
|
||||
if let Some(var) = name.strip_prefix("env.") {
|
||||
return std::env::var(var).ok();
|
||||
}
|
||||
match name {
|
||||
"os.name" => Some(os_name().to_owned()),
|
||||
"os.arch" => Some(os_arch().to_owned()),
|
||||
"user.home" => dirs::home_dir().map(|home| home.to_string_lossy().into_owned()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn profiles(xml: &str) -> Vec<RawProfile> {
|
||||
super::super::parse_pom(&format!("<project><profiles>{xml}</profiles></project>")).unwrap().profiles
|
||||
}
|
||||
|
||||
fn holds(env: &Env, activation: &str) -> bool {
|
||||
let profiles = profiles(&format!("<profile><id>p</id><activation>{activation}</activation></profile>"));
|
||||
env.conditions(&profiles, &[], &mut Vec::new())[0]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_config_takes_one_option_per_line() {
|
||||
let config = MavenConfig::parse(
|
||||
"# shared options\n-Pci,!slow\n-P\nnative\n--activate-profiles=docs\n-Dflavor=x\n-Dquick\n-D\nmode=a=b\n-T4\n",
|
||||
);
|
||||
assert_eq!(config.profiles, ["ci", "!slow", "native", "docs"]);
|
||||
let properties = HashMap::from(
|
||||
[("flavor", "x"), ("quick", "true"), ("mode", "a=b")].map(|(k, v)| (k.to_owned(), v.to_owned())),
|
||||
);
|
||||
assert_eq!(config.properties, properties);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conditions_hold_as_mavens_activators_decide() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(dir.path().join("present")).unwrap();
|
||||
let activation = ProfileActivation { jdk: Some(21), ..Default::default() };
|
||||
let config = MavenConfig::parse("-Dflavor=x\n-Dempty=\n");
|
||||
let env = Env { activation: &activation, config: &config, basedir: dir.path() };
|
||||
let family = if cfg!(windows) {
|
||||
"windows"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"mac"
|
||||
} else {
|
||||
"unix"
|
||||
};
|
||||
let cases = [
|
||||
("<property><name>flavor</name></property>".to_owned(), true),
|
||||
("<property><name>!flavor</name></property>".into(), false),
|
||||
("<property><name>flavor</name><value>x</value></property>".into(), true),
|
||||
("<property><name>flavor</name><value>!x</value></property>".into(), false),
|
||||
("<property><name>empty</name></property>".into(), false),
|
||||
("<property><name>!unset</name></property>".into(), true),
|
||||
(format!("<os><family>{family}</family></os>"), true),
|
||||
(format!("<os><family>!{family}</family></os>"), false),
|
||||
("<os><family>os/400</family></os>".into(), false),
|
||||
(format!("<os><arch>{}</arch></os>", os_arch()), true),
|
||||
// Maven compares what Java reports (`Mac OS X`, `aarch64`), not other spellings.
|
||||
(format!("<os><name>{}</name></os>", os_name()), true),
|
||||
("<os><name>macos</name></os>".into(), false),
|
||||
("<os><arch>arm64</arch></os>".into(), false),
|
||||
("<os/>".into(), false),
|
||||
("<file><exists>present</exists></file>".into(), true),
|
||||
("<file><missing>${basedir}/absent</missing></file>".into(), true),
|
||||
("<file/>".into(), false),
|
||||
("<jdk>[17,)</jdk>".into(), true),
|
||||
("<jdk></jdk>".into(), true),
|
||||
(format!("<os><family>{family}</family></os><jdk>[30,)</jdk>"), false),
|
||||
];
|
||||
for (activation, expected) in cases {
|
||||
assert_eq!(holds(&env, &activation), expected, "{activation}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_turned_off_stays_off_and_active_by_default_ones_step_aside() {
|
||||
let ps = profiles(
|
||||
"<profile><id>dev</id><activation><activeByDefault>true</activeByDefault></activation></profile>\
|
||||
<profile><id>ci</id></profile>",
|
||||
);
|
||||
let config = MavenConfig::default();
|
||||
let none = [false, false];
|
||||
let select = |profiles: &[&str], choices: &[&str], implicit: bool| {
|
||||
let activation = ProfileActivation {
|
||||
profiles: profiles.iter().map(|p| p.to_string()).collect(),
|
||||
choices: choices.iter().map(|p| p.to_string()).collect(),
|
||||
jdk: None,
|
||||
};
|
||||
let env = Env { activation: &activation, config: &config, basedir: Path::new("/") };
|
||||
if implicit { env.implicit(&ps, &none) } else { env.select(&ps, &none, None) }
|
||||
};
|
||||
assert_eq!(select(&[], &[], false), [true, false]);
|
||||
assert_eq!(select(&[], &["ci"], false), [false, true]);
|
||||
assert_eq!(select(&[], &["ci", "dev"], false), [true, true]);
|
||||
// Turned off by the tool window while Settings turn it on: off, whatever the order.
|
||||
assert_eq!(select(&["ci"], &["!ci"], false), [true, false]);
|
||||
// Still on unless the tool window turns it off, so it keeps passing `-P!ci`.
|
||||
assert_eq!(select(&["ci"], &["!ci"], true), [true, true]);
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ use std::fs::{self, File};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
const DEPENDENCY_PLUGIN: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1";
|
||||
const SOURCE_REFRESH_WORKERS: usize = 4;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
@@ -44,7 +43,15 @@ impl Artifact {
|
||||
|
||||
/// Resolve only jars inside the selected local repository, including custom repositories.
|
||||
pub fn artifact(jar: &Path, repository: &Path) -> Option<Artifact> {
|
||||
let relative = jar.strip_prefix(repository).ok()?;
|
||||
let (jar, relative) = match jar.strip_prefix(repository) {
|
||||
Ok(rel) => (jar.to_path_buf(), rel.to_path_buf()),
|
||||
Err(_) => {
|
||||
let canon_repo = dunce::canonicalize(repository).ok()?;
|
||||
let canon_jar = dunce::canonicalize(jar).unwrap_or_else(|_| jar.to_path_buf());
|
||||
let rel = canon_jar.strip_prefix(&canon_repo).ok()?.to_path_buf();
|
||||
(canon_jar, rel)
|
||||
}
|
||||
};
|
||||
let parts: Vec<&str> = relative
|
||||
.components()
|
||||
.map(|c| match c {
|
||||
@@ -64,8 +71,8 @@ pub fn artifact(jar: &Path, repository: &Path) -> Option<Artifact> {
|
||||
group: parts[..n - 3].join("."),
|
||||
name: name.into(),
|
||||
version: version.into(),
|
||||
binary: jar.to_owned(),
|
||||
sources: jar.with_file_name(format!("{name}-{version}-sources.jar")),
|
||||
binary: jar,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -99,6 +106,11 @@ fn resolve(
|
||||
args.extend(profile_args.iter().cloned());
|
||||
args.push(format!("-Dmaven.repo.local={}", repository.display()));
|
||||
let coordinate = format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version);
|
||||
// The newest `maven-dependency-plugin` the project's Maven can load (#8114).
|
||||
let plugin = format!(
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:{}",
|
||||
super::pinned_plugin("maven-dependency-plugin", super::maven_version(&project.command))
|
||||
);
|
||||
let stage = if let Some(binary) = stale {
|
||||
// Keep the existing attachment readable while Maven resolves the timestamped snapshot.
|
||||
// Disable Resolver's in-place copy to the base -SNAPSHOT filename.
|
||||
@@ -107,14 +119,14 @@ fn resolve(
|
||||
args.extend([
|
||||
"-U".into(),
|
||||
"-Daether.artifactResolver.snapshotNormalization=false".into(),
|
||||
format!("{DEPENDENCY_PLUGIN}:copy"),
|
||||
format!("{plugin}:copy"),
|
||||
coordinate,
|
||||
"-Dmdep.useBaseVersion=true".into(),
|
||||
format!("-DoutputDirectory={}", stage.path().display()),
|
||||
]);
|
||||
Some((stage, binary))
|
||||
} else {
|
||||
args.extend([format!("{DEPENDENCY_PLUGIN}:get"), coordinate, "-Dtransitive=false".into()]);
|
||||
args.extend([format!("{plugin}:get"), coordinate, "-Dtransitive=false".into()]);
|
||||
None
|
||||
};
|
||||
let output = process::run(&project.command, &args, &root.join(&project.dir), &project.env, cancel, |_, _| {})?;
|
||||
@@ -290,6 +302,34 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_canonicalized_jar_against_non_canonical_repository() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let real_repo = dir.path().join("real-repo");
|
||||
let sibling = dir.path().join("other");
|
||||
let jar = real_repo.join("org/example/demo/1.2.3/demo-1.2.3.jar");
|
||||
fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
fs::create_dir_all(&sibling).unwrap();
|
||||
fs::write(&jar, b"").unwrap();
|
||||
let canon_jar = dunce::canonicalize(&jar).unwrap();
|
||||
let non_canon_repo = sibling.join("..").join("real-repo");
|
||||
|
||||
let found = artifact(&canon_jar, &non_canon_repo).expect("should match via canonicalized repo fallback");
|
||||
assert_eq!(found.group, "org.example");
|
||||
assert_eq!(found.name, "demo");
|
||||
assert_eq!(found.version, "1.2.3");
|
||||
assert_eq!(found.sources, canon_jar.with_file_name("demo-1.2.3-sources.jar"));
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let link_repo = dir.path().join("m2-link");
|
||||
std::os::unix::fs::symlink(&real_repo, &link_repo).unwrap();
|
||||
let linked = artifact(&canon_jar, &link_repo).expect("should match through symlinked Maven repo");
|
||||
assert_eq!(linked.group, "org.example");
|
||||
assert_eq!(linked.sources, canon_jar.with_file_name("demo-1.2.3-sources.jar"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_existing_snapshot_attachments_from_the_resolved_tree() {
|
||||
use crate::maven::{MavenDependency, Omission};
|
||||
|
||||
@@ -81,6 +81,9 @@ struct GradleCache {
|
||||
/// The projects report how their resources are processed; older caches are stale.
|
||||
#[serde(default)]
|
||||
resources: bool,
|
||||
/// The source sets report the `Test` tasks running them; older caches are stale.
|
||||
#[serde(default)]
|
||||
test_tasks: bool,
|
||||
}
|
||||
|
||||
/// Init script printing every project, its source sets and Java version once configured.
|
||||
@@ -89,34 +92,39 @@ const MODEL_INIT_SCRIPT: &str = include_str!("gradle-model.gradle");
|
||||
const MAVEN_CACHE: &str = "maven.json";
|
||||
const MAVEN_CACHE_VERSION: u32 = 1;
|
||||
|
||||
/// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven
|
||||
/// omitted (conflicts, duplicates): verbose output was dropped in 3.0 and is back since 3.2.
|
||||
/// Offline, it is used only when an earlier sync downloaded it; otherwise the newest version
|
||||
/// in the local repository is.
|
||||
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
|
||||
const DEPENDENCY_TREE_JAR: &str =
|
||||
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
|
||||
|
||||
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
|
||||
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
|
||||
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
|
||||
/// Offline without a cached 3.x `maven-help-plugin`, `effective-pom` is skipped so `mvn -o`
|
||||
/// still resolves the dependency tree instead of failing to download the help plugin.
|
||||
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
|
||||
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
|
||||
/// `repo` is the local repository the build resolves from and `maven` the version of the Maven
|
||||
/// that runs them, when known. Both goals name their plugin by coordinates: offline, a prefix
|
||||
/// resolves only from group metadata the repository may lack. The tree uses a pinned
|
||||
/// `maven-dependency-plugin` whose `-Dverbose` lists the occurrences Maven omitted (conflicts,
|
||||
/// duplicates; dropped in 3.0, back since 3.2), the newest that `maven` can load; offline it is
|
||||
/// used only when an earlier sync downloaded it, otherwise the newest compatible version in the
|
||||
/// local repository is. Offline without a cached compatible 3.x `maven-help-plugin`,
|
||||
/// `effective-pom` is skipped so `mvn -o` still resolves the dependency tree instead of failing
|
||||
/// to download the help plugin.
|
||||
fn maven_sync_goals(
|
||||
effective: &Path,
|
||||
offline: bool,
|
||||
repo: Option<&Path>,
|
||||
maven: Option<maven::MavenVersion>,
|
||||
) -> Vec<String> {
|
||||
let version = maven::pinned_plugin("maven-dependency-plugin", maven);
|
||||
let jar =
|
||||
format!("org/apache/maven/plugins/maven-dependency-plugin/{version}/maven-dependency-plugin-{version}.jar");
|
||||
let pinned = !offline || repo.is_some_and(|repo| repo.join(jar).is_file());
|
||||
let tree = if pinned {
|
||||
DEPENDENCY_TREE.to_owned()
|
||||
format!("org.apache.maven.plugins:maven-dependency-plugin:{version}:tree")
|
||||
} else {
|
||||
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2)).map_or_else(
|
||||
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2, maven)).map_or_else(
|
||||
|| "dependency:tree".to_owned(),
|
||||
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
|
||||
)
|
||||
};
|
||||
let has_help =
|
||||
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3).is_some());
|
||||
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3, maven).is_some());
|
||||
let mut goals = Vec::with_capacity(4);
|
||||
if has_help {
|
||||
goals.push(maven::plugin_goal("help:effective-pom", repo));
|
||||
goals.push(maven::plugin_goal("help:effective-pom", repo, maven));
|
||||
goals.push(format!("-Doutput={}", effective.to_string_lossy()));
|
||||
}
|
||||
goals.push(tree);
|
||||
@@ -295,8 +303,9 @@ pub fn apply_gradle_cache(root: &Path, cache_dir: &Path, model: &mut GradleModel
|
||||
}
|
||||
}
|
||||
// A successful sync from before projects were cached has not seen computed includes,
|
||||
// nor, before resources were read, which launches need Gradle to process them.
|
||||
let outdated = cache.error.is_none() && (cache.projects.is_empty() || !cache.resources);
|
||||
// nor, before resources were read, which launches need Gradle to process them, nor, before
|
||||
// test tasks were read, which task runs the tests of a test suite.
|
||||
let outdated = cache.error.is_none() && (cache.projects.is_empty() || !cache.resources || !cache.test_tasks);
|
||||
model.synced_at = Some(cache.at_ms);
|
||||
model.sync_error = cache.error;
|
||||
model.stale = outdated || cache.hash != hash_gradle_files(&gradle::build_files(root, model));
|
||||
@@ -375,11 +384,12 @@ pub fn sync_maven(
|
||||
cancel: &CancellationToken,
|
||||
progress: &dyn Fn(SyncProgress),
|
||||
) -> IdeResult<()> {
|
||||
let mut model = maven::load_with_linked_jdk(
|
||||
let activation =
|
||||
maven::ProfileActivation::new(root, &options.maven_settings, &options.profiles, options.jdk_version);
|
||||
let mut model = maven::load_with_activation(
|
||||
root,
|
||||
maven::default_local_repo(),
|
||||
&options.maven_settings.profiles(&options.profiles),
|
||||
options.jdk_version,
|
||||
&activation,
|
||||
&options.maven_settings.linked_projects,
|
||||
);
|
||||
maven::UnlinkedProjects::from_model(&model, &options.maven_settings).filter(&mut model);
|
||||
@@ -414,9 +424,9 @@ pub fn sync_maven(
|
||||
if !options.profiles.is_empty() {
|
||||
args.push(format!("-P{}", options.profiles.join(",")));
|
||||
}
|
||||
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref()));
|
||||
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
|
||||
let command = options.maven_command.as_deref().unwrap_or(&top.command);
|
||||
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref(), maven::maven_version(command)));
|
||||
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
|
||||
let out = run(command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
|
||||
if let Some((name, i, total)) = maven_building(line) {
|
||||
let fraction = (i.saturating_sub(1) as f32 / total.max(1) as f32).min(1.0);
|
||||
@@ -489,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());
|
||||
}
|
||||
@@ -526,6 +534,7 @@ pub fn sync_gradle_model(
|
||||
tasks: if out.success { gradle::parse_tasks(&out.text) } else { Vec::new() },
|
||||
projects,
|
||||
resources: true,
|
||||
test_tasks: true,
|
||||
};
|
||||
write_cache(&cache_dir, GRADLE_CACHE, &cache)
|
||||
}
|
||||
@@ -783,7 +792,7 @@ mod tests {
|
||||
test,
|
||||
src: src.iter().map(|p| core_src(p)).collect(),
|
||||
res: res.iter().map(|p| core_src(p)).collect(),
|
||||
processed: None,
|
||||
..Default::default()
|
||||
};
|
||||
// A settings script's own println comes first; task listing lines follow.
|
||||
let out = format!(
|
||||
@@ -884,6 +893,7 @@ mod tests {
|
||||
})
|
||||
.collect(),
|
||||
resources: true,
|
||||
test_tasks: true,
|
||||
};
|
||||
write_cache(&cache_dir, GRADLE_CACHE, &cache).unwrap();
|
||||
apply_gradle_cache(&root, &cache_dir, &mut model);
|
||||
@@ -929,6 +939,7 @@ mod tests {
|
||||
..Default::default()
|
||||
}],
|
||||
resources: true,
|
||||
test_tasks: true,
|
||||
..Default::default()
|
||||
};
|
||||
write_cache(&cache_dir, GRADLE_CACHE, &cache).unwrap();
|
||||
@@ -959,15 +970,19 @@ mod tests {
|
||||
assert!(!save_maven_offline(&tmp.path().join("other"), false).unwrap(), "online is the default");
|
||||
}
|
||||
|
||||
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
|
||||
const DEPENDENCY_TREE_JAR: &str =
|
||||
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
|
||||
|
||||
#[test]
|
||||
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline_without_it() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()), None);
|
||||
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
|
||||
// Offline with neither plugin cached: `effective-pom` is skipped so `mvn -o` does not fail
|
||||
// on an uncached `maven-help-plugin`, and the tree falls back to the project's own version.
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()), None);
|
||||
assert_eq!(offline, ["dependency:tree", "-Dverbose"]);
|
||||
// #5757 / #5844: offline, plugins in the local repository are named by their coordinates,
|
||||
// since the prefix needs group metadata a repository filled from a private mirror may lack;
|
||||
@@ -978,21 +993,37 @@ mod tests {
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
}
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()), None);
|
||||
assert_eq!(offline, ["org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree", "-Dverbose"]);
|
||||
let help_jar = tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.4.0/maven-help-plugin-3.4.0.jar");
|
||||
std::fs::create_dir_all(help_jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&help_jar, "").unwrap();
|
||||
// A version folder without its jar (only the POM was fetched) doesn't count.
|
||||
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()), None);
|
||||
assert_eq!(offline[0], "org.apache.maven.plugins:maven-help-plugin:3.4.0:effective-pom");
|
||||
assert_eq!(offline[2], "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree");
|
||||
// Downloaded by an online sync: offline keeps using it, the project's version may be missing.
|
||||
let jar = tmp.path().join(DEPENDENCY_TREE_JAR);
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
assert_eq!(maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()))[2], DEPENDENCY_TREE);
|
||||
assert_eq!(maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()), None)[2], DEPENDENCY_TREE);
|
||||
}
|
||||
|
||||
/// #8114: an old Maven gets plugin versions it can load, also for the verbose tree.
|
||||
#[test]
|
||||
fn sync_goals_follow_the_maven_version() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let goals = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()), Some((3, 3, 9)));
|
||||
assert_eq!(
|
||||
goals,
|
||||
[
|
||||
"org.apache.maven.plugins:maven-help-plugin:3.3.0:effective-pom",
|
||||
"-Doutput=e.xml",
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree",
|
||||
"-Dverbose",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1175,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);
|
||||
}
|
||||
}
|
||||
@@ -125,8 +125,11 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
|
||||
// POM's effective identity first; profiles and -D options can change its GAV.
|
||||
let output = cache.join("artifact-project.txt");
|
||||
let mut probe = top.options.clone();
|
||||
let evaluate =
|
||||
crate::maven::plugin_goal("help:evaluate", crate::maven::local_repository_for(&top.options).as_deref());
|
||||
let evaluate = crate::maven::plugin_goal(
|
||||
"help:evaluate",
|
||||
crate::maven::local_repository_for(&top.options).as_deref(),
|
||||
crate::maven::maven_version(&top.command),
|
||||
);
|
||||
probe.extend([
|
||||
"-f".into(),
|
||||
root.join(&p.pom).to_string_lossy().into_owned(),
|
||||
|
||||
@@ -380,6 +380,8 @@ pub struct CodeEditingSettings {
|
||||
pub quick_doc_delay: u32,
|
||||
/// Next / previous error goes to errors only (skips warnings).
|
||||
pub next_error_errors_only: bool,
|
||||
/// Show the diagnostic producer and rule code beneath each message in editor hover tooltips.
|
||||
pub show_diagnostic_source_on_hover: bool,
|
||||
pub sticky_lines_max: u32,
|
||||
pub sticky_lines_disabled_languages: Vec<String>,
|
||||
}
|
||||
@@ -393,6 +395,7 @@ impl Default for CodeEditingSettings {
|
||||
quick_doc_on_hover: true,
|
||||
quick_doc_delay: 500,
|
||||
next_error_errors_only: true,
|
||||
show_diagnostic_source_on_hover: true,
|
||||
sticky_lines_max: 5,
|
||||
sticky_lines_disabled_languages: Vec::new(),
|
||||
}
|
||||
@@ -744,4 +747,15 @@ mod sticky_lines_tests {
|
||||
assert_eq!(saved.sticky_lines_disabled_languages, ["markdown", "rust"]);
|
||||
assert_eq!(serde_json::to_value(saved).unwrap()["stickyLinesDisabledLanguages"], json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostic_source_on_hover_defaults_to_true_and_round_trips() {
|
||||
let legacy: CodeEditingSettings = serde_json::from_value(serde_json::json!({"quickDocOnHover": true})).unwrap();
|
||||
assert!(legacy.show_diagnostic_source_on_hover);
|
||||
let hidden: CodeEditingSettings =
|
||||
serde_json::from_value(serde_json::json!({"showDiagnosticSourceOnHover": false})).unwrap();
|
||||
assert!(!hidden.show_diagnostic_source_on_hover);
|
||||
let serialized = serde_json::to_value(&hidden).unwrap();
|
||||
assert_eq!(serialized["showDiagnosticSourceOnHover"], false);
|
||||
}
|
||||
}
|
||||
@@ -208,6 +208,12 @@ pub enum IdeEvent {
|
||||
/// A `LineEnding` in its serialized form: `lf`, `crLf` or `cr`.
|
||||
line_ending: String,
|
||||
},
|
||||
/// An open file was made read-only or writable outside the IDE (`chmod`, a VCS sync), which
|
||||
/// the editor only reads when it opens the file.
|
||||
DocReadOnly {
|
||||
doc: DocId,
|
||||
read_only: bool,
|
||||
},
|
||||
/// Full replacement of diagnostics for one file from one producer.
|
||||
Diagnostics {
|
||||
path: crate::IpcPath,
|
||||
|
||||
@@ -81,9 +81,61 @@ pub fn strip(src: &str) -> String {
|
||||
cleaned
|
||||
}
|
||||
|
||||
/// Comments and a leading byte order mark turned into spaces, byte for byte, so that offsets
|
||||
/// into the result are offsets into `src`. Line breaks stay, and so do trailing commas.
|
||||
pub fn blank_comments(src: &str) -> String {
|
||||
let mut out = src.as_bytes().to_vec();
|
||||
let blank = |out: &mut [u8]| out.iter_mut().filter(|b| !matches!(b, b'\n' | b'\r')).for_each(|b| *b = b' ');
|
||||
let mut i = 0;
|
||||
if src.starts_with('\u{feff}') {
|
||||
i = '\u{feff}'.len_utf8();
|
||||
blank(&mut out[..i]);
|
||||
}
|
||||
let mut in_str = false;
|
||||
while i < src.len() {
|
||||
let rest = &src.as_bytes()[i..];
|
||||
let comment = match rest {
|
||||
[b'\\', ..] if in_str => {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
[b'"', ..] => {
|
||||
in_str = !in_str;
|
||||
None
|
||||
}
|
||||
[b'/', b'/', ..] if !in_str => Some(rest.iter().position(|&b| b == b'\n').unwrap_or(rest.len())),
|
||||
// An unterminated block comment runs to the end, leaving a document that still parses
|
||||
// only if it was complete before it.
|
||||
[b'/', b'*', ..] if !in_str => {
|
||||
Some(rest[2..].windows(2).position(|w| w == b"*/").map_or(rest.len(), |end| end + 4))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
match comment {
|
||||
Some(len) => {
|
||||
blank(&mut out[i..i + len]);
|
||||
i += len;
|
||||
}
|
||||
None => i += 1,
|
||||
}
|
||||
}
|
||||
// Only whole characters were replaced: comments and the mark start and end on ASCII.
|
||||
String::from_utf8(out).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::strip;
|
||||
use super::{blank_comments, strip};
|
||||
|
||||
#[test]
|
||||
fn blanking_comments_keeps_every_offset_and_trailing_commas() {
|
||||
let src = "\u{feff}{// é\r\n\"a//\\\"\": /* ü\n*/ 1,}";
|
||||
let blank = blank_comments(src);
|
||||
assert_eq!(blank.len(), src.len());
|
||||
assert_eq!(blank.split_whitespace().collect::<Vec<_>>(), ["{", "\"a//\\\"\":", "1,}"]);
|
||||
assert_eq!(blank.find('1'), src.find('1'));
|
||||
assert_eq!(blank_comments("{}/* open é"), "{} ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drops_comments_and_trailing_commas_outside_strings() {
|
||||
|
||||
@@ -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()));
|
||||
|
||||
@@ -312,20 +312,7 @@ impl Default for AgentSkillPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
/// How an agent instruction, rule, or memory entry may load (`[agents.memory.entries.<id>] mode = …`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemoryMode {
|
||||
/// Load according to its native rules (always for instructions, matching files for path-scoped rules).
|
||||
#[default]
|
||||
Auto,
|
||||
/// Force-load into every session regardless of path scoping.
|
||||
Always,
|
||||
/// Exclude from sessions where the harness supports it.
|
||||
Off,
|
||||
}
|
||||
|
||||
/// How an agent's automatic cross-session memory runs (`[agents.memory] autoMemory = …`).
|
||||
/// How an agent's automatic cross-session memory runs (`[agents.memory.providers.<id>]`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AutoMemoryMode {
|
||||
@@ -340,24 +327,6 @@ pub enum AutoMemoryMode {
|
||||
Off,
|
||||
}
|
||||
|
||||
/// One memory or instruction entry's policy in Settings › Agents › Memory.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentMemoryEntryPolicy {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentMemoryMode)]
|
||||
pub mode: AgentMemoryMode,
|
||||
/// Agent provider ids this entry applies to; empty means all agents.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub agents: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for AgentMemoryEntryPolicy {
|
||||
fn default() -> Self {
|
||||
Self { mode: AgentMemoryMode::Auto, agents: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-provider auto-memory policy (`[agents.memory.providers.<id>]`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -371,18 +340,10 @@ pub struct AgentProviderMemoryPolicy {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentMemorySettings {
|
||||
/// Default cross-session auto-memory policy across agents.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AutoMemoryMode)]
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
/// Optional per-provider auto-memory overrides (`[agents.memory.providers.<provider>]`).
|
||||
/// Per-provider cross-session auto-memory overrides (`[agents.memory.providers.<provider>]`).
|
||||
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(type = BTreeMap<String, AgentProviderMemoryPolicy>)]
|
||||
pub providers: BTreeMap<String, AgentProviderMemoryPolicy>,
|
||||
/// Per-entry modes (`[agents.memory.entries.<id>]`).
|
||||
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(type = BTreeMap<String, AgentMemoryEntryPolicy>)]
|
||||
pub entries: BTreeMap<String, AgentMemoryEntryPolicy>,
|
||||
}
|
||||
|
||||
/// One agent plugin bundle's policy in Settings › Agents › Plugins
|
||||
@@ -865,19 +826,25 @@ pub enum ToolchainKind {
|
||||
/// mingw32-make and gdb from there.
|
||||
#[serde(rename = "mingw")]
|
||||
MinGw,
|
||||
/// A Visual Studio installation: configure, build and run get the environment its
|
||||
/// `vcvarsall.bat` sets up (Windows only).
|
||||
#[serde(rename = "visualStudio")]
|
||||
VisualStudio,
|
||||
}
|
||||
|
||||
/// Build, Execution, Deployment › Toolchains (IDE-wide, as in CLion). Empty fields are
|
||||
/// detected: from the MinGW directory, else from `PATH`.
|
||||
/// detected from the toolchain installation when it has them, else from `PATH`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Toolchain {
|
||||
pub name: String,
|
||||
pub kind: ToolchainKind,
|
||||
/// The MinGW directory (the one holding `bin`).
|
||||
/// The MinGW directory (the one holding `bin`), or the Visual Studio installation directory.
|
||||
pub path: String,
|
||||
/// `vcvarsall.bat`'s architecture argument (`x64`, `x86`, `x64_arm64` …); empty is the host's.
|
||||
pub arch: String,
|
||||
pub cmake: String,
|
||||
/// `CMAKE_MAKE_PROGRAM`: make, mingw32-make or ninja.
|
||||
/// `CMAKE_MAKE_PROGRAM`: make, mingw32-make, nmake or ninja.
|
||||
pub build_tool: String,
|
||||
pub c_compiler: String,
|
||||
pub cxx_compiler: String,
|
||||
@@ -1915,8 +1882,9 @@ pub struct PythonSettings {
|
||||
/// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses
|
||||
/// it, else unittest), `pytest` or `unittest`.
|
||||
pub test_runner: String,
|
||||
/// What Profile runs Python under (Settings › Python › Profiler): `auto` (py-spy where it
|
||||
/// is installed and samples without root, else cProfile), `cprofile` or `py-spy`.
|
||||
/// What Profile runs Python under (Settings › Python › Profiler): `auto` (yappi when the
|
||||
/// interpreter can import it, else py-spy where it is installed and samples without root, else
|
||||
/// cProfile), `cprofile`, `py-spy` or `yappi`.
|
||||
pub profiler: String,
|
||||
/// Show matplotlib figures of Python runs in the Plots tool window (the IDE sets `MPLBACKEND`
|
||||
/// unless the run sets it); off: matplotlib's own window.
|
||||
|
||||
@@ -14,4 +14,5 @@ serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
dunce.workspace = true
|
||||
tempfile.workspace = true
|
||||
@@ -51,8 +51,14 @@ fn resolve(filename: &str, sources: &[(PathBuf, bool)], base: &Path) -> PathBuf
|
||||
|
||||
/// Relative sources (and filenames without sources) resolve against `base`.
|
||||
pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Error> {
|
||||
let mut reader = Reader::from_str(xml);
|
||||
let mut acc = Accumulator::default();
|
||||
parse_into(xml, base, &mut acc)?;
|
||||
Ok(acc)
|
||||
}
|
||||
|
||||
/// Like [`parse`], merging into the data of other reports.
|
||||
pub(crate) fn parse_into(xml: &str, base: &Path, acc: &mut Accumulator) -> Result<(), quick_xml::Error> {
|
||||
let mut reader = Reader::from_str(xml);
|
||||
let mut sources: Vec<(PathBuf, bool)> = Vec::new();
|
||||
let mut source: Option<String> = None;
|
||||
let mut file: Option<PathBuf> = None;
|
||||
@@ -72,7 +78,8 @@ pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Er
|
||||
let Some(number) = attr(&e, "number").and_then(|n| n.parse::<u32>().ok()) else { continue };
|
||||
let line = number.saturating_sub(1);
|
||||
acc.line(path, line, attr(&e, "hits").and_then(|h| h.parse().ok()).unwrap_or(0));
|
||||
if attr(&e, "branch").as_deref() == Some("true")
|
||||
// coverlet writes `True`.
|
||||
if attr(&e, "branch").is_some_and(|b| b.eq_ignore_ascii_case("true"))
|
||||
&& let Some((covered, total)) = attr(&e, "condition-coverage").as_deref().and_then(conditions)
|
||||
{
|
||||
acc.has_branches = true;
|
||||
@@ -115,7 +122,7 @@ pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Er
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(acc)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -162,6 +169,16 @@ mod tests {
|
||||
assert!(parse("<coverage><packages></coverage>", Path::new("/root")).is_err());
|
||||
}
|
||||
|
||||
/// Written by `dotnet test --collect:"XPlat Code Coverage"` (coverlet.collector 6.0.4).
|
||||
#[test]
|
||||
fn reads_a_coverlet_report() {
|
||||
let suite =
|
||||
parse(include_str!("testdata/coverlet.cobertura.xml"), Path::new("/root")).unwrap().finish("coverlet");
|
||||
let [file] = suite.files.as_slice() else { panic!("{:?}", suite.files) };
|
||||
assert!((file.path.as_ref() as &Path).ends_with("home/dev/dn app/Calc/Calculator.cs"));
|
||||
assert_eq!((file.lines_covered, file.lines_total, file.branches_covered, file.branches_total), (6, 7, 1, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filenames_without_sources_resolve_against_the_base() {
|
||||
let xml = r#"<coverage><packages><package><classes><class filename="a/b.py"><lines><line number="1" hits="1"/></lines></class></classes></package></packages></coverage>"#;
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
//! `dotnet test` with coverage: coverlet.collector under VSTest,
|
||||
//! Microsoft.Testing.Extensions.CodeCoverage under Microsoft.Testing.Platform.
|
||||
//!
|
||||
//! The run gets its own results directory, so only this run's reports are read.
|
||||
|
||||
use crate::plan::{missing, ready, unsupported};
|
||||
use crate::{CoveragePrepared, CoverageReportSpec};
|
||||
use ide_run::{RunConfig, wrap};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const COLLECTOR: &str = "coverlet.collector";
|
||||
const CODE_COVERAGE: &str = "Microsoft.Testing.Extensions.CodeCoverage";
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
enum Runner {
|
||||
VsTest,
|
||||
/// `global.json` selects the testing platform's `dotnet test`.
|
||||
Mtp,
|
||||
/// A testing-platform project run through the VSTest target: its options go after `--`.
|
||||
MtpLegacy,
|
||||
}
|
||||
|
||||
/// What MSBuild says about a project: (testing-platform project, referenced packages).
|
||||
fn evaluation(json: &str) -> Option<(bool, Vec<String>)> {
|
||||
let json: serde_json::Value = serde_json::from_str(&json[json.find('{')?..]).ok()?;
|
||||
let packages: Vec<String> = json["Items"]["PackageReference"]
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter_map(|p| p["Identity"].as_str().map(str::to_ascii_lowercase))
|
||||
.collect();
|
||||
let mtp = json["Properties"]
|
||||
.as_object()
|
||||
.is_some_and(|p| p.values().any(|v| v.as_str().is_some_and(|v| v.eq_ignore_ascii_case("true"))))
|
||||
|| packages.iter().any(|p| p.starts_with("xunit.v3.mtp"));
|
||||
Some((mtp, packages))
|
||||
}
|
||||
|
||||
/// Whether the nearest `global.json` selects Microsoft.Testing.Platform.
|
||||
fn global_mtp(dir: &Path) -> bool {
|
||||
dir.ancestors().find_map(|d| std::fs::read_to_string(d.join("global.json")).ok()).is_some_and(|text| {
|
||||
serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
|
||||
.is_ok_and(|j| j["test"]["runner"] == "Microsoft.Testing.Platform")
|
||||
})
|
||||
}
|
||||
|
||||
/// The project file the configuration tests; none for a solution or a bare `dotnet test`.
|
||||
fn project_file(config: &RunConfig, dir: &Path) -> Option<PathBuf> {
|
||||
config
|
||||
.extras
|
||||
.params
|
||||
.get("project")
|
||||
.into_iter()
|
||||
.chain(config.args.iter().skip(1))
|
||||
.find(|a| Path::new(a).extension().is_some_and(|e| e.to_string_lossy().to_ascii_lowercase().ends_with("proj")))
|
||||
.map(|p| dir.join(p))
|
||||
}
|
||||
|
||||
pub(crate) fn prepare(config: &RunConfig, dir: &Path, out: &Path) -> CoveragePrepared {
|
||||
if config.args.first().is_none_or(|a| a != "test") {
|
||||
return unsupported(".NET coverage runs `dotnet test` configurations.");
|
||||
}
|
||||
let project = project_file(config, dir);
|
||||
let evaluated = project.as_ref().and_then(|project| {
|
||||
let mut argv = vec![
|
||||
config.command.clone(),
|
||||
"msbuild".into(),
|
||||
project.to_string_lossy().into_owned(),
|
||||
"-nologo".into(),
|
||||
"-getProperty:IsTestingPlatformApplication,TestingPlatformDotnetTestSupport,EnableMSTestRunner".into(),
|
||||
"-getItem:PackageReference".into(),
|
||||
];
|
||||
if let Some(framework) = config.extras.params.get("framework").filter(|f| !f.is_empty()) {
|
||||
argv.push(format!("-p:TargetFramework={framework}"));
|
||||
}
|
||||
evaluation(&wrap::capture(&argv, dir, config)?)
|
||||
});
|
||||
let project_dir = project.as_deref().and_then(Path::parent).unwrap_or(dir);
|
||||
let runner = if global_mtp(project_dir) {
|
||||
Runner::Mtp
|
||||
} else if evaluated.as_ref().is_some_and(|(mtp, _)| *mtp) {
|
||||
Runner::MtpLegacy
|
||||
} else {
|
||||
Runner::VsTest
|
||||
};
|
||||
let package = if runner == Runner::VsTest { COLLECTOR } else { CODE_COVERAGE };
|
||||
if let Some((project, (_, packages))) = project.as_ref().zip(evaluated.as_ref())
|
||||
&& !packages.iter().any(|p| p.eq_ignore_ascii_case(package))
|
||||
{
|
||||
let target = project.strip_prefix(dir).unwrap_or(project).to_string_lossy();
|
||||
let add = [&config.command, "add", &target, "package", package].map(str::to_owned);
|
||||
return missing(
|
||||
package,
|
||||
format!(".NET coverage needs the {package} package in the test project."),
|
||||
Some((add.to_vec(), dir)),
|
||||
);
|
||||
}
|
||||
launch(config, dir, out, runner, package)
|
||||
}
|
||||
|
||||
fn launch(config: &RunConfig, dir: &Path, out: &Path, runner: Runner, package: &str) -> CoveragePrepared {
|
||||
let results = out.to_string_lossy().into_owned();
|
||||
let mut extra: Vec<String> = match runner {
|
||||
Runner::VsTest => vec!["--collect:XPlat Code Coverage".into()],
|
||||
_ => ["--coverage", "--coverage-output-format", "cobertura"].map(str::to_owned).to_vec(),
|
||||
};
|
||||
extra.extend(["--results-directory".into(), results]);
|
||||
let mut launch = config.clone();
|
||||
// A `dotnet test` configuration type rebuilds its command line from the parameters.
|
||||
launch.extras.params.insert("coverageArgs".into(), serde_json::json!(extra).to_string());
|
||||
let boundary = launch.args.iter().position(|a| a == "--");
|
||||
match runner {
|
||||
Runner::VsTest => {
|
||||
let at = boundary.unwrap_or(launch.args.len());
|
||||
launch.args.splice(at..at, extra);
|
||||
}
|
||||
Runner::Mtp => launch.args.extend(extra),
|
||||
Runner::MtpLegacy => {
|
||||
if boundary.is_none() {
|
||||
launch.args.push("--".into());
|
||||
}
|
||||
launch.args.extend(extra);
|
||||
}
|
||||
}
|
||||
let report = CoverageReportSpec::Cobertura {
|
||||
runner: package.to_owned(),
|
||||
dir: out.to_path_buf().into(),
|
||||
base: dir.to_path_buf().into(),
|
||||
hint: format!("Check the test output, and that every test project references {package}."),
|
||||
};
|
||||
ready(package, &launch, launch.command.clone(), launch.args.clone(), report)
|
||||
}
|
||||
|
||||
/// VSTest writes `<dir>/<guid>/coverage.cobertura.xml`, the testing platform
|
||||
/// `<dir>/<name>.cobertura.xml`. Deeper files are the TRX logger's copies of the same data.
|
||||
pub(crate) fn reports(dir: &Path) -> Vec<PathBuf> {
|
||||
let is_report = |p: &Path| p.is_file() && p.to_string_lossy().ends_with(".cobertura.xml");
|
||||
let entries = |d: &Path| std::fs::read_dir(d).into_iter().flatten().flatten().map(|e| e.path()).collect::<Vec<_>>();
|
||||
let mut found: Vec<PathBuf> = entries(dir)
|
||||
.into_iter()
|
||||
.flat_map(|p| if p.is_dir() { entries(&p) } else { vec![p] })
|
||||
.filter(|p| is_report(p))
|
||||
.collect();
|
||||
found.sort();
|
||||
found
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn config(args: &[&str]) -> RunConfig {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "t", "name": "t", "kind": "shell", "command": "dotnet", "args": args,
|
||||
"env": {}, "detected": true, "isTest": true,
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn args(runner: Runner, base: &[&str]) -> Vec<String> {
|
||||
match launch(&config(base), Path::new("/p"), Path::new("/o"), runner, "x") {
|
||||
CoveragePrepared::Ready { launch, .. } => launch.args,
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_go_where_each_runner_reads_them() {
|
||||
assert_eq!(
|
||||
args(Runner::VsTest, &["test", "--", "A=1"]),
|
||||
["test", "--collect:XPlat Code Coverage", "--results-directory", "/o", "--", "A=1"]
|
||||
);
|
||||
let platform = ["--coverage", "--coverage-output-format", "cobertura", "--results-directory", "/o"];
|
||||
assert_eq!(args(Runner::Mtp, &["test"])[1..], platform);
|
||||
let legacy = args(Runner::MtpLegacy, &["test"]);
|
||||
assert_eq!((legacy[1].as_str(), &legacy[2..]), ("--", platform.map(str::to_owned).as_slice()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn msbuild_evaluation_names_packages_and_the_platform() {
|
||||
let json = r#"noise {"Properties":{"IsTestingPlatformApplication":""},"Items":{"PackageReference":[{"Identity":"Coverlet.Collector"}]}}"#;
|
||||
assert_eq!(evaluation(json), Some((false, vec!["coverlet.collector".into()])));
|
||||
let json = r#"{"Properties":{"EnableMSTestRunner":"true"},"Items":{"PackageReference":[]}}"#;
|
||||
assert_eq!(evaluation(json), Some((true, vec![])));
|
||||
assert_eq!(evaluation("error MSB1009"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_files_and_global_json() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let project = project_file(&config(&["test", "a/T.fsproj"]), tmp.path()).unwrap();
|
||||
assert_eq!(project, tmp.path().join("a/T.fsproj"));
|
||||
assert_eq!(project_file(&config(&["test", "All.sln"]), tmp.path()), None);
|
||||
assert!(!global_mtp(&tmp.path().join("a")));
|
||||
std::fs::write(
|
||||
tmp.path().join("global.json"),
|
||||
"{ // x\n\"test\":{\"runner\":\"Microsoft.Testing.Platform\"},}",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(global_mtp(&tmp.path().join("a")));
|
||||
}
|
||||
|
||||
/// One report per test project is merged; the TRX logger's copies are not counted twice.
|
||||
#[test]
|
||||
fn merges_the_reports_of_one_run() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let xml = include_str!("testdata/coverlet.cobertura.xml");
|
||||
for file in
|
||||
["guid-a/coverage.cobertura.xml", "guid-b/coverage.cobertura.xml", "t/In/host/coverage.cobertura.xml"]
|
||||
{
|
||||
let file = tmp.path().join(file);
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(file, xml).unwrap();
|
||||
}
|
||||
let spec = CoverageReportSpec::Cobertura {
|
||||
runner: "coverlet.collector".into(),
|
||||
dir: tmp.path().to_path_buf().into(),
|
||||
base: tmp.path().to_path_buf().into(),
|
||||
hint: "why".into(),
|
||||
};
|
||||
let suite = crate::collect(&spec).unwrap();
|
||||
assert_eq!(suite.files[0].lines[0].hits, 2);
|
||||
std::fs::write(tmp.path().join("direct.cobertura.xml"), xml).unwrap();
|
||||
assert_eq!(reports(tmp.path()).len(), 3);
|
||||
// A cancelled or failed build leaves nothing: say why.
|
||||
let empty = tempfile::tempdir().unwrap();
|
||||
let spec = CoverageReportSpec::Cobertura {
|
||||
runner: "x".into(),
|
||||
dir: empty.path().to_path_buf().into(),
|
||||
base: empty.path().to_path_buf().into(),
|
||||
hint: "why".into(),
|
||||
};
|
||||
assert!(crate::collect(&spec).unwrap_err().to_string().contains("why"));
|
||||
}
|
||||
}
|
||||
@@ -14,11 +14,13 @@
|
||||
//! | Go (`go test`) | `-coverprofile` | Go cover profile |
|
||||
//! | Maven / Gradle tests | JaCoCo (plugin goals / an init script) | JaCoCo XML |
|
||||
//! | Xcode tests (`xcodebuild test`) | `-enableCodeCoverage YES` | the result bundle, read with `xccov` |
|
||||
//! | .NET (`dotnet test`) | coverlet.collector, or Microsoft.Testing.Extensions.CodeCoverage | Cobertura XML |
|
||||
//!
|
||||
//! Lines in the model are 0-based, like every IPC coordinate.
|
||||
|
||||
mod cobertura;
|
||||
mod coveragepy;
|
||||
mod dotnet;
|
||||
mod goprofile;
|
||||
mod import;
|
||||
mod jacoco;
|
||||
@@ -94,6 +96,9 @@ pub enum CoverageReportSpec {
|
||||
SimpleCov { path: IpcPath, base: IpcPath },
|
||||
/// Every JaCoCo XML report (Maven `target/site/jacoco`, Gradle `build/reports/jacoco`) under `dir`.
|
||||
Jacoco { dir: IpcPath },
|
||||
/// The Cobertura reports `dotnet test` left in its results directory `dir`: one per test
|
||||
/// project and target framework. `hint` explains why there might be none.
|
||||
Cobertura { runner: String, dir: IpcPath, base: IpcPath, hint: String },
|
||||
/// The tool's raw data is exported to lcov by `argv` first (coverage.py: `… -m coverage lcov -o <lcov>`).
|
||||
Exported { runner: String, argv: Vec<String>, cwd: IpcPath, env: BTreeMap<String, String>, lcov: IpcPath },
|
||||
/// An Xcode result bundle, read with `xcrun xccov`; only files under `root` are kept.
|
||||
@@ -218,6 +223,19 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult<CoverageSuite> {
|
||||
}
|
||||
Ok(acc.finish("JaCoCo"))
|
||||
}
|
||||
CoverageReportSpec::Cobertura { runner, dir, base, hint } => {
|
||||
let reports = dotnet::reports(dir);
|
||||
if reports.is_empty() {
|
||||
return Err(IdeError::not_found(format!("the run produced no coverage report. {hint}")));
|
||||
}
|
||||
let mut acc = Accumulator::default();
|
||||
for report in reports {
|
||||
let xml = std::fs::read_to_string(&report)?;
|
||||
cobertura::parse_into(&xml, base, &mut acc)
|
||||
.map_err(|e| IdeError::invalid(format!("{}: {e}", report.display())))?;
|
||||
}
|
||||
Ok(acc.finish(runner))
|
||||
}
|
||||
CoverageReportSpec::Exported { runner, argv, cwd, env, lcov } => {
|
||||
let (program, args) =
|
||||
argv.split_first().ok_or_else(|| IdeError::invalid("empty coverage export command"))?;
|
||||
|
||||
@@ -28,11 +28,15 @@ fn path(p: &Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn unsupported(reason: impl Into<String>) -> CoveragePrepared {
|
||||
pub(crate) fn unsupported(reason: impl Into<String>) -> CoveragePrepared {
|
||||
CoveragePrepared::Unsupported { reason: reason.into() }
|
||||
}
|
||||
|
||||
fn missing(tool: &str, message: impl Into<String>, install: Option<(Vec<String>, &Path)>) -> CoveragePrepared {
|
||||
pub(crate) fn missing(
|
||||
tool: &str,
|
||||
message: impl Into<String>,
|
||||
install: Option<(Vec<String>, &Path)>,
|
||||
) -> CoveragePrepared {
|
||||
CoveragePrepared::MissingTool {
|
||||
tool: tool.to_owned(),
|
||||
message: message.into(),
|
||||
@@ -43,7 +47,7 @@ fn missing(tool: &str, message: impl Into<String>, install: Option<(Vec<String>,
|
||||
}
|
||||
}
|
||||
|
||||
fn ready(
|
||||
pub(crate) fn ready(
|
||||
runner: &str,
|
||||
config: &RunConfig,
|
||||
command: String,
|
||||
@@ -69,6 +73,7 @@ pub fn prepare(root: &Path, config: &RunConfig, out: &Path) -> CoveragePrepared
|
||||
let first = config.args.first().map(String::as_str).unwrap_or_default();
|
||||
match program.as_str() {
|
||||
"cargo" => cargo(config, &dir, out),
|
||||
"dotnet" => crate::dotnet::prepare(config, &dir, out),
|
||||
"go" if first == "test" => go(config, &dir, out),
|
||||
"go" => unsupported("Go coverage is collected by `go test`; run a test configuration with coverage."),
|
||||
"mvn" | "mvnw" => maven(config, &dir),
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<coverage line-rate="0.8571" branch-rate="0.5" version="1.9" timestamp="1796282470" lines-covered="6" lines-valid="7" branches-covered="1" branches-valid="2">
|
||||
<sources>
|
||||
<source>/</source>
|
||||
</sources>
|
||||
<packages>
|
||||
<package name="Calc" line-rate="0.8571" branch-rate="0.5" complexity="3">
|
||||
<classes>
|
||||
<class name="Calc.Calculator" filename="home/dev/dn app/Calc/Calculator.cs" line-rate="0.8571" branch-rate="0.5" complexity="3">
|
||||
<methods>
|
||||
<method name="Add" signature="(System.Int32,System.Int32)" line-rate="1" branch-rate="1" complexity="1">
|
||||
<lines>
|
||||
<line number="5" hits="1" branch="False" />
|
||||
</lines>
|
||||
</method>
|
||||
<method name="Sign" signature="(System.Int32)" line-rate="0.8332999999999999" branch-rate="0.5" complexity="2">
|
||||
<lines>
|
||||
<line number="8" hits="1" branch="False" />
|
||||
<line number="9" hits="1" branch="True" condition-coverage="50% (1/2)">
|
||||
<conditions>
|
||||
<condition number="7" type="jump" coverage="50%" />
|
||||
</conditions>
|
||||
</line>
|
||||
<line number="10" hits="1" branch="False" />
|
||||
<line number="11" hits="1" branch="False" />
|
||||
<line number="13" hits="0" branch="False" />
|
||||
<line number="14" hits="1" branch="False" />
|
||||
</lines>
|
||||
</method>
|
||||
</methods>
|
||||
<lines>
|
||||
<line number="5" hits="1" branch="False" />
|
||||
<line number="8" hits="1" branch="False" />
|
||||
<line number="9" hits="1" branch="True" condition-coverage="50% (1/2)">
|
||||
<conditions>
|
||||
<condition number="7" type="jump" coverage="50%" />
|
||||
</conditions>
|
||||
</line>
|
||||
<line number="10" hits="1" branch="False" />
|
||||
<line number="11" hits="1" branch="False" />
|
||||
<line number="13" hits="0" branch="False" />
|
||||
<line number="14" hits="1" branch="False" />
|
||||
</lines>
|
||||
</class>
|
||||
</classes>
|
||||
</package>
|
||||
</packages>
|
||||
</coverage>
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Run with Coverage against the real `dotnet` CLI on `fixtures/dotnet-coverage`.
|
||||
//! Skipped without a .NET 10 SDK, except in CI, where the workflow installs one.
|
||||
|
||||
use ide_coverage::{CoveragePrepared, CoverageSuite, collect, prepare};
|
||||
use ide_run::RunConfig;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
fn has_sdk() -> bool {
|
||||
let found = Command::new("dotnet")
|
||||
.arg("--list-sdks")
|
||||
.output()
|
||||
.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).lines().any(|l| l.starts_with("10.")));
|
||||
assert!(found || std::env::var_os("CI").is_none(), "CI needs the .NET 10 SDK");
|
||||
found
|
||||
}
|
||||
|
||||
fn copy(from: &Path, to: &Path) {
|
||||
std::fs::create_dir_all(to).unwrap();
|
||||
for entry in std::fs::read_dir(from).unwrap().flatten() {
|
||||
let (name, path) = (entry.file_name(), entry.path());
|
||||
if path.is_dir() {
|
||||
if name != "bin" && name != "obj" {
|
||||
copy(&path, &to.join(name));
|
||||
}
|
||||
} else {
|
||||
std::fs::copy(&path, to.join(name)).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn config(args: &[&str]) -> RunConfig {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "t", "name": "t", "kind": "shell", "command": "dotnet", "args": args,
|
||||
"env": {}, "detected": true, "isTest": true,
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Prepares, runs and collects like the IDE does; `out` has a space in its name.
|
||||
fn covered(root: &Path, config: &RunConfig, out: &Path) -> CoverageSuite {
|
||||
std::fs::create_dir_all(out).unwrap();
|
||||
let CoveragePrepared::Ready { launch, report, .. } = prepare(root, config, out) else {
|
||||
panic!("{:?}", prepare(root, config, out));
|
||||
};
|
||||
let cwd = launch.cwd.as_deref().map_or_else(|| root.to_path_buf(), |c| root.join(c));
|
||||
let run = Command::new(&launch.command).args(&launch.args).current_dir(cwd).output().unwrap();
|
||||
assert!(run.status.success(), "{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
|
||||
collect(&report).unwrap()
|
||||
}
|
||||
|
||||
/// (covered, total) lines of `Calculator.cs`, which must exist on this machine.
|
||||
fn calculator(suite: &CoverageSuite) -> (u32, u32) {
|
||||
let file = suite.files.iter().find(|f| (f.path.as_ref() as &Path).ends_with("Calc/Calculator.cs"));
|
||||
let file = file.unwrap_or_else(|| panic!("{:?}", suite.files));
|
||||
assert!((file.path.as_ref() as &Path).is_file(), "{:?}", file.path);
|
||||
(file.lines_covered, file.lines_total)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vstest_projects_solutions_and_missing_packages() {
|
||||
if !has_sdk() {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
copy(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/dotnet-coverage"), &root);
|
||||
|
||||
let project = config(&["test", "Add.Tests/Add.Tests.csproj"]);
|
||||
let one = covered(&root, &project, &root.join("out one"));
|
||||
assert_eq!(calculator(&one), (1, 7));
|
||||
// Both test projects of the solution are merged.
|
||||
let all = covered(&root, &config(&["test", "Calc.slnx"]), &root.join("out all"));
|
||||
assert_eq!(calculator(&all), (6, 7));
|
||||
|
||||
let csproj = root.join("Add.Tests/Add.Tests.csproj");
|
||||
let text = std::fs::read_to_string(&csproj).unwrap();
|
||||
let without: Vec<&str> = text.lines().filter(|l| !l.contains("coverlet")).collect();
|
||||
std::fs::write(&csproj, without.join("\n")).unwrap();
|
||||
match prepare(&root, &project, &root.join("out one")) {
|
||||
CoveragePrepared::MissingTool { tool, install: Some(install), .. } => {
|
||||
assert_eq!(tool, "coverlet.collector");
|
||||
assert_eq!(install.args, ["add", "Add.Tests/Add.Tests.csproj", "package", "coverlet.collector"]);
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn testing_platform_projects() {
|
||||
if !has_sdk() {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
copy(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/dotnet-coverage"), &root);
|
||||
// `global.json` is read from the working directory.
|
||||
let mut config = config(&["test", "--project", "Mtp.Tests.csproj"]);
|
||||
config.cwd = Some(root.join("mtp").into());
|
||||
assert_eq!(calculator(&covered(&root, &config, &root.join("out mtp"))), (1, 7));
|
||||
}
|
||||
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> {
|
||||
@@ -1487,34 +1564,204 @@ impl Pool {
|
||||
($c:expr) => {{
|
||||
let mut tx = (&mut **$c).begin().await.map_err(db_err)?;
|
||||
let mut total = 0;
|
||||
let mut failed = None;
|
||||
for (sql, expect_one) in statements {
|
||||
let done = sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone()))
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
let n = done.rows_affected();
|
||||
if *expect_one && (n > 1 || (n == 0 && !matches!(self, Pool::Mysql(_)))) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
let n = match sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut *tx).await {
|
||||
Ok(done) => done.rows_affected(),
|
||||
Err(e) => {
|
||||
failed = Some(db_err(e));
|
||||
break;
|
||||
}
|
||||
};
|
||||
// MySQL counts the rows a statement matched (sqlx asks for CLIENT_FOUND_ROWS),
|
||||
// so a row left as it was counts and a key that matches none is 0.
|
||||
if *expect_one && n != 1 {
|
||||
failed = Some(IdeError::invalid(format!(
|
||||
"{sql}: expected to change 1 row, changed {n}; nothing was saved"
|
||||
)));
|
||||
break;
|
||||
}
|
||||
total += n;
|
||||
}
|
||||
tx.commit().await.map_err(db_err)?;
|
||||
Ok(total)
|
||||
match failed {
|
||||
None => (tx.commit().await.map(|()| total).map_err(db_err), true),
|
||||
// Rolled back here: a dropped transaction rolls back only when its connection
|
||||
// is next used, and keeps the table's locks in the pool until then.
|
||||
Some(error) => (Err(error), tx.rollback().await.is_ok()),
|
||||
}
|
||||
}};
|
||||
}
|
||||
match &mut conn {
|
||||
let (result, clean) = match &mut conn {
|
||||
Held::Sqlite(c) => transaction!(c),
|
||||
Held::Postgres(c) => transaction!(&mut ***c),
|
||||
Held::Mysql(c) => transaction!(&mut ***c),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
if !clean {
|
||||
// A failed rollback must never return an open transaction to the pool.
|
||||
conn.discard().await;
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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>),
|
||||
@@ -1639,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;
|
||||
}
|
||||
@@ -2269,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() {
|
||||
|
||||
@@ -163,6 +163,7 @@ pub(super) struct ConsoleSession {
|
||||
|
||||
impl ConsoleSession {
|
||||
/// Runs `statement` on the console's connection; `None` when it has none and needs none.
|
||||
/// `pinned`: a script's, which every statement needs.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) async fn execute(
|
||||
&self,
|
||||
@@ -173,6 +174,7 @@ impl ConsoleSession {
|
||||
max_rows: usize,
|
||||
request: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
pinned: bool,
|
||||
) -> IdeResult<Option<QueryResult>> {
|
||||
let cancel = self.retired.child_token();
|
||||
let mut slot = tokio::select! {
|
||||
@@ -189,7 +191,7 @@ impl ConsoleSession {
|
||||
}
|
||||
let schema = schema.filter(|s| !s.is_empty());
|
||||
if slot.open.is_none() {
|
||||
if !needs_session(statement, pool.driver()) {
|
||||
if !pinned && !needs_session(statement, pool.driver()) {
|
||||
return Ok(None);
|
||||
}
|
||||
slot.open = Some(tokio::select! {
|
||||
|
||||
@@ -404,11 +404,21 @@ pub struct ConsoleId<'a> {
|
||||
pub window: &'a str,
|
||||
pub path: &'a str,
|
||||
expected_manual: Option<bool>,
|
||||
/// Keeps its connection from the first statement on, not from the first that needs one.
|
||||
script: bool,
|
||||
}
|
||||
|
||||
impl<'a> ConsoleId<'a> {
|
||||
pub const fn new(window: &'a str, path: &'a str) -> Self {
|
||||
Self { window, path, expected_manual: None }
|
||||
Self { window, path, expected_manual: None, script: false }
|
||||
}
|
||||
|
||||
/// A run of statements outside any console, `run` naming it uniquely in `window`. It runs on one
|
||||
/// connection, as each database's own client runs a script, and releasing it with
|
||||
/// [`DbManager::release_target_console`] closes that connection instead of returning it to the
|
||||
/// pool with the session state the script left.
|
||||
pub const fn script(window: &'a str, run: &'a str) -> Self {
|
||||
Self { window, path: run, expected_manual: None, script: true }
|
||||
}
|
||||
|
||||
pub fn expecting_manual(mut self, manual: Option<bool>) -> Self {
|
||||
@@ -1982,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
|
||||
@@ -2226,7 +2257,8 @@ impl DbManager {
|
||||
return p.execute_in_console(statement, skip, max_rows, cancel, console).await;
|
||||
}
|
||||
let editor = console.filter(|_| !matches!(&*pool, Pool::Snowflake(_)) && !pool.transaction_read_only());
|
||||
let console = console.filter(|_| matches!(&*pool, Pool::Postgres(_)));
|
||||
// A script has no console transaction: it runs in the data source's manual transaction, if any.
|
||||
let console = console.filter(|c| !c.script && matches!(&*pool, Pool::Postgres(_)));
|
||||
let session = match console {
|
||||
Some(console) => connection.console_transactions.session(console),
|
||||
None => self.sessions.lock().get(id).cloned(),
|
||||
@@ -2450,10 +2482,11 @@ impl DbManager {
|
||||
}
|
||||
let pool = self.pool(id).await?;
|
||||
let driver = pool.driver();
|
||||
let binary = binary_columns(&pool, driver, schema, table, edits).await?;
|
||||
let statements = edits
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let sql = sql::edit_statement(driver, schema, table, e).map_err(IdeError::invalid)?;
|
||||
let sql = sql::edit_statement(driver, schema, table, e, &binary).map_err(IdeError::invalid)?;
|
||||
Ok((sql, !matches!(e, DbRowEdit::Insert { .. })))
|
||||
})
|
||||
.collect::<IdeResult<Vec<_>>>()?;
|
||||
@@ -2461,6 +2494,36 @@ impl DbManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// The columns of `table` whose bytes the grid shows as `0x…` hex, looked up only when an edit
|
||||
/// carries such a value.
|
||||
async fn binary_columns(
|
||||
pool: &Pool,
|
||||
driver: DbDriver,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
edits: &[DbRowEdit],
|
||||
) -> IdeResult<Vec<String>> {
|
||||
let hex =
|
||||
|c: &CellValue| c.value.as_deref().is_some_and(|v| v.get(..2).is_some_and(|p| p.eq_ignore_ascii_case("0x")));
|
||||
let carries_hex = edits.iter().any(|edit| match edit {
|
||||
DbRowEdit::Update { key, values } => key.iter().chain(values).any(hex),
|
||||
DbRowEdit::Insert { values: cells } | DbRowEdit::Delete { key: cells } => cells.iter().any(hex),
|
||||
});
|
||||
// The dialects `sql::binary_column` knows binary types of.
|
||||
if !carries_hex || !matches!(driver, DbDriver::Sqlite | DbDriver::Mysql | DbDriver::SqlServer) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let rows = pool.rows(&sql::columns(driver, schema, table), MAX_META_ROWS).await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
let name = it.next().flatten()?;
|
||||
it.next().flatten().is_some_and(|t| sql::binary_column(driver, &t)).then_some(name)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -208,7 +208,8 @@ impl ConsoleTransactions {
|
||||
auto.entry(key(console)).or_default().clone()
|
||||
};
|
||||
// Boxed: the connect inside would double the size of every statement's future.
|
||||
Box::pin(session.execute(pool, &self.auto_capacity, statement, skip, max_rows, cancel, schema)).await
|
||||
Box::pin(session.execute(pool, &self.auto_capacity, statement, skip, max_rows, cancel, schema, console.script))
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn release_auto(&self, console: ConsoleId<'_>) {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -2,9 +2,12 @@
|
||||
//! literals, quoted identifiers, comments and PostgreSQL dollar quoting.
|
||||
//! MySQL strings take backslash escapes (no `NO_BACKSLASH_ESCAPES`) and double
|
||||
//! quotes (no `ANSI_QUOTES`), its defaults; the console's lexer.ts reads them alike.
|
||||
//! Routine and trigger bodies, the mysql client's `DELIMITER` and SQL Server's
|
||||
//! `GO` end statements where each dialect's own client ends them.
|
||||
//! 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;
|
||||
|
||||
@@ -29,6 +32,19 @@ enum State {
|
||||
BlockComment,
|
||||
}
|
||||
|
||||
/// The routine or trigger body a statement holds: what ends the statement, as its `;` may not.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Body {
|
||||
None,
|
||||
/// BEGIN … END blocks (and the CASE … END inside them) outside parentheses: psql's rule for
|
||||
/// PostgreSQL routines, also read in MySQL routines and every T-SQL statement.
|
||||
Blocks,
|
||||
/// A SQLite trigger, which only `;` END `;` ends (sqlite3_complete).
|
||||
Trigger,
|
||||
/// A SQL Server routine: the rest of its batch.
|
||||
Batch,
|
||||
}
|
||||
|
||||
// Starts just after the opening `/*`.
|
||||
fn after_nested_block_comment(mut text: &str) -> &str {
|
||||
let mut depth = 1usize;
|
||||
@@ -74,6 +90,12 @@ pub(super) fn clickhouse_keyword<'a>(sql: &mut &'a str) -> Option<&'a str> {
|
||||
|
||||
/// Every statement of `text` that contains more than whitespace and comments.
|
||||
pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
split_with(text, driver, ";".into()).0
|
||||
}
|
||||
|
||||
/// [`split`] with the mysql client's `delimiter` in effect at the start; also returns the one in
|
||||
/// effect at the end.
|
||||
fn split_with(text: &str, driver: DbDriver, mut delimiter: String) -> (Vec<SqlStatement>, String) {
|
||||
let mysql = driver == DbDriver::Mysql;
|
||||
let clickhouse = driver == DbDriver::Clickhouse;
|
||||
// PL/SQL: `;` inside BEGIN…END / DECLARE…END blocks does not terminate a statement.
|
||||
@@ -114,6 +136,21 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
let mut defines = false;
|
||||
// The open string is PostgreSQL's `E'…'`.
|
||||
let mut escape_string = false;
|
||||
let mut body = Body::None;
|
||||
// Block keywords inside parentheses (a parameter named `begin`) count for nothing.
|
||||
let mut parens = 0usize;
|
||||
// The previous `;` of a SQLite trigger.
|
||||
let mut last_semi: Option<usize> = None;
|
||||
let routines = postgres || mysql || sqlite || sql_server;
|
||||
// The next statement starts at `$at`, with nothing open.
|
||||
macro_rules! next_statement {
|
||||
($at:expr) => {{
|
||||
start = $at;
|
||||
has_code = false;
|
||||
(depth, declarations, block, package, script, defines) = (0, false, false, false, false, false);
|
||||
(body, parens, last_semi) = (Body::None, 0, None);
|
||||
}};
|
||||
}
|
||||
let push = |out: &mut Vec<SqlStatement>, s: usize, e: usize, has_code: bool| {
|
||||
if !has_code {
|
||||
return;
|
||||
@@ -135,6 +172,33 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
while i < chars.len() {
|
||||
let c = chars[i].1;
|
||||
let next = chars.get(i + 1).map(|c| c.1);
|
||||
// Lines the client reads itself instead of sending them.
|
||||
let command = match c {
|
||||
'G' | 'g' => sql_server,
|
||||
'D' | 'd' => mysql && !has_code,
|
||||
_ => false,
|
||||
};
|
||||
if command && state == State::Code && starts_line(&chars, i) {
|
||||
if let Some(end) = go_line(&chars, i) {
|
||||
// sqlcmd and SSMS send the batch so far.
|
||||
push(&mut out, start, i, has_code);
|
||||
next_statement!(end);
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
if let Some((set, end)) = delimiter_line(&chars, i) {
|
||||
delimiter = set;
|
||||
next_statement!(end);
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if state == State::Code && delimiter != ";" && text[byte_at(i)..].starts_with(delimiter.as_str()) {
|
||||
push(&mut out, start, i, has_code);
|
||||
i += delimiter.chars().count();
|
||||
next_statement!(i);
|
||||
continue;
|
||||
}
|
||||
match state {
|
||||
State::Code => match c {
|
||||
_ if plsql && !has_code && c.is_alphabetic() => {
|
||||
@@ -164,15 +228,37 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
// Re-read this character as code (it starts BEGIN / DECLARE).
|
||||
continue;
|
||||
}
|
||||
';' if depth == 0 && !declarations && !package => {
|
||||
push(&mut out, start, if block { i + 1 } else { i }, has_code);
|
||||
start = i + 1;
|
||||
has_code = false;
|
||||
block = false;
|
||||
script = false;
|
||||
defines = false;
|
||||
_ if routines && !has_code && c.is_alphabetic() => {
|
||||
body = body_of(&chars, i, driver);
|
||||
has_code = true;
|
||||
// Re-read this character as code.
|
||||
continue;
|
||||
}
|
||||
';' => {
|
||||
let ends = delimiter == ";"
|
||||
&& depth == 0
|
||||
&& !declarations
|
||||
&& !package
|
||||
&& match body {
|
||||
Body::None | Body::Blocks => true,
|
||||
Body::Trigger => last_semi.is_some_and(|semi| only_end(&chars, semi + 1, i)),
|
||||
Body::Batch => false,
|
||||
};
|
||||
if ends {
|
||||
push(&mut out, start, if block { i + 1 } else { i }, has_code);
|
||||
next_statement!(i + 1);
|
||||
} else {
|
||||
has_code = true;
|
||||
last_semi = Some(i);
|
||||
}
|
||||
}
|
||||
_ if body == Body::Blocks
|
||||
&& parens == 0
|
||||
&& ["BEGIN", "CASE", "END"].iter().any(|w| keyword_at(&chars, i, w)) =>
|
||||
{
|
||||
i = block_keyword(&chars, i, driver, &mut depth);
|
||||
has_code = true;
|
||||
}
|
||||
';' => has_code = true,
|
||||
// Words are read whole: the `E` of `E'…'` starts one, and a `$` inside one quotes nothing.
|
||||
_ if postgres && (c.is_alphabetic() || c == '_') => {
|
||||
has_code = true;
|
||||
@@ -208,6 +294,12 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
i = chars.partition_point(|&(offset, _)| offset < end);
|
||||
continue;
|
||||
}
|
||||
// MySQL runs the code of `/*! … */` and MariaDB that of `/*M! … */`: mysqldump's
|
||||
// SETs and triggers are statements made of them alone.
|
||||
let after = |n: usize| chars.get(i + n).map(|&(_, c)| c);
|
||||
if mysql && (after(2) == Some('!') || (after(2) == Some('M') && after(3) == Some('!'))) {
|
||||
has_code = true;
|
||||
}
|
||||
state = State::BlockComment;
|
||||
i += 1;
|
||||
}
|
||||
@@ -225,9 +317,7 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
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;
|
||||
}
|
||||
@@ -313,6 +403,14 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
i = closing.map_or(i + 3, |w| after + w.len()) - 1;
|
||||
has_code = true;
|
||||
}
|
||||
'(' => {
|
||||
parens += 1;
|
||||
has_code = true;
|
||||
}
|
||||
')' => {
|
||||
parens = parens.saturating_sub(1);
|
||||
has_code = true;
|
||||
}
|
||||
c if !c.is_whitespace() => has_code = true,
|
||||
_ => {}
|
||||
},
|
||||
@@ -353,7 +451,9 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -367,7 +467,129 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
i += 1;
|
||||
}
|
||||
push(&mut out, start, chars.len(), has_code);
|
||||
out
|
||||
(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)]
|
||||
@@ -381,10 +603,10 @@ enum Unit {
|
||||
Package,
|
||||
}
|
||||
|
||||
/// What kind of PL/SQL unit, if any, a statement starting at `i` is.
|
||||
fn plsql_unit(chars: &[(usize, char)], mut i: usize) -> Unit {
|
||||
/// The first `n` words from `i`, upper-cased, as long as only whitespace separates them.
|
||||
fn leading_words(chars: &[(usize, char)], mut i: usize, n: usize) -> Vec<String> {
|
||||
let mut words: Vec<String> = Vec::new();
|
||||
while words.len() < 6 {
|
||||
while words.len() < n {
|
||||
let word: String = chars[i.min(chars.len())..]
|
||||
.iter()
|
||||
.map(|&(_, c)| c)
|
||||
@@ -396,6 +618,12 @@ fn plsql_unit(chars: &[(usize, char)], mut i: usize) -> Unit {
|
||||
i = skip_ws(chars, i + word.chars().count());
|
||||
words.push(word.to_ascii_uppercase());
|
||||
}
|
||||
words
|
||||
}
|
||||
|
||||
/// What kind of PL/SQL unit, if any, a statement starting at `i` is.
|
||||
fn plsql_unit(chars: &[(usize, char)], i: usize) -> Unit {
|
||||
let words = leading_words(chars, i, 6);
|
||||
let w = |n: usize| words.get(n).map_or("", String::as_str);
|
||||
match w(0) {
|
||||
"DECLARE" | "BEGIN" => return Unit::Block,
|
||||
@@ -413,6 +641,168 @@ fn plsql_unit(chars: &[(usize, char)], mut i: usize) -> Unit {
|
||||
}
|
||||
}
|
||||
|
||||
/// The body a statement starting at `i` may hold, by the rule of the dialect's own client.
|
||||
fn body_of(chars: &[(usize, char)], i: usize, driver: DbDriver) -> Body {
|
||||
let words = leading_words(chars, i, 4);
|
||||
let w = |n: usize| words.get(n).map_or("", String::as_str);
|
||||
match driver {
|
||||
// sqlite3: CREATE [TEMP | TEMPORARY] TRIGGER.
|
||||
DbDriver::Sqlite => {
|
||||
let n = if matches!(w(1), "TEMP" | "TEMPORARY") { 2 } else { 1 };
|
||||
if w(0) == "CREATE" && w(n) == "TRIGGER" { Body::Trigger } else { Body::None }
|
||||
}
|
||||
// psql: CREATE [OR REPLACE] {FUNCTION | PROCEDURE}.
|
||||
DbDriver::Postgres => {
|
||||
let n = if (w(1), w(2)) == ("OR", "REPLACE") { 3 } else { 1 };
|
||||
if w(0) == "CREATE" && matches!(w(n), "FUNCTION" | "PROCEDURE") { Body::Blocks } else { Body::None }
|
||||
}
|
||||
DbDriver::Mysql if mysql_routine(chars, i) => Body::Blocks,
|
||||
// A routine must be alone in its batch, so SQL Server reads the rest of it as the body.
|
||||
DbDriver::SqlServer => {
|
||||
let n = match (w(0), w(1), w(2)) {
|
||||
("CREATE", "OR", "ALTER") => 3,
|
||||
("CREATE" | "ALTER", ..) => 1,
|
||||
_ => return Body::Blocks,
|
||||
};
|
||||
if matches!(w(n), "PROC" | "PROCEDURE" | "FUNCTION" | "TRIGGER") { Body::Batch } else { Body::Blocks }
|
||||
}
|
||||
_ => Body::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a MySQL statement at `i` creates a stored program:
|
||||
/// `CREATE [OR REPLACE] [DEFINER = user] [AGGREGATE] {PROCEDURE | FUNCTION | TRIGGER | EVENT}`.
|
||||
fn mysql_routine(chars: &[(usize, char)], mut i: usize) -> bool {
|
||||
let word = |i: &mut usize| {
|
||||
let word = leading_words(chars, *i, 1).pop().unwrap_or_default();
|
||||
*i = skip_ws(chars, *i + word.chars().count());
|
||||
word
|
||||
};
|
||||
if word(&mut i) != "CREATE" {
|
||||
return false;
|
||||
}
|
||||
let mut next = word(&mut i);
|
||||
if next == "OR" && word(&mut i) == "REPLACE" {
|
||||
next = word(&mut i);
|
||||
}
|
||||
if next == "DEFINER" {
|
||||
// `= 'name'@'host'`, `name@host`, `CURRENT_USER()`…: up to a blank outside quotes.
|
||||
if chars.get(i).is_some_and(|&(_, c)| c == '=') {
|
||||
i = skip_ws(chars, i + 1);
|
||||
}
|
||||
while let Some(&(_, c)) = chars.get(i)
|
||||
&& !c.is_whitespace()
|
||||
{
|
||||
i += 1;
|
||||
if matches!(c, '\'' | '"' | '`') {
|
||||
i = chars[i..].iter().position(|&(_, q)| q == c).map_or(chars.len(), |n| i + n + 1);
|
||||
}
|
||||
}
|
||||
i = skip_ws(chars, i);
|
||||
next = word(&mut i);
|
||||
}
|
||||
if next == "AGGREGATE" {
|
||||
next = word(&mut i);
|
||||
}
|
||||
matches!(next.as_str(), "PROCEDURE" | "FUNCTION" | "TRIGGER" | "EVENT")
|
||||
}
|
||||
|
||||
/// [`word_at`] for a keyword, which a MySQL / T-SQL `@variable` or a qualified `t.end` is not.
|
||||
fn keyword_at(chars: &[(usize, char)], i: usize, word: &str) -> bool {
|
||||
word_at(chars, i, word) && chars[..i].last().is_none_or(|&(_, c)| c != '@' && c != '.')
|
||||
}
|
||||
|
||||
/// Counts the BEGIN, CASE or END at `i` into the block `depth` of a body. Returns the index of
|
||||
/// its last character, or of the word after END that belongs to it.
|
||||
fn block_keyword(chars: &[(usize, char)], i: usize, driver: DbDriver, depth: &mut usize) -> usize {
|
||||
if word_at(chars, i, "BEGIN") {
|
||||
// T-SQL's BEGIN TRAN, BEGIN DIALOG… are statements.
|
||||
let after = skip_ws(chars, i + 5);
|
||||
let statement = driver == DbDriver::SqlServer
|
||||
&& ["TRAN", "TRANSACTION", "DISTRIBUTED", "DIALOG", "CONVERSATION"]
|
||||
.iter()
|
||||
.any(|w| word_at(chars, after, w));
|
||||
if !statement {
|
||||
*depth += 1;
|
||||
}
|
||||
return i + 4;
|
||||
}
|
||||
if word_at(chars, i, "CASE") {
|
||||
// Its END closes it, not the block; outside a block it holds no `;` (psql).
|
||||
if *depth > 0 {
|
||||
*depth += 1;
|
||||
}
|
||||
return i + 3;
|
||||
}
|
||||
// MySQL's END IF / LOOP / REPEAT / WHILE close statements that opened no block, and T-SQL's
|
||||
// END CONVERSATION is a statement; END CASE / TRY / CATCH close what they name.
|
||||
let (closing, neutral): (&[&str], &[&str]) = match driver {
|
||||
DbDriver::Mysql => (&["CASE"], &["IF", "LOOP", "REPEAT", "WHILE"]),
|
||||
DbDriver::SqlServer => (&["TRY", "CATCH"], &["CONVERSATION"]),
|
||||
_ => (&[], &[]),
|
||||
};
|
||||
let after = skip_ws(chars, i + 3);
|
||||
let named = closing.iter().chain(neutral).find(|w| word_at(chars, after, w));
|
||||
if named.is_none_or(|w| !neutral.contains(w)) {
|
||||
*depth = depth.saturating_sub(1);
|
||||
}
|
||||
named.map_or(i + 2, |w| after + w.len() - 1)
|
||||
}
|
||||
|
||||
/// The end (`\n` or the end of the text) of a SQL Server `GO` line starting at `i`. As in sqlcmd, a
|
||||
/// `--` comment may follow GO and `GO;` is SQL. A repeat count (`GO 2`) is not run here: the line
|
||||
/// is left to the server.
|
||||
fn go_line(chars: &[(usize, char)], i: usize) -> Option<usize> {
|
||||
if !word_at(chars, i, "GO") {
|
||||
return None;
|
||||
}
|
||||
let end = chars[i..].iter().position(|&(_, c)| c == '\n').map_or(chars.len(), |n| i + n);
|
||||
let rest: String = chars[i + 2..end].iter().map(|&(_, c)| c).collect();
|
||||
let rest = rest.trim_start();
|
||||
(rest.is_empty() || rest.starts_with("--")).then_some(end)
|
||||
}
|
||||
|
||||
/// The mysql client's `DELIMITER x` at `i`: the new delimiter and the end of its line, which the
|
||||
/// command takes whole. An argument the client refuses (none, a backslash) leaves it SQL.
|
||||
fn delimiter_line(chars: &[(usize, char)], i: usize) -> Option<(String, usize)> {
|
||||
if !word_at(chars, i, "DELIMITER") {
|
||||
return None;
|
||||
}
|
||||
let end = chars[i..].iter().position(|&(_, c)| c == '\n').map_or(chars.len(), |n| i + n);
|
||||
let line: String = chars[i + "DELIMITER".len()..end].iter().map(|&(_, c)| c).collect();
|
||||
let argument = line.strip_prefix([' ', '\t'])?.trim_start_matches([' ', '\t']);
|
||||
let delimiter = match argument.chars().next()? {
|
||||
quote @ ('\'' | '"' | '`') => argument[1..].split(quote).next().unwrap_or_default(),
|
||||
_ => argument.split([' ', '\t', '\r']).next().unwrap_or_default(),
|
||||
};
|
||||
(!delimiter.is_empty() && !delimiter.contains('\\')).then(|| (delimiter.to_owned(), end))
|
||||
}
|
||||
|
||||
/// Whether only END, blanks and comments lie in `from..to`: the `;` END `;` ending a SQLite trigger.
|
||||
fn only_end(chars: &[(usize, char)], from: usize, to: usize) -> bool {
|
||||
let at = past_blanks(chars, from, to);
|
||||
word_at(chars, at, "END") && past_blanks(chars, at + 3, to) == to
|
||||
}
|
||||
|
||||
/// The first index of `i..to` that is neither whitespace nor in a comment.
|
||||
fn past_blanks(chars: &[(usize, char)], mut i: usize, to: usize) -> usize {
|
||||
let starts = |i: usize, s: &str| chars[i..to].iter().map(|&(_, c)| c).take(2).eq(s.chars());
|
||||
while i < to {
|
||||
if chars[i].1.is_whitespace() {
|
||||
i += 1;
|
||||
} else if starts(i, "--") {
|
||||
i = chars[i..to].iter().position(|&(_, c)| c == '\n').map_or(to, |n| i + n);
|
||||
} else if starts(i, "/*") {
|
||||
i = (i + 2..to.saturating_sub(1))
|
||||
.find(|&j| chars[j].1 == '*' && chars[j + 1].1 == '/')
|
||||
.map_or(to, |j| j + 2);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
/// Whether the characters at `i` are the keyword `word` (identifier bounds respected).
|
||||
fn word_at(chars: &[(usize, char)], i: usize, word: &str) -> bool {
|
||||
let (before, after) = (chars[..i].last().map(|&(_, c)| c), chars.get(i).map(|&(_, c)| c));
|
||||
@@ -477,7 +867,17 @@ pub fn statement_at(text: &str, offset: u32, driver: DbDriver) -> Option<SqlStat
|
||||
/// selected text itself, split.
|
||||
pub fn statements_in(text: &str, from: u32, to: u32, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
let selected = utf16_slice(text, from, to);
|
||||
split(selected, driver).into_iter().map(|s| SqlStatement { from: s.from + from, to: s.to + from, ..s }).collect()
|
||||
// A DELIMITER above the selection still holds in it.
|
||||
let delimiter = if driver == DbDriver::Mysql {
|
||||
split_with(utf16_slice(text, 0, from), driver, ";".into()).1
|
||||
} else {
|
||||
";".into()
|
||||
};
|
||||
split_with(selected, driver, delimiter)
|
||||
.0
|
||||
.into_iter()
|
||||
.map(|s| SqlStatement { from: s.from + from, to: s.to + from, ..s })
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn utf16_slice(text: &str, from: u32, to: u32) -> &str {
|
||||
@@ -500,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";
|
||||
@@ -575,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``;`"#;
|
||||
@@ -765,4 +1252,188 @@ mod tests {
|
||||
vec!["select case when a then 1 end, b from t", "select 2"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlite_triggers_end_at_end_semicolon_like_sqlite3() {
|
||||
let trigger = "CREATE TRIGGER a_ins AFTER INSERT ON a BEGIN\n INSERT INTO log VALUES ('inserted ' || NEW.id);\n \
|
||||
UPDATE a SET n = n + 1 WHERE id = NEW.id;\nEND";
|
||||
assert_eq!(
|
||||
texts(&format!("CREATE TABLE log (msg TEXT);\n{trigger};\nINSERT INTO a VALUES (1, 0);"), DbDriver::Sqlite),
|
||||
vec!["CREATE TABLE log (msg TEXT)", trigger, "INSERT INTO a VALUES (1, 0)"]
|
||||
);
|
||||
// Only `;` END `;` ends one, whatever CASE … END and comments it holds.
|
||||
let temp = "create temp trigger t after insert on a begin\n select case when new.id > 0 then 1 end;\n \
|
||||
select 2; -- ; END ;\n /* END; */ select 3;\nend\n";
|
||||
assert_eq!(texts(&format!("{temp};select 4"), DbDriver::Sqlite), vec![temp.trim_end(), "select 4"]);
|
||||
// Execute with the caret in the body runs the whole trigger.
|
||||
let console = "CREATE TRIGGER users_gone AFTER DELETE ON users BEGIN\n INSERT INTO audit VALUES ('gone');\n \
|
||||
DELETE FROM sessions WHERE expires < datetime('now');\nEND;";
|
||||
let caret = console.find("FROM sessions").unwrap() as u32;
|
||||
let whole = console.trim_end_matches(';');
|
||||
assert_eq!(statement_at(console, caret, DbDriver::Sqlite).map(|s| s.text).as_deref(), Some(whole));
|
||||
// A transaction's BEGIN … END is no body.
|
||||
assert_eq!(texts("BEGIN; DELETE FROM a; END;", DbDriver::Sqlite), vec!["BEGIN", "DELETE FROM a", "END"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_begin_atomic_bodies_like_psql() {
|
||||
let procedure = "CREATE PROCEDURE insert_data(a integer, b integer)\nLANGUAGE SQL\nBEGIN ATOMIC\n \
|
||||
INSERT INTO tbl VALUES (a);\n INSERT INTO tbl VALUES (b);\nEND";
|
||||
let function = "create or replace function classify(x integer) returns text language sql\nbegin atomic\n \
|
||||
select case when x > 0 then 'pos' else 'neg' end;\nend";
|
||||
assert_eq!(
|
||||
texts(
|
||||
&format!("CREATE TABLE tbl (n integer);\n{procedure};\n{function};\nCALL insert_data(1, 2);"),
|
||||
DbDriver::Postgres
|
||||
),
|
||||
vec!["CREATE TABLE tbl (n integer)", procedure, function, "CALL insert_data(1, 2)"]
|
||||
);
|
||||
// Words in parentheses count for nothing, and other statements have no body.
|
||||
let named = "CREATE FUNCTION f(begin int) RETURNS int LANGUAGE sql RETURN 1";
|
||||
assert_eq!(texts(&format!("{named}; SELECT 2"), DbDriver::Postgres), vec![named, "SELECT 2"]);
|
||||
assert_eq!(
|
||||
texts("BEGIN; CALL insert_data(1, 2); END; SELECT case when true then 1 end", DbDriver::Postgres),
|
||||
vec!["BEGIN", "CALL insert_data(1, 2)", "END", "SELECT case when true then 1 end"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_delimiter_lines_set_the_terminator_like_the_mysql_client() {
|
||||
let procedure = "CREATE PROCEDURE p()\nBEGIN\n SELECT 1;\n SELECT 2;\nEND";
|
||||
assert_eq!(
|
||||
texts(&format!("DELIMITER //\n{procedure} //\nDELIMITER ;\nCALL p();"), DbDriver::Mysql),
|
||||
vec![procedure, "CALL p()"]
|
||||
);
|
||||
// mysqldump's `;;`, a quoted delimiter, a lower-case command and what follows the argument.
|
||||
for (command, delimiter) in
|
||||
[("DELIMITER ;;", ";;"), ("delimiter '$$'", "$$"), (" DELIMITER $$ -- the rest is ignored", "$$")]
|
||||
{
|
||||
assert_eq!(
|
||||
texts(&format!("{command}\n{procedure}{delimiter}\nSELECT 3{delimiter}"), DbDriver::Mysql),
|
||||
vec![procedure, "SELECT 3"],
|
||||
"{command}"
|
||||
);
|
||||
}
|
||||
// Only at the start of a statement; an empty or backslashed argument is no command.
|
||||
for sql in ["SELECT 1\nDELIMITER //\n", "DELIMITER\n", "DELIMITER \\\\\n"] {
|
||||
assert_eq!(texts(&format!("{sql}SELECT 2"), DbDriver::Mysql), vec![format!("{sql}SELECT 2")]);
|
||||
}
|
||||
// A selection between the DELIMITER lines runs with the delimiter set above it.
|
||||
let script = format!("DELIMITER //\n{procedure} //\nSELECT 3 //\nDELIMITER ;");
|
||||
let from = script.find("CREATE").unwrap() as u32;
|
||||
let to = script.find("\nDELIMITER ;").unwrap() as u32;
|
||||
let selected: Vec<_> = statements_in(&script, from, to, DbDriver::Mysql).into_iter().map(|s| s.text).collect();
|
||||
assert_eq!(selected, vec![procedure, "SELECT 3"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_routine_bodies_keep_their_statements() {
|
||||
let trigger =
|
||||
"CREATE TRIGGER t_bi BEFORE INSERT ON t FOR EACH ROW BEGIN\n SET NEW.a = 1;\n SET NEW.b = 2;\nEND";
|
||||
let procedure = "CREATE DEFINER=`root`@`%` PROCEDURE p(IN n INT)\nBEGIN\n DECLARE i INT DEFAULT 0;\n \
|
||||
lbl: LOOP\n SET i = i + 1;\n IF i >= n THEN LEAVE lbl; END IF;\n END LOOP lbl;\n \
|
||||
CASE WHEN i > 1 THEN SELECT 'many'; ELSE SELECT 'one'; END CASE;\n \
|
||||
SELECT CASE WHEN i = 3 THEN 'three' END AS c;\nEND";
|
||||
let event = "CREATE EVENT e ON SCHEDULE EVERY 1 HOUR ENDS NOW() + INTERVAL 1 DAY DO BEGIN DELETE FROM t; END";
|
||||
let function = "CREATE DEFINER = CURRENT_USER() FUNCTION f() RETURNS INT DETERMINISTIC BEGIN\n \
|
||||
SET @begin = 1;\n RETURN (SELECT t.end FROM t LIMIT 1);\nEND";
|
||||
assert_eq!(
|
||||
texts(
|
||||
&format!("{trigger};\n{procedure};\n{event};\n{function};\nINSERT INTO t (id) VALUES (1);"),
|
||||
DbDriver::Mysql
|
||||
),
|
||||
vec![trigger, procedure, event, function, "INSERT INTO t (id) VALUES (1)"]
|
||||
);
|
||||
// Outside a routine BEGIN starts a transaction.
|
||||
assert_eq!(texts("BEGIN; DELETE FROM t; COMMIT", DbDriver::Mysql), vec!["BEGIN", "DELETE FROM t", "COMMIT"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_executable_comments_are_statements() {
|
||||
// Lines of a mysqldump 8.4 dump: its SETs and triggers are code the server runs.
|
||||
let trigger = "/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `orders_ai` AFTER INSERT \
|
||||
ON `orders` FOR EACH ROW BEGIN\n UPDATE customers SET orders_count = orders_count + 1 WHERE id = \
|
||||
NEW.customer_id;\nEND */";
|
||||
let procedure = "CREATE DEFINER=`root`@`localhost` PROCEDURE `add_order`(IN p_id INT)\nBEGIN\n \
|
||||
INSERT INTO orders (id) VALUES (p_id);\nEND";
|
||||
let dump = format!(
|
||||
"/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n\
|
||||
INSERT INTO `orders` VALUES (10,1,'first; with a semicolon');\n\
|
||||
/*!50003 SET character_set_client = latin1 */ ;\nDELIMITER ;;\n{trigger};;\nDELIMITER ;\n\
|
||||
/*!50003 DROP PROCEDURE IF EXISTS `add_order` */;\nDELIMITER ;;\n{procedure} ;;\nDELIMITER ;\n\
|
||||
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;\n/*M!100100 SET @x = 1 */;\n\
|
||||
/* a note */;\n-- Dump completed\n"
|
||||
);
|
||||
assert_eq!(
|
||||
texts(&dump, DbDriver::Mysql),
|
||||
vec![
|
||||
"/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */",
|
||||
"INSERT INTO `orders` VALUES (10,1,'first; with a semicolon')",
|
||||
"/*!50003 SET character_set_client = latin1 */",
|
||||
trigger,
|
||||
"/*!50003 DROP PROCEDURE IF EXISTS `add_order` */",
|
||||
procedure,
|
||||
"/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */",
|
||||
"/*M!100100 SET @x = 1 */",
|
||||
]
|
||||
);
|
||||
// The `;` inside one stays in it, also without DELIMITER.
|
||||
let inline = "/*!50003 TRIGGER t BEFORE INSERT ON a FOR EACH ROW BEGIN SET NEW.n = 1; END */";
|
||||
assert_eq!(texts(&format!("{inline};\nSELECT 2"), DbDriver::Mysql), vec![inline, "SELECT 2"]);
|
||||
// Elsewhere they are comments.
|
||||
for driver in [DbDriver::Postgres, DbDriver::Sqlite, DbDriver::SqlServer] {
|
||||
assert_eq!(texts("/*!40101 SET NAMES utf8 */;\nSELECT 2", driver), vec!["SELECT 2"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sql_server_go_lines_end_batches_like_sqlcmd() {
|
||||
let procedure = "CREATE PROCEDURE p AS\nBEGIN\n SET NOCOUNT ON;\n SELECT a FROM t;\nEND";
|
||||
assert_eq!(
|
||||
texts(&format!("CREATE TABLE t (a int)\nGO\n{procedure}\n go -- done\nEXEC p\nGo"), DbDriver::SqlServer),
|
||||
vec!["CREATE TABLE t (a int)", procedure, "EXEC p"]
|
||||
);
|
||||
// GO in a string or comment, `GOTO`, `GO 2` (a repeat count) and `GO;` are left to the server.
|
||||
for sql in ["SELECT 'a\nGO\n'", "/* a\nGO\n*/ SELECT 1", "SELECT 1\nGOTO x", "SELECT 1\nGO 2"] {
|
||||
assert_eq!(texts(&format!("{sql}\nSELECT 2"), DbDriver::SqlServer), vec![format!("{sql}\nSELECT 2")]);
|
||||
}
|
||||
assert_eq!(texts("SELECT 1\nGO;\nSELECT 2", DbDriver::SqlServer), vec!["SELECT 1\nGO", "SELECT 2"]);
|
||||
let script = format!("SELECT 0\nGO\n{procedure}\nGO\nSELECT 3");
|
||||
let caret = script.find("SELECT a").unwrap() as u32;
|
||||
assert_eq!(statement_at(&script, caret, DbDriver::SqlServer).map(|s| s.text).as_deref(), Some(procedure));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sql_server_routines_run_to_the_end_of_their_batch() {
|
||||
for routine in [
|
||||
"CREATE PROCEDURE p AS SELECT 1 AS one; SELECT 2 AS two;",
|
||||
"create or alter function f() returns int as begin declare @n int = 1; return @n; end;",
|
||||
"ALTER PROC p AS SET NOCOUNT ON; SELECT 1",
|
||||
"CREATE TRIGGER tr ON t AFTER INSERT AS INSERT INTO log VALUES (1); INSERT INTO log VALUES (2)",
|
||||
] {
|
||||
assert_eq!(texts(routine, DbDriver::SqlServer), vec![routine]);
|
||||
assert_eq!(texts(&format!("{routine}\nGO\nEXEC p"), DbDriver::SqlServer), vec![routine, "EXEC p"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sql_server_blocks_keep_their_statements() {
|
||||
let block =
|
||||
"IF OBJECT_ID('t') IS NOT NULL\nBEGIN\n INSERT INTO t VALUES (2);\n INSERT INTO t VALUES (3);\nEND";
|
||||
let tried = "BEGIN TRY\n SELECT 1/0 AS boom;\nEND TRY\nBEGIN CATCH\n \
|
||||
SELECT CASE WHEN ERROR_NUMBER() > 0 THEN 1 END;\n DECLARE @begin int = 1;\nEND CATCH";
|
||||
assert_eq!(
|
||||
texts(&format!("{block};\n{tried};\nBEGIN TRAN;\nINSERT INTO t VALUES (4);\nCOMMIT;"), DbDriver::SqlServer),
|
||||
vec![block, tried, "BEGIN TRAN", "INSERT INTO t VALUES (4)", "COMMIT"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_commands_and_bodies_of_other_dialects_are_sql() {
|
||||
for driver in [DbDriver::Postgres, DbDriver::Sqlite, DbDriver::Clickhouse, DbDriver::Jdbc] {
|
||||
assert_eq!(texts("SELECT 1\nGO\nSELECT 2", driver), vec!["SELECT 1\nGO\nSELECT 2"]);
|
||||
assert_eq!(texts("DELIMITER //\nSELECT 1 //", driver), vec!["DELIMITER //\nSELECT 1 //"]);
|
||||
assert_eq!(texts("CREATE PROCEDURE p AS SELECT 1; SELECT 2", driver).len(), 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
+112
-26
@@ -22,10 +22,6 @@ pub fn quote_literal(driver: DbDriver, value: &str) -> String {
|
||||
format!("'{s}'")
|
||||
}
|
||||
|
||||
fn literal_or_null(driver: DbDriver, v: Option<&str>) -> String {
|
||||
v.map_or_else(|| "NULL".to_owned(), |v| quote_literal(driver, v))
|
||||
}
|
||||
|
||||
pub fn qualified(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
if schema.is_empty() {
|
||||
quote_ident(driver, table)
|
||||
@@ -626,19 +622,56 @@ pub enum DbRowEdit {
|
||||
Delete { key: Vec<CellValue> },
|
||||
}
|
||||
|
||||
fn where_key(driver: DbDriver, key: &[CellValue]) -> String {
|
||||
/// Whether a column of type `data_type` (as [`columns`] lists it) holds bytes that the grid
|
||||
/// shows as `0x…` hex. PostgreSQL shows `bytea` as its own `\x…` input text.
|
||||
pub fn binary_column(driver: DbDriver, data_type: &str) -> bool {
|
||||
let t = data_type.to_ascii_lowercase();
|
||||
match driver {
|
||||
DbDriver::Sqlite => t.contains("blob"),
|
||||
DbDriver::Mysql => t.contains("blob") || t.contains("binary"),
|
||||
DbDriver::SqlServer => matches!(t.as_str(), "binary" | "varbinary" | "image" | "timestamp" | "rowversion"),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The literal of `value` for a column: the bytes of a `0x…` hex value in a binary column, else text.
|
||||
fn column_literal(driver: DbDriver, column: &str, value: &str, binary: &[String]) -> String {
|
||||
let hex = value.strip_prefix("0x").or_else(|| value.strip_prefix("0X"));
|
||||
match hex {
|
||||
Some(hex)
|
||||
if hex.len() % 2 == 0
|
||||
&& hex.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
&& binary.iter().any(|b| b.eq_ignore_ascii_case(column)) =>
|
||||
{
|
||||
if driver == DbDriver::SqlServer {
|
||||
format!("0x{hex}")
|
||||
} else {
|
||||
format!("X'{hex}'")
|
||||
}
|
||||
}
|
||||
_ => quote_literal(driver, value),
|
||||
}
|
||||
}
|
||||
|
||||
fn where_key(driver: DbDriver, key: &[CellValue], binary: &[String]) -> String {
|
||||
key.iter()
|
||||
.map(|c| match &c.value {
|
||||
Some(v) => format!("{} = {}", quote_ident(driver, &c.column), quote_literal(driver, v)),
|
||||
Some(v) => format!("{} = {}", quote_ident(driver, &c.column), column_literal(driver, &c.column, v, binary)),
|
||||
None => format!("{} IS NULL", quote_ident(driver, &c.column)),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" AND ")
|
||||
}
|
||||
|
||||
/// The DML statement for `edit`. Values are written as quoted literals, which
|
||||
/// every supported database coerces to the column type.
|
||||
pub fn edit_statement(driver: DbDriver, schema: &str, table: &str, edit: &DbRowEdit) -> Result<String, String> {
|
||||
/// The DML statement for `edit`. Values are written as quoted literals, which every supported
|
||||
/// database coerces to the column type, except the `0x…` hex of the `binary` columns: their bytes.
|
||||
pub fn edit_statement(
|
||||
driver: DbDriver,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
edit: &DbRowEdit,
|
||||
binary: &[String],
|
||||
) -> Result<String, String> {
|
||||
if driver == DbDriver::Jdbc {
|
||||
return Err("Custom JDBC table editing is unsupported".into());
|
||||
}
|
||||
@@ -646,6 +679,9 @@ pub fn edit_statement(driver: DbDriver, schema: &str, table: &str, edit: &DbRowE
|
||||
return Err("ClickHouse table editing is unsupported: primary keys do not uniquely identify rows and edits require transactions".into());
|
||||
}
|
||||
let target = qualified(driver, schema, table);
|
||||
let literal = |c: &CellValue| {
|
||||
c.value.as_deref().map_or_else(|| "NULL".to_owned(), |v| column_literal(driver, &c.column, v, binary))
|
||||
};
|
||||
match edit {
|
||||
DbRowEdit::Update { key, values } => {
|
||||
if key.is_empty() {
|
||||
@@ -654,13 +690,9 @@ pub fn edit_statement(driver: DbDriver, schema: &str, table: &str, edit: &DbRowE
|
||||
if values.is_empty() {
|
||||
return Err("nothing to update".into());
|
||||
}
|
||||
let set: Vec<String> = values
|
||||
.iter()
|
||||
.map(|c| {
|
||||
format!("{} = {}", quote_ident(driver, &c.column), literal_or_null(driver, c.value.as_deref()))
|
||||
})
|
||||
.collect();
|
||||
Ok(format!("UPDATE {target} SET {} WHERE {}", set.join(", "), where_key(driver, key)))
|
||||
let set: Vec<String> =
|
||||
values.iter().map(|c| format!("{} = {}", quote_ident(driver, &c.column), literal(c))).collect();
|
||||
Ok(format!("UPDATE {target} SET {} WHERE {}", set.join(", "), where_key(driver, key, binary)))
|
||||
}
|
||||
DbRowEdit::Insert { values } => {
|
||||
if values.is_empty() {
|
||||
@@ -675,14 +707,14 @@ pub fn edit_statement(driver: DbDriver, schema: &str, table: &str, edit: &DbRowE
|
||||
});
|
||||
}
|
||||
let cols: Vec<String> = values.iter().map(|c| quote_ident(driver, &c.column)).collect();
|
||||
let vals: Vec<String> = values.iter().map(|c| literal_or_null(driver, c.value.as_deref())).collect();
|
||||
let vals: Vec<String> = values.iter().map(literal).collect();
|
||||
Ok(format!("INSERT INTO {target} ({}) VALUES ({})", cols.join(", "), vals.join(", ")))
|
||||
}
|
||||
DbRowEdit::Delete { key } => {
|
||||
if key.is_empty() {
|
||||
return Err("rows can only be deleted in tables with a primary key".into());
|
||||
}
|
||||
Ok(format!("DELETE FROM {target} WHERE {}", where_key(driver, key)))
|
||||
Ok(format!("DELETE FROM {target} WHERE {}", where_key(driver, key, binary)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1288,7 +1320,7 @@ mod tests {
|
||||
DbRowEdit::Insert { values: vec![cv("name", Some("new"))] },
|
||||
DbRowEdit::Insert { values: vec![] },
|
||||
] {
|
||||
let error = edit_statement(DbDriver::Clickhouse, "default", "events", &edit).unwrap_err();
|
||||
let error = edit_statement(DbDriver::Clickhouse, "default", "events", &edit, &[]).unwrap_err();
|
||||
assert!(error.contains("primary keys do not uniquely identify rows"));
|
||||
}
|
||||
}
|
||||
@@ -1315,21 +1347,74 @@ mod tests {
|
||||
DbDriver::Sqlite,
|
||||
"main",
|
||||
"t",
|
||||
&DbRowEdit::Update { key: key.clone(), values: vec![cv("name", Some("O'Brien")), cv("note", None)] }
|
||||
&DbRowEdit::Update { key: key.clone(), values: vec![cv("name", Some("O'Brien")), cv("note", None)] },
|
||||
&[]
|
||||
)
|
||||
.unwrap(),
|
||||
"UPDATE \"main\".\"t\" SET \"name\" = 'O''Brien', \"note\" = NULL WHERE \"id\" = '1'"
|
||||
);
|
||||
assert_eq!(
|
||||
edit_statement(DbDriver::Mysql, "db", "t", &DbRowEdit::Insert { values: vec![cv("a", Some("x"))] })
|
||||
edit_statement(DbDriver::Mysql, "db", "t", &DbRowEdit::Insert { values: vec![cv("a", Some("x"))] }, &[])
|
||||
.unwrap(),
|
||||
"INSERT INTO `db`.`t` (`a`) VALUES ('x')"
|
||||
);
|
||||
assert_eq!(
|
||||
edit_statement(DbDriver::Postgres, "s", "t", &DbRowEdit::Delete { key: vec![cv("k", None)] }).unwrap(),
|
||||
edit_statement(DbDriver::Postgres, "s", "t", &DbRowEdit::Delete { key: vec![cv("k", None)] }, &[]).unwrap(),
|
||||
"DELETE FROM \"s\".\"t\" WHERE \"k\" IS NULL"
|
||||
);
|
||||
assert!(edit_statement(DbDriver::Postgres, "s", "t", &DbRowEdit::Delete { key: vec![] }).is_err());
|
||||
assert!(edit_statement(DbDriver::Postgres, "s", "t", &DbRowEdit::Delete { key: vec![] }, &[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_write_the_bytes_of_the_hex_a_binary_cell_shows() {
|
||||
let binary = ["id".to_owned(), "data".to_owned()];
|
||||
let update = DbRowEdit::Update {
|
||||
key: vec![cv("id", Some("0x0102"))],
|
||||
values: vec![cv("DATA", Some("0xcaff")), cv("name", Some("0xCAFF"))],
|
||||
};
|
||||
assert_eq!(
|
||||
edit_statement(DbDriver::Sqlite, "main", "files", &update, &binary).unwrap(),
|
||||
"UPDATE \"main\".\"files\" SET \"DATA\" = X'caff', \"name\" = '0xCAFF' WHERE \"id\" = X'0102'"
|
||||
);
|
||||
assert_eq!(
|
||||
edit_statement(DbDriver::Mysql, "db", "files", &update, &binary).unwrap(),
|
||||
"UPDATE `db`.`files` SET `DATA` = X'caff', `name` = '0xCAFF' WHERE `id` = X'0102'"
|
||||
);
|
||||
assert_eq!(
|
||||
edit_statement(DbDriver::SqlServer, "dbo", "files", &update, &binary).unwrap(),
|
||||
"UPDATE [dbo].[files] SET [DATA] = 0xcaff, [name] = '0xCAFF' WHERE [id] = 0x0102"
|
||||
);
|
||||
// Empty bytes, NULL, and text that is not whole bytes of hex.
|
||||
let insert = DbRowEdit::Insert {
|
||||
values: vec![cv("id", Some("0x")), cv("data", None), cv("data", Some("0xCAF")), cv("data", Some("plain"))],
|
||||
};
|
||||
assert_eq!(
|
||||
edit_statement(DbDriver::SqlServer, "dbo", "files", &insert, &binary).unwrap(),
|
||||
"INSERT INTO [dbo].[files] ([id], [data], [data], [data]) VALUES (0x, NULL, '0xCAF', 'plain')"
|
||||
);
|
||||
let delete = DbRowEdit::Delete { key: vec![cv("id", Some("0X0A0B"))] };
|
||||
assert_eq!(
|
||||
edit_statement(DbDriver::Mysql, "db", "files", &delete, &binary).unwrap(),
|
||||
"DELETE FROM `db`.`files` WHERE `id` = X'0A0B'"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_columns_by_dialect() {
|
||||
for (driver, binary, text) in [
|
||||
(DbDriver::Sqlite, &["BLOB", "blob"][..], &["TEXT", "", "INTEGER"][..]),
|
||||
(DbDriver::Mysql, &["binary(16)", "varbinary(8)", "tinyblob", "longblob"], &["varchar(16)", "bit(1)"]),
|
||||
(
|
||||
DbDriver::SqlServer,
|
||||
&["binary", "varbinary", "image", "timestamp"],
|
||||
&["varchar", "nvarchar", "uniqueidentifier"],
|
||||
),
|
||||
(DbDriver::Postgres, &[], &["bytea", "text"]),
|
||||
(DbDriver::Oracle, &[], &["RAW", "BLOB"]),
|
||||
] {
|
||||
assert!(binary.iter().all(|t| binary_column(driver, t)), "{driver:?} {binary:?}");
|
||||
assert!(!text.iter().any(|t| binary_column(driver, t)), "{driver:?} {text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1463,12 +1548,13 @@ mod tests {
|
||||
DbDriver::Oracle,
|
||||
"hr",
|
||||
"t",
|
||||
&DbRowEdit::Update { key: key.clone(), values: vec![cv("n", Some("x"))] }
|
||||
&DbRowEdit::Update { key: key.clone(), values: vec![cv("n", Some("x"))] },
|
||||
&[]
|
||||
)
|
||||
.unwrap(),
|
||||
"UPDATE \"hr\".\"t\" SET \"n\" = 'x' WHERE \"id\" = '1'"
|
||||
);
|
||||
assert!(edit_statement(DbDriver::Oracle, "hr", "t", &DbRowEdit::Insert { values: vec![] }).is_err());
|
||||
assert!(edit_statement(DbDriver::Oracle, "hr", "t", &DbRowEdit::Insert { values: vec![] }, &[]).is_err());
|
||||
use crate::DbObjectKind as K;
|
||||
let (q, col) = object_ddl(DbDriver::Oracle, "hr", K::Procedure, "p").unwrap();
|
||||
assert!(q.contains("DBMS_METADATA.GET_DDL('PROCEDURE'") && col == 0);
|
||||
@@ -1702,7 +1788,7 @@ mod tests {
|
||||
table_page(driver, "PUBLIC", "ORDERS", None, &[], 50, 25),
|
||||
"SELECT * FROM \"PUBLIC\".\"ORDERS\" LIMIT 26 OFFSET 50"
|
||||
);
|
||||
assert!(edit_statement(driver, "PUBLIC", "T", &DbRowEdit::Insert { values: vec![] }).is_err());
|
||||
assert!(edit_statement(driver, "PUBLIC", "T", &DbRowEdit::Insert { values: vec![] }, &[]).is_err());
|
||||
assert_eq!(crate::conn::begin_statement(driver), "BEGIN");
|
||||
assert_eq!(crate::plan::explain_statement(driver, "select 1;"), "EXPLAIN USING TABULAR select 1");
|
||||
}
|
||||
|
||||
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::{DataSource, DbDriver, DbManager, DbOptions};
|
||||
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()
|
||||
}])
|
||||
@@ -304,6 +313,78 @@ async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Edits made from what the grid shows: a binary cell is `0x…` hex.
|
||||
#[tokio::test]
|
||||
async fn submits_binary_keys_and_values_as_bytes_and_a_missed_key_fails() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
for sql in [
|
||||
"DROP DATABASE IF EXISTS oi_binary",
|
||||
"CREATE DATABASE oi_binary",
|
||||
"CREATE TABLE oi_binary.files (id BINARY(16) PRIMARY KEY, name VARCHAR(20), data VARBINARY(8))",
|
||||
"INSERT INTO oi_binary.files VALUES (UUID_TO_BIN('3f06af63-a93c-11e4-9797-00505690773f'), 'a', 0xCAFE), \
|
||||
(0x01, 'b', NULL)",
|
||||
] {
|
||||
db.execute("m", sql, 1, &c).await?;
|
||||
}
|
||||
let page = db.table_page("m", "oi_binary", "files", None, &[], 0, 10, &c).await?;
|
||||
let mut ids: Vec<String> = page.result.rows.iter().map(|r| r[0].clone().unwrap()).collect();
|
||||
ids.sort();
|
||||
assert_eq!(ids, ["0x01000000000000000000000000000000", "0x3F06AF63A93C11E4979700505690773F"]);
|
||||
let cell = |column: &str, value: &str| CellValue { column: column.into(), value: Some(value.into()) };
|
||||
let edits = [
|
||||
DbRowEdit::Update {
|
||||
key: vec![cell("id", &ids[1])],
|
||||
values: vec![cell("name", "renamed"), cell("data", "0xCAFF")],
|
||||
},
|
||||
DbRowEdit::Delete { key: vec![cell("id", &ids[0])] },
|
||||
];
|
||||
assert_eq!(db.apply_edits("m", "oi_binary", "files", &edits).await?, 2);
|
||||
let r = db.execute("m", "SELECT HEX(id), name, HEX(data), LENGTH(data) FROM oi_binary.files", 10, &c).await?;
|
||||
let row = ["3F06AF63A93C11E4979700505690773F", "renamed", "CAFF", "2"].map(|v| Some(v.to_owned()));
|
||||
assert_eq!(r.rows, [row]);
|
||||
// The connection counts matched rows: an edit that leaves the row as it is counts it, and a
|
||||
// key that matches no row fails instead of reporting 0 rows changed.
|
||||
let same = DbRowEdit::Update { key: vec![cell("id", &ids[1])], values: vec![cell("name", "renamed")] };
|
||||
assert_eq!(db.apply_edits("m", "oi_binary", "files", &[same]).await?, 1);
|
||||
let missed = DbRowEdit::Update { key: vec![cell("id", "0x02")], values: vec![cell("name", "lost")] };
|
||||
let error = db.apply_edits("m", "oi_binary", "files", &[missed]).await.unwrap_err();
|
||||
assert!(error.message.contains("expected to change 1 row, changed 0"), "{}", error.message);
|
||||
db.execute("m", "DROP DATABASE oi_binary", 1, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_script_keeps_routine_bodies_and_delimiter_blocks_whole() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
for stmt in ["DROP DATABASE IF EXISTS oi_split", "CREATE DATABASE oi_split"] {
|
||||
db.execute("m", stmt, 1, &c).await?;
|
||||
}
|
||||
// A trigger written without DELIMITER, one as mysqldump writes it (in executable comments), then
|
||||
// a procedure in the mysql client's DELIMITER form.
|
||||
let script = "CREATE TABLE oi_split.t (id INT PRIMARY KEY, a INT, b INT);\n\
|
||||
CREATE TABLE oi_split.log (id INT);\n\
|
||||
CREATE TRIGGER oi_split.t_bi BEFORE INSERT ON oi_split.t FOR EACH ROW BEGIN\n \
|
||||
SET NEW.a = 1;\n SET NEW.b = 2;\nEND;\nDELIMITER ;;\n\
|
||||
/*!50003 CREATE*/ /*!50017 DEFINER=CURRENT_USER*/ /*!50003 TRIGGER oi_split.t_ai AFTER INSERT ON \
|
||||
oi_split.t FOR EACH ROW BEGIN\n INSERT INTO oi_split.log VALUES (NEW.id);\nEND */;;\n\
|
||||
DELIMITER //\nCREATE PROCEDURE oi_split.p()\nBEGIN\n \
|
||||
INSERT INTO oi_split.t (id) VALUES (1);\n INSERT INTO oi_split.t (id) VALUES (2);\nEND //\n\
|
||||
DELIMITER ;\nCALL oi_split.p();";
|
||||
for statement in ide_db::split::split(script, DbDriver::Mysql) {
|
||||
db.execute("m", &statement.text, 10, &c).await?;
|
||||
}
|
||||
let r = db
|
||||
.execute("m", "SELECT count(*), sum(a), sum(b), (SELECT count(*) FROM oi_split.log) FROM oi_split.t", 1, &c)
|
||||
.await?;
|
||||
assert_eq!(r.rows, [[Some("2".into()), Some("2".into()), Some("4".into()), Some("2".into())]]);
|
||||
db.execute("m", "DROP DATABASE oi_split", 1, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -363,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.
+108
-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();
|
||||
@@ -566,6 +650,28 @@ async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_script_keeps_begin_atomic_bodies_whole() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
for cleanup in ["DROP PROCEDURE IF EXISTS oi_split_insert", "DROP TABLE IF EXISTS oi_split"] {
|
||||
db.execute("p", cleanup, 1, &c).await?;
|
||||
}
|
||||
// The example of the CREATE PROCEDURE manual page, run statement by statement as the console does.
|
||||
let script = "CREATE TABLE oi_split (n integer);\nCREATE PROCEDURE oi_split_insert(a integer, b integer)\n\
|
||||
LANGUAGE SQL\nBEGIN ATOMIC\n INSERT INTO oi_split VALUES (a);\n INSERT INTO oi_split VALUES (b);\nEND;\n\
|
||||
CALL oi_split_insert(1, 2);";
|
||||
for statement in ide_db::split::split(script, DbDriver::Postgres) {
|
||||
db.execute("p", &statement.text, 10, &c).await?;
|
||||
}
|
||||
assert_eq!(db.execute("p", "SELECT count(*) FROM oi_split", 1, &c).await?.rows, [[Some("2".into())]]);
|
||||
for cleanup in ["DROP PROCEDURE oi_split_insert", "DROP TABLE oi_split"] {
|
||||
db.execute("p", cleanup, 1, &c).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -679,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(),
|
||||
@@ -736,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();
|
||||
@@ -227,6 +228,37 @@ async fn pages_sorts_filters_and_edits_in_a_transaction() -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Edits made from what the grid shows: a binary cell is `0x…` hex.
|
||||
#[tokio::test]
|
||||
async fn submits_binary_keys_and_values_as_bytes() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
let c = CancellationToken::new();
|
||||
for sql in [
|
||||
"CREATE TABLE files (id BLOB PRIMARY KEY, name TEXT, data BLOB)",
|
||||
"INSERT INTO files VALUES (x'0102', 'a', x'CAFE'), (x'0304', 'b', NULL)",
|
||||
] {
|
||||
db.execute("s1", sql, 1, &c).await?;
|
||||
}
|
||||
let page = db.table_page("s1", "main", "files", None, &[], 0, 10, &c).await?;
|
||||
let shown: Vec<_> = page.result.rows.iter().map(|r| r[0].clone().unwrap()).collect();
|
||||
assert_eq!(shown, ["0x0102", "0x0304"]);
|
||||
let cell = |column: &str, value: &str| CellValue { column: column.into(), value: Some(value.into()) };
|
||||
let edits = [
|
||||
DbRowEdit::Update {
|
||||
key: vec![cell("id", "0x0102")],
|
||||
values: vec![cell("name", "renamed"), cell("data", "0xCAFF")],
|
||||
},
|
||||
DbRowEdit::Delete { key: vec![cell("id", "0x0304")] },
|
||||
DbRowEdit::Insert { values: vec![cell("id", "0x05"), cell("name", "0x0A"), cell("data", "0x")] },
|
||||
];
|
||||
assert_eq!(db.apply_edits("s1", "main", "files", &edits).await?, 3);
|
||||
let r = db.execute("s1", "SELECT hex(id), name, typeof(data), hex(data) FROM files ORDER BY id", 10, &c).await?;
|
||||
let cells = |row: &[&str]| row.iter().map(|v| Some(v.to_string())).collect::<Vec<_>>();
|
||||
// A hex-looking value of a text column stays text.
|
||||
assert_eq!(r.rows, [cells(&["0102", "renamed", "blob", "CAFF"]), cells(&["05", "0x0A", "blob", ""])]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_connection_and_disconnect() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
@@ -417,6 +449,38 @@ async fn lists_triggers_and_their_ddl() -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scripts_and_execute_at_the_caret_keep_trigger_bodies_whole() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
let c = CancellationToken::new();
|
||||
// A script runs its statements one by one, as the console and Run SQL Script do.
|
||||
let script = "CREATE TABLE log (msg TEXT);\nCREATE TRIGGER users_added AFTER INSERT ON users BEGIN\n \
|
||||
INSERT INTO log VALUES ('added ' || NEW.name);\n UPDATE users SET note = 'logged' WHERE id = NEW.id;\nEND;\n\
|
||||
INSERT INTO users (name) VALUES ('dee');";
|
||||
for statement in ide_db::split::split(script, DbDriver::Sqlite) {
|
||||
db.execute("s1", &statement.text, 10, &c).await?;
|
||||
}
|
||||
let r = db
|
||||
.execute("s1", "SELECT (SELECT group_concat(msg) FROM log), (SELECT note FROM users WHERE name = 'dee')", 1, &c)
|
||||
.await?;
|
||||
assert_eq!(r.rows, [[Some("added dee".into()), Some("logged".into())]]);
|
||||
// Execute with the caret on the body's DELETE creates the trigger and deletes nothing.
|
||||
let console = "CREATE TRIGGER users_gone AFTER DELETE ON users BEGIN\n DELETE FROM log;\nEND;";
|
||||
let caret = console.find("FROM log").unwrap() as u32;
|
||||
let statement = ide_db::split::statement_at(console, caret, DbDriver::Sqlite).unwrap();
|
||||
db.execute("s1", &statement.text, 10, &c).await?;
|
||||
let r = db
|
||||
.execute(
|
||||
"s1",
|
||||
"SELECT (SELECT count(*) FROM log), (SELECT count(*) FROM sqlite_master WHERE type = 'trigger')",
|
||||
1,
|
||||
&c,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(r.rows, [[Some("1".into()), Some("2".into())]]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn applies_driver_properties_and_the_startup_script_on_connect() -> IdeResult<()> {
|
||||
let (tmp, db) = setup().await;
|
||||
@@ -464,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.
+100
@@ -96,6 +96,106 @@ async fn sqlserver_values_paging_transactions_and_cancellation() {
|
||||
assert_eq!(pool.rows("SELECT 1", 1).await.unwrap()[0][0].as_deref(), Some("1"));
|
||||
}
|
||||
|
||||
/// Edits made from what the grid shows: a binary cell is `0x…` hex.
|
||||
#[tokio::test]
|
||||
async fn sqlserver_submits_binary_keys_and_values_as_bytes() {
|
||||
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
|
||||
let mut parts = server.splitn(4, ':');
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().to_path_buf();
|
||||
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let db = ide_db::DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
db.save_sources(vec![DataSource {
|
||||
id: "s".into(),
|
||||
name: "sqlserver".into(),
|
||||
driver: DbDriver::SqlServer,
|
||||
host: parts.next().unwrap().into(),
|
||||
port: Some(parts.next().unwrap().parse().unwrap()),
|
||||
user: parts.next().unwrap().into(),
|
||||
database: "tempdb".into(),
|
||||
ssl: DbSslMode::Disable,
|
||||
..Default::default()
|
||||
}])
|
||||
.await
|
||||
.unwrap();
|
||||
db.set_password("s", parts.next().map(str::to_owned), false).await.unwrap();
|
||||
let c = CancellationToken::new();
|
||||
let table = format!("oi_binary_{}", std::process::id());
|
||||
db.execute(
|
||||
"s",
|
||||
&format!("CREATE TABLE dbo.{table} (id varbinary(16) PRIMARY KEY, name nvarchar(20), data varbinary(8))"),
|
||||
1,
|
||||
&c,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
db.execute("s", &format!("INSERT INTO dbo.{table} VALUES (0x0102, 'a', 0xCAFE), (0x0304, 'b', NULL)"), 1, &c)
|
||||
.await
|
||||
.unwrap();
|
||||
let page = db.table_page("s", "dbo", &table, None, &[], 0, 10, &c).await.unwrap();
|
||||
let mut ids: Vec<_> = page.result.rows.iter().map(|r| r[0].clone().unwrap()).collect();
|
||||
ids.sort();
|
||||
assert_eq!(ids, ["0x0102", "0x0304"]);
|
||||
let cell = |column: &str, value: &str| ide_db::CellValue { column: column.into(), value: Some(value.into()) };
|
||||
let edits = [
|
||||
ide_db::DbRowEdit::Update {
|
||||
key: vec![cell("id", "0x0102")],
|
||||
values: vec![cell("name", "renamed"), cell("data", "0xCAFF")],
|
||||
},
|
||||
ide_db::DbRowEdit::Delete { key: vec![cell("id", "0x0304")] },
|
||||
];
|
||||
assert_eq!(db.apply_edits("s", "dbo", &table, &edits).await.unwrap(), 2);
|
||||
let r = db
|
||||
.execute(
|
||||
"s",
|
||||
&format!("SELECT CONVERT(varchar(40), id, 1), name, CONVERT(varchar(40), data, 1) FROM dbo.{table}"),
|
||||
10,
|
||||
&c,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.rows, [["0x0102", "renamed", "0xCAFF"].map(|v| Some(v.to_owned()))]);
|
||||
db.execute("s", &format!("DROP TABLE dbo.{table}"), 1, &c).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlserver_scripts_keep_go_batches_and_routine_bodies_whole() {
|
||||
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
|
||||
let mut parts = server.splitn(4, ':');
|
||||
let source = DataSource {
|
||||
driver: DbDriver::SqlServer,
|
||||
host: parts.next().unwrap().into(),
|
||||
port: Some(parts.next().unwrap().parse().unwrap()),
|
||||
user: parts.next().unwrap().into(),
|
||||
database: "tempdb".into(),
|
||||
ssl: DbSslMode::Disable,
|
||||
..Default::default()
|
||||
};
|
||||
let pool = Pool::connect(&source, parts.next(), None).await.unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let (table, proc) =
|
||||
(format!("dbo.oi_split_{}", std::process::id()), format!("dbo.oi_split_p_{}", std::process::id()));
|
||||
// An SSMS-style script, run statement by statement as the console does.
|
||||
let script = format!(
|
||||
"CREATE TABLE {table} (a int)\nGO\nCREATE PROCEDURE {proc} AS\nBEGIN\n SET NOCOUNT ON;\n \
|
||||
INSERT INTO {table} VALUES (1);\n INSERT INTO {table} VALUES (2);\nEND\nGO\nEXEC {proc}"
|
||||
);
|
||||
for statement in ide_db::split::split(&script, DbDriver::SqlServer) {
|
||||
pool.execute(&statement.text, 10, &cancel).await.unwrap();
|
||||
}
|
||||
assert_eq!(pool.rows(&format!("SELECT count(*) FROM {table}"), 1).await.unwrap(), [[Some("2".into())]]);
|
||||
// Without GO, SQL Server reads the rest of the batch as the body.
|
||||
let body = format!("CREATE PROCEDURE {proc}_q AS SELECT 1 AS one; SELECT 2 AS two;");
|
||||
for statement in ide_db::split::split(&body, DbDriver::SqlServer) {
|
||||
pool.execute(&statement.text, 10, &cancel).await.unwrap();
|
||||
}
|
||||
let definition = pool.rows(&format!("SELECT OBJECT_DEFINITION(OBJECT_ID('{proc}_q'))"), 1).await.unwrap();
|
||||
assert_eq!(definition, [[Some(body)]]);
|
||||
pool.execute(&format!("DROP PROCEDURE {proc}; DROP PROCEDURE {proc}_q; DROP TABLE {table}"), 1, &cancel)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlserver_creates_from_a_held_model_and_force_drops_a_held_database() {
|
||||
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
|
||||
File renamed without changes.
@@ -7,8 +7,9 @@
|
||||
|
||||
use crate::{
|
||||
COMPOSE_DIR, COMPOSE_FILES, COMPOSE_PROJECT, COMPOSE_SERVICE, ContainerOp, DockerAvailability, DockerContainer,
|
||||
DockerEndpoint, DockerHostResources, DockerImage, DockerImageLayer, DockerLogLine, DockerNetwork, DockerObject,
|
||||
DockerProcessList, DockerSnapshot, DockerVolume, parse_info, split_csv,
|
||||
DockerContainerStatsSample, DockerEndpoint, DockerHostResources, DockerImage, DockerImageLayer, DockerLogLine,
|
||||
DockerNetwork, DockerObject, DockerProcessList, DockerSnapshot, DockerVolume, EngineStatsState,
|
||||
parse_engine_stats_frame, parse_info, split_csv,
|
||||
};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::Deserialize;
|
||||
@@ -66,17 +67,25 @@ pub(crate) fn address(ep: &DockerEndpoint) -> Option<Address> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a daemon host URL (`unix:///path`, `tcp://host:port`, `http://host:port`)
|
||||
/// into a direct Engine API address when no TLS or Windows named pipe is required.
|
||||
pub(crate) fn address_from_url(url: &str) -> Option<Address> {
|
||||
let host = url.trim();
|
||||
if host.is_empty() {
|
||||
return None;
|
||||
}
|
||||
match host.split_once("://") {
|
||||
Some(("unix", rest)) if !cfg!(windows) && !rest.is_empty() => Some(Address::UnixSocket(rest.to_owned())),
|
||||
Some(("tcp", rest)) | Some(("http", rest)) => host_port(rest).map(|(host, port)| Address::Tcp { host, port }),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The default endpoint's daemon: `DOCKER_HOST` when it is a plain socket or
|
||||
/// TCP address, else the unix socket (Windows named pipes need the CLI).
|
||||
fn default_address(docker_host: Option<&str>) -> Option<Address> {
|
||||
if let Some(host) = docker_host.map(str::trim).filter(|h| !h.is_empty()) {
|
||||
return match host.split_once("://") {
|
||||
Some(("unix", rest)) if !cfg!(windows) && !rest.is_empty() => Some(Address::UnixSocket(rest.to_owned())),
|
||||
Some(("tcp", rest)) | Some(("http", rest)) => {
|
||||
host_port(rest).map(|(host, port)| Address::Tcp { host, port })
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
return address_from_url(host);
|
||||
}
|
||||
if cfg!(unix) { Some(Address::UnixSocket("/var/run/docker.sock".into())) } else { None }
|
||||
}
|
||||
@@ -623,9 +632,77 @@ fn unix_now() -> i64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// How often a log stream that has nothing to read checks for cancellation.
|
||||
fn unix_now_ms() -> u64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// How often a log or stats stream that has nothing to read checks for cancellation.
|
||||
const LOG_POLL: Duration = Duration::from_millis(200);
|
||||
|
||||
/// Streams live resource samples for running container `id` directly from the Docker
|
||||
/// Engine HTTP API (`GET /containers/{id}/stats?stream=true`) until the container stops
|
||||
/// or `cancel` fires.
|
||||
pub(crate) fn container_stats_stream(
|
||||
addr: &Address,
|
||||
id: &str,
|
||||
timeout: Duration,
|
||||
cancel: &CancellationToken,
|
||||
on_sample: &dyn Fn(DockerContainerStatsSample),
|
||||
) -> IdeResult<()> {
|
||||
let path = format!("/containers/{}/stats?stream=true", path_segment(id));
|
||||
let mut conn = Conn::connect(addr, timeout)?;
|
||||
conn.write_all(
|
||||
format!("GET {path} HTTP/1.1\r\nHost: docker\r\nUser-Agent: openidea\r\nConnection: close\r\n\r\n").as_bytes(),
|
||||
)?;
|
||||
let head = read_head(&mut conn)?;
|
||||
if !(200..300).contains(&head.status) {
|
||||
let body = read_body(&mut conn, &head)?;
|
||||
check(Response { status: head.status, body })?;
|
||||
}
|
||||
conn.set_timeouts(LOG_POLL);
|
||||
let mut framing = BodyFraming::from_head(&head);
|
||||
let mut partial = Vec::new();
|
||||
let mut payload = Vec::new();
|
||||
let mut state = EngineStatsState::default();
|
||||
let mut buf = [0u8; 8192];
|
||||
while !framing.done() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match conn.read(&mut buf) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => {
|
||||
payload.clear();
|
||||
framing.decode(&buf[..n], &mut payload)?;
|
||||
for &b in &payload {
|
||||
if b == b'\n' {
|
||||
let line = line_text(&partial);
|
||||
partial.clear();
|
||||
if let Some(sample) = parse_engine_stats_frame(&line, &mut state, unix_now_ms()) {
|
||||
on_sample(sample);
|
||||
}
|
||||
} else {
|
||||
partial.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e)
|
||||
if matches!(
|
||||
e.kind(),
|
||||
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut | std::io::ErrorKind::Interrupted
|
||||
) => {}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
if !partial.is_empty() {
|
||||
let line = line_text(&partial);
|
||||
if let Some(sample) = parse_engine_stats_frame(&line, &mut state, unix_now_ms()) {
|
||||
on_sample(sample);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct ApiContainerInspect {
|
||||
@@ -723,32 +800,30 @@ enum ChunkState {
|
||||
Done,
|
||||
}
|
||||
|
||||
impl LogDecoder {
|
||||
fn new(head: &Head, tty: bool) -> Self {
|
||||
let body = if head.chunked {
|
||||
BodyFraming::Chunked { state: ChunkState::Size, line: Vec::new() }
|
||||
impl BodyFraming {
|
||||
fn from_head(head: &Head) -> Self {
|
||||
if head.chunked {
|
||||
Self::Chunked { state: ChunkState::Size, line: Vec::new() }
|
||||
} else if let Some(n) = head.length {
|
||||
BodyFraming::Length(n)
|
||||
Self::Length(n)
|
||||
} else {
|
||||
BodyFraming::Close
|
||||
};
|
||||
Self { body, tty, header: Vec::new(), frame_left: 0, frame_stderr: false, partial: [Vec::new(), Vec::new()] }
|
||||
Self::Close
|
||||
}
|
||||
}
|
||||
|
||||
fn done(&self) -> bool {
|
||||
matches!(self.body, BodyFraming::Chunked { state: ChunkState::Done, .. } | BodyFraming::Length(0))
|
||||
matches!(self, Self::Chunked { state: ChunkState::Done, .. } | Self::Length(0))
|
||||
}
|
||||
|
||||
fn feed(&mut self, mut bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) -> IdeResult<()> {
|
||||
let mut payload = Vec::new();
|
||||
match &mut self.body {
|
||||
BodyFraming::Close => payload.extend_from_slice(bytes),
|
||||
BodyFraming::Length(left) => {
|
||||
fn decode(&mut self, mut bytes: &[u8], payload: &mut Vec<u8>) -> IdeResult<()> {
|
||||
match self {
|
||||
Self::Close => payload.extend_from_slice(bytes),
|
||||
Self::Length(left) => {
|
||||
let take = (*left).min(bytes.len());
|
||||
payload.extend_from_slice(&bytes[..take]);
|
||||
*left -= take;
|
||||
}
|
||||
BodyFraming::Chunked { state, line } => {
|
||||
Self::Chunked { state, line } => {
|
||||
while !bytes.is_empty() {
|
||||
match *state {
|
||||
ChunkState::Done => break,
|
||||
@@ -791,6 +866,29 @@ impl LogDecoder {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl LogDecoder {
|
||||
fn new(head: &Head, tty: bool) -> Self {
|
||||
Self {
|
||||
body: BodyFraming::from_head(head),
|
||||
tty,
|
||||
header: Vec::new(),
|
||||
frame_left: 0,
|
||||
frame_stderr: false,
|
||||
partial: [Vec::new(), Vec::new()],
|
||||
}
|
||||
}
|
||||
|
||||
fn done(&self) -> bool {
|
||||
self.body.done()
|
||||
}
|
||||
|
||||
fn feed(&mut self, bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) -> IdeResult<()> {
|
||||
let mut payload = Vec::new();
|
||||
self.body.decode(bytes, &mut payload)?;
|
||||
self.frames(&payload, emit);
|
||||
Ok(())
|
||||
}
|
||||
@@ -1443,4 +1541,65 @@ mod tests {
|
||||
assert_eq!(path_segment("a/b"), "a%2Fb");
|
||||
assert_eq!(path_segment(" sha256:ab "), "sha256%3Aab");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_stats_stream_reads_chunked_ndjson_samples() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (mut sock, _) = listener.accept().unwrap();
|
||||
let mut req_buf = [0u8; 512];
|
||||
let n = sock.read(&mut req_buf).unwrap();
|
||||
let req = String::from_utf8_lossy(&req_buf[..n]);
|
||||
assert!(req.starts_with("GET /containers/c1/stats?stream=true HTTP/1.1\r\n"));
|
||||
let f1 = concat!(
|
||||
r#"{"read":"2026-12-04T18:12:06Z","pids_stats":{"current":3},"#,
|
||||
r#""cpu_stats":{"cpu_usage":{"total_usage":200},"system_cpu_usage":1000,"online_cpus":2},"#,
|
||||
r#""precpu_stats":{"cpu_usage":{"total_usage":100},"system_cpu_usage":500,"online_cpus":2},"#,
|
||||
r#""memory_stats":{"usage":52428800,"limit":104857600},"#,
|
||||
r#""networks":{"eth0":{"rx_bytes":1000,"tx_bytes":500}},"#,
|
||||
r#""blkio_stats":{"io_service_bytes_recursive":[{"op":"Read","value":4096},{"op":"Write","value":8192}]}}"#,
|
||||
"\n",
|
||||
);
|
||||
let f2 = concat!(
|
||||
r#"{"read":"2026-12-04T18:12:07Z","pids_stats":{"current":4},"#,
|
||||
r#""cpu_stats":{"cpu_usage":{"total_usage":250},"system_cpu_usage":1500,"online_cpus":2},"#,
|
||||
r#""memory_stats":{"usage":62914560,"limit":104857600},"#,
|
||||
r#""networks":{"eth0":{"rx_bytes":2500,"tx_bytes":900}},"#,
|
||||
r#""blkio_stats":{"io_service_bytes_recursive":[{"op":"Read","value":4096},{"op":"Write","value":16384}]}}"#,
|
||||
"\n",
|
||||
);
|
||||
let mut resp =
|
||||
b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\n".to_vec();
|
||||
for chunk in [f1.as_bytes(), f2.as_bytes()] {
|
||||
resp.extend(format!("{:x}\r\n", chunk.len()).as_bytes());
|
||||
resp.extend(chunk);
|
||||
resp.extend(b"\r\n");
|
||||
}
|
||||
resp.extend(b"0\r\n\r\n");
|
||||
sock.write_all(&resp).unwrap();
|
||||
});
|
||||
|
||||
let samples = std::sync::Mutex::new(Vec::new());
|
||||
let cancel = CancellationToken::new();
|
||||
container_stats_stream(
|
||||
&Address::Tcp { host: "127.0.0.1".into(), port },
|
||||
"c1",
|
||||
Duration::from_secs(5),
|
||||
&cancel,
|
||||
&|s| samples.lock().unwrap().push(s),
|
||||
)
|
||||
.unwrap();
|
||||
server.join().unwrap();
|
||||
|
||||
let samples = samples.into_inner().unwrap();
|
||||
assert_eq!(samples.len(), 2);
|
||||
assert!((samples[0].cpu_percent - 40.0).abs() < 1e-6);
|
||||
assert_eq!(samples[0].mem_used_bytes, 52_428_800);
|
||||
assert_eq!(samples[0].disk_write_bytes, 8192);
|
||||
// Second frame lacked precpu_stats and used saved EngineStatsState: (50/500)*2*100 = 20%.
|
||||
assert!((samples[1].cpu_percent - 20.0).abs() < 1e-6);
|
||||
assert_eq!(samples[1].net_rx_bytes, 2500);
|
||||
assert_eq!(samples[1].pids, 4);
|
||||
}
|
||||
}
|
||||
@@ -343,6 +343,75 @@ pub fn container_stats(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerContain
|
||||
parse_container_stats(&out).ok_or_else(|| IdeError::not_found("no container stats returned"))
|
||||
}
|
||||
|
||||
fn unix_now_ms() -> u64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Resolves `ep` to a direct Docker Engine API socket/TCP address when reachable
|
||||
/// without TLS or named pipes, including `Default`/`Context` daemons such as
|
||||
/// Docker Desktop (`desktop-linux`), OrbStack, or Colima.
|
||||
fn resolve_engine_address(ep: &DockerEndpoint) -> Option<engine::Address> {
|
||||
if std::env::var_os("OPENIDEA_DOCKER").is_some() {
|
||||
return None;
|
||||
}
|
||||
match ep {
|
||||
DockerEndpoint::Socket { .. } | DockerEndpoint::Tcp { .. } => engine::address(ep),
|
||||
DockerEndpoint::Default => {
|
||||
if docker_executable().is_none() {
|
||||
return engine::address(ep);
|
||||
}
|
||||
let url = default_daemon_url(
|
||||
ide_core::process::host_var_os("DOCKER_CONTEXT").as_deref().and_then(|v| v.to_str()),
|
||||
ide_core::process::host_var_os("DOCKER_HOST").as_deref().and_then(|v| v.to_str()),
|
||||
|name| context_host(&DockerEndpoint::Default, name),
|
||||
)
|
||||
.ok()?;
|
||||
engine::address_from_url(&url).or_else(|| engine::address(ep))
|
||||
}
|
||||
DockerEndpoint::Context { name } => {
|
||||
let url = context_host(&DockerEndpoint::Default, Some(name.trim())).ok()?;
|
||||
engine::address_from_url(&url)
|
||||
}
|
||||
DockerEndpoint::Ssh { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams live resource samples for running container `id` until it stops or `cancel` fires.
|
||||
/// Prefers the direct Engine HTTP API (`GET /containers/{id}/stats?stream=true`) for exact
|
||||
/// byte counters with zero CLI process overhead; falls back to streaming `docker stats`.
|
||||
pub fn stream_container_stats(
|
||||
ep: &DockerEndpoint,
|
||||
id: &str,
|
||||
cancel: &CancellationToken,
|
||||
on_sample: &dyn Fn(DockerContainerStatsSample),
|
||||
) -> IdeResult<()> {
|
||||
let id = check_id(id)?;
|
||||
if let Some(addr) = resolve_engine_address(ep) {
|
||||
let emitted = std::cell::Cell::new(false);
|
||||
let res = engine::container_stats_stream(&addr, id, QUICK, cancel, &|sample| {
|
||||
emitted.set(true);
|
||||
on_sample(sample);
|
||||
});
|
||||
match res {
|
||||
Ok(()) => return Ok(()),
|
||||
// If cancelled, or samples already streamed, or CLI is absent, propagate directly.
|
||||
Err(e) if cancel.is_cancelled() || emitted.get() || docker_executable().is_none() => return Err(e),
|
||||
Err(e) => {
|
||||
tracing::debug!("direct Docker stats stream unavailable, falling back to CLI: {}", e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
let args = ["stats", "--no-trunc", "--format", "{{json .}}", id];
|
||||
let (ok, stderr) = process::stream(command(ep, &args)?, cancel, &mut |stream, line| {
|
||||
if stream == Stream::Stdout
|
||||
&& let Some(sample) = parse_cli_stats_sample(&line, unix_now_ms())
|
||||
{
|
||||
on_sample(sample);
|
||||
}
|
||||
})?;
|
||||
if ok { Ok(()) } else { Err(failure(&args, &stderr.join("\n"), "")) }
|
||||
}
|
||||
|
||||
/// CPU and memory capacity of the Docker daemon / VM (`docker info`).
|
||||
pub fn host_resources(ep: &DockerEndpoint) -> IdeResult<DockerHostResources> {
|
||||
if docker_executable().is_none()
|
||||
|
||||
@@ -145,6 +145,37 @@ pub struct DockerContainerStats {
|
||||
pub pids: String,
|
||||
}
|
||||
|
||||
/// One time-series resource sample for a running container (from Docker Engine
|
||||
/// `GET /containers/{id}/stats?stream=true` or the `docker stats` CLI stream fallback).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DockerContainerStatsSample {
|
||||
/// Sample timestamp as Unix epoch milliseconds.
|
||||
pub timestamp_ms: u64,
|
||||
/// CPU utilization percentage (may exceed 100.0 on multi-core containers).
|
||||
pub cpu_percent: f64,
|
||||
/// Number of CPUs visible to this container/daemon, if reported.
|
||||
pub online_cpus: Option<u32>,
|
||||
/// Working memory usage in bytes (excluding reclaimable page cache, matching `docker stats`).
|
||||
pub mem_used_bytes: u64,
|
||||
/// Effective memory limit in bytes (container cgroup limit or Docker VM memory).
|
||||
pub mem_limit_bytes: u64,
|
||||
/// Memory usage percentage (`0.0..=100.0`).
|
||||
pub mem_percent: f64,
|
||||
/// Cumulative network bytes received across all interfaces.
|
||||
pub net_rx_bytes: u64,
|
||||
/// Cumulative network bytes transmitted across all interfaces.
|
||||
pub net_tx_bytes: u64,
|
||||
/// Cumulative block device bytes read.
|
||||
pub disk_read_bytes: u64,
|
||||
/// Cumulative block device bytes written.
|
||||
pub disk_write_bytes: u64,
|
||||
/// Current PID count inside the container.
|
||||
pub pids: u64,
|
||||
/// True when I/O or memory counters came from rounded CLI strings rather than raw Engine API bytes.
|
||||
pub approximate_io: bool,
|
||||
}
|
||||
|
||||
/// CPU and memory capacity of the Docker daemon / VM (`docker info`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -517,6 +548,342 @@ pub fn parse_container_stats(text: &str) -> Option<DockerContainerStats> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Previous CPU counters retained across Engine API stats frames so CPU% stays
|
||||
/// accurate even when the daemon omits `precpu_stats` on the first frame.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct EngineStatsState {
|
||||
prev_cpu_total: Option<u64>,
|
||||
prev_system_cpu: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiStatsFrame {
|
||||
read: String,
|
||||
pids_stats: ApiPidsStats,
|
||||
blkio_stats: ApiBlkioStats,
|
||||
storage_stats: ApiStorageStats,
|
||||
cpu_stats: ApiCpuStats,
|
||||
precpu_stats: ApiCpuStats,
|
||||
memory_stats: ApiMemoryStats,
|
||||
networks: Option<BTreeMap<String, ApiNetworkStats>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiPidsStats {
|
||||
current: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiBlkioStats {
|
||||
io_service_bytes_recursive: Option<Vec<ApiBlkioEntry>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiBlkioEntry {
|
||||
op: String,
|
||||
value: u64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiStorageStats {
|
||||
read_size_bytes: Option<u64>,
|
||||
write_size_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiCpuStats {
|
||||
cpu_usage: ApiCpuUsage,
|
||||
system_cpu_usage: Option<u64>,
|
||||
online_cpus: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiCpuUsage {
|
||||
total_usage: u64,
|
||||
percpu_usage: Option<Vec<u64>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiMemoryStats {
|
||||
usage: Option<u64>,
|
||||
limit: Option<u64>,
|
||||
privateworkingset: Option<u64>,
|
||||
stats: Option<BTreeMap<String, u64>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiNetworkStats {
|
||||
rx_bytes: u64,
|
||||
tx_bytes: u64,
|
||||
}
|
||||
|
||||
fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
|
||||
let y = year - i64::from(month <= 2);
|
||||
let era = y.div_euclid(400);
|
||||
let yoe = (y - era * 400) as u64;
|
||||
let m = month as u64;
|
||||
let d = day as u64;
|
||||
let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
|
||||
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
||||
era * 146_097 + doe as i64 - 719_468
|
||||
}
|
||||
|
||||
/// Parses an RFC3339 timestamp (`YYYY-MM-DDTHH:MM:SS(.frac)?(Z|±HH:MM)`) into Unix
|
||||
/// epoch milliseconds, rejecting Docker's zero timestamp (`0001-01-01…`).
|
||||
pub fn parse_rfc3339_ms(raw: &str) -> Option<u64> {
|
||||
let s = raw.trim();
|
||||
if s.len() < 20 {
|
||||
return None;
|
||||
}
|
||||
let b = s.as_bytes();
|
||||
if b[4] != b'-'
|
||||
|| b[7] != b'-'
|
||||
|| (b[10] != b'T' && b[10] != b't' && b[10] != b' ')
|
||||
|| b[13] != b':'
|
||||
|| b[16] != b':'
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let year: i64 = s[0..4].parse().ok()?;
|
||||
let month: u32 = s[5..7].parse().ok()?;
|
||||
let day: u32 = s[8..10].parse().ok()?;
|
||||
let hour: u64 = s[11..13].parse().ok()?;
|
||||
let minute: u64 = s[14..16].parse().ok()?;
|
||||
let second: u64 = s[17..19].parse().ok()?;
|
||||
if year <= 1 || !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || minute > 59 || second > 60 {
|
||||
return None;
|
||||
}
|
||||
let mut rest = &s[19..];
|
||||
let mut millis: u64 = 0;
|
||||
if let Some(after_dot) = rest.strip_prefix('.') {
|
||||
let digits_len = after_dot.bytes().take_while(u8::is_ascii_digit).count();
|
||||
let frac = &after_dot[..digits_len];
|
||||
let mut scale = 100u64;
|
||||
for ch in frac.bytes().take(3) {
|
||||
millis += u64::from(ch - b'0') * scale;
|
||||
scale /= 10;
|
||||
}
|
||||
rest = &after_dot[digits_len..];
|
||||
}
|
||||
let offset_secs: i64 = if rest.eq_ignore_ascii_case("Z") {
|
||||
0
|
||||
} else if rest.len() == 6 && (rest.starts_with('+') || rest.starts_with('-')) && rest.as_bytes()[3] == b':' {
|
||||
let sign = if rest.starts_with('-') { -1i64 } else { 1i64 };
|
||||
let oh: i64 = rest[1..3].parse().ok()?;
|
||||
let om: i64 = rest[4..6].parse().ok()?;
|
||||
if oh > 23 || om > 59 {
|
||||
return None;
|
||||
}
|
||||
sign * (oh * 3600 + om * 60)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
let days = days_from_civil(year, month, day);
|
||||
let secs = days * 86_400 + (hour * 3600 + minute * 60 + second) as i64 - offset_secs;
|
||||
if secs < 0 {
|
||||
return None;
|
||||
}
|
||||
Some((secs as u64).saturating_mul(1000).saturating_add(millis))
|
||||
}
|
||||
|
||||
/// Parses one newline-delimited JSON frame from Docker Engine `GET /containers/{id}/stats`.
|
||||
/// Returns `None` for malformed lines or Docker's empty final frame after a container stops.
|
||||
pub fn parse_engine_stats_frame(
|
||||
line: &str,
|
||||
state: &mut EngineStatsState,
|
||||
fallback_timestamp_ms: u64,
|
||||
) -> Option<DockerContainerStatsSample> {
|
||||
let trimmed = line.trim();
|
||||
if !trimmed.starts_with('{') {
|
||||
return None;
|
||||
}
|
||||
let frame: ApiStatsFrame = serde_json::from_str(trimmed).ok()?;
|
||||
|
||||
let mem_limit = frame.memory_stats.limit.unwrap_or(0);
|
||||
let sys_cpu = frame.cpu_stats.system_cpu_usage.unwrap_or(0);
|
||||
let raw_usage = frame.memory_stats.usage.unwrap_or(0);
|
||||
let private_ws = frame.memory_stats.privateworkingset.unwrap_or(0);
|
||||
|
||||
// When a container stops mid-stream, Docker sends a final zeroed frame with read="0001-01-01…".
|
||||
if frame.read.starts_with("0001-01-01") && mem_limit == 0 && sys_cpu == 0 && raw_usage == 0 && private_ws == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let timestamp_ms = parse_rfc3339_ms(&frame.read).unwrap_or(fallback_timestamp_ms);
|
||||
|
||||
let online_cpus = frame
|
||||
.cpu_stats
|
||||
.online_cpus
|
||||
.filter(|&n| n > 0)
|
||||
.or_else(|| frame.cpu_stats.cpu_usage.percpu_usage.as_ref().map(|v| v.len() as u32).filter(|&n| n > 0));
|
||||
|
||||
let cur_cpu = frame.cpu_stats.cpu_usage.total_usage;
|
||||
let (pre_cpu, pre_sys) = match frame.precpu_stats.system_cpu_usage.filter(|&s| s > 0) {
|
||||
Some(s) => (frame.precpu_stats.cpu_usage.total_usage, s),
|
||||
None => (state.prev_cpu_total.unwrap_or(0), state.prev_system_cpu.unwrap_or(0)),
|
||||
};
|
||||
state.prev_cpu_total = Some(cur_cpu);
|
||||
state.prev_system_cpu = Some(sys_cpu);
|
||||
|
||||
let cpu_delta = cur_cpu.saturating_sub(pre_cpu);
|
||||
let system_delta = sys_cpu.saturating_sub(pre_sys);
|
||||
let cpu_percent = if system_delta > 0 && cpu_delta > 0 {
|
||||
(cpu_delta as f64 / system_delta as f64) * f64::from(online_cpus.unwrap_or(1)) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
// Match Docker CLI `calculateMemUsageUnixNoCache`: subtract inactive_file (cgroup v2)
|
||||
// or total_inactive_file (cgroup v1) when below raw usage; fall back to Windows privateworkingset.
|
||||
let mem_used_bytes = if raw_usage > 0 {
|
||||
let reclaimable = frame
|
||||
.memory_stats
|
||||
.stats
|
||||
.as_ref()
|
||||
.and_then(|s| s.get("total_inactive_file").or_else(|| s.get("inactive_file")).copied())
|
||||
.filter(|&v| v < raw_usage)
|
||||
.unwrap_or(0);
|
||||
raw_usage - reclaimable
|
||||
} else {
|
||||
private_ws
|
||||
};
|
||||
let mem_percent = if mem_limit > 0 { (mem_used_bytes as f64 / mem_limit as f64) * 100.0 } else { 0.0 };
|
||||
|
||||
let (mut net_rx_bytes, mut net_tx_bytes) = (0u64, 0u64);
|
||||
if let Some(nets) = frame.networks {
|
||||
for net in nets.values() {
|
||||
net_rx_bytes = net_rx_bytes.saturating_add(net.rx_bytes);
|
||||
net_tx_bytes = net_tx_bytes.saturating_add(net.tx_bytes);
|
||||
}
|
||||
}
|
||||
|
||||
let (mut disk_read_bytes, mut disk_write_bytes) = (0u64, 0u64);
|
||||
let mut saw_blkio = false;
|
||||
if let Some(entries) = frame.blkio_stats.io_service_bytes_recursive {
|
||||
for entry in entries {
|
||||
if entry.op.eq_ignore_ascii_case("read") {
|
||||
disk_read_bytes = disk_read_bytes.saturating_add(entry.value);
|
||||
saw_blkio = true;
|
||||
} else if entry.op.eq_ignore_ascii_case("write") {
|
||||
disk_write_bytes = disk_write_bytes.saturating_add(entry.value);
|
||||
saw_blkio = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !saw_blkio {
|
||||
disk_read_bytes = frame.storage_stats.read_size_bytes.unwrap_or(0);
|
||||
disk_write_bytes = frame.storage_stats.write_size_bytes.unwrap_or(0);
|
||||
}
|
||||
|
||||
Some(DockerContainerStatsSample {
|
||||
timestamp_ms,
|
||||
cpu_percent,
|
||||
online_cpus,
|
||||
mem_used_bytes,
|
||||
mem_limit_bytes: mem_limit,
|
||||
mem_percent,
|
||||
net_rx_bytes,
|
||||
net_tx_bytes,
|
||||
disk_read_bytes,
|
||||
disk_write_bytes,
|
||||
pids: frame.pids_stats.current.unwrap_or(0),
|
||||
approximate_io: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_unit_bytes(raw: &str) -> u64 {
|
||||
let s = raw.trim();
|
||||
if s.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let split = s.find(|c: char| !c.is_ascii_digit() && c != '.').unwrap_or(s.len());
|
||||
let num = match s[..split].trim().parse::<f64>() {
|
||||
Ok(v) if v.is_finite() && v > 0.0 => v,
|
||||
_ => return 0,
|
||||
};
|
||||
let unit = s[split..].trim();
|
||||
let mult: f64 = match unit {
|
||||
"" | "B" => 1.0,
|
||||
"KiB" | "Ki" => 1024.0,
|
||||
"MiB" | "Mi" => 1024.0 * 1024.0,
|
||||
"GiB" | "Gi" => 1024.0 * 1024.0 * 1024.0,
|
||||
"TiB" | "Ti" => 1024.0 * 1024.0 * 1024.0 * 1024.0,
|
||||
"PiB" | "Pi" => 1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0,
|
||||
"kB" | "KB" | "K" | "k" => 1000.0,
|
||||
"MB" | "M" => 1000.0 * 1000.0,
|
||||
"GB" | "G" => 1000.0 * 1000.0 * 1000.0,
|
||||
"TB" | "T" => 1000.0 * 1000.0 * 1000.0 * 1000.0,
|
||||
"PB" | "P" => 1000.0 * 1000.0 * 1000.0 * 1000.0 * 1000.0,
|
||||
_ => 1.0,
|
||||
};
|
||||
(num * mult).round().max(0.0) as u64
|
||||
}
|
||||
|
||||
fn parse_pair_bytes(raw: &str) -> (u64, u64) {
|
||||
let mut parts = raw.split('/');
|
||||
let a = parts.next().map(parse_unit_bytes).unwrap_or(0);
|
||||
let b = parts.next().map(parse_unit_bytes).unwrap_or(0);
|
||||
(a, b)
|
||||
}
|
||||
|
||||
/// Parses one line of `docker stats --no-trunc --format '{{json .}}'` (stripping any
|
||||
/// leading ANSI screen-clear control codes Docker CLI emits before each JSON object).
|
||||
pub fn parse_cli_stats_sample(line: &str, timestamp_ms: u64) -> Option<DockerContainerStatsSample> {
|
||||
let start = line.find('{')?;
|
||||
let end = line.rfind('}')?;
|
||||
if end < start {
|
||||
return None;
|
||||
}
|
||||
let raw: RawStats = serde_json::from_str(&line[start..=end]).ok()?;
|
||||
let cpu_percent = raw
|
||||
.cpu_perc
|
||||
.trim()
|
||||
.trim_end_matches('%')
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|v| v.is_finite() && *v >= 0.0)
|
||||
.unwrap_or(0.0);
|
||||
let (mem_used_bytes, mem_limit_bytes) = parse_pair_bytes(&raw.mem_usage);
|
||||
let mem_percent = raw
|
||||
.mem_perc
|
||||
.trim()
|
||||
.trim_end_matches('%')
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|v| v.is_finite() && *v >= 0.0)
|
||||
.unwrap_or_else(|| {
|
||||
if mem_limit_bytes > 0 { (mem_used_bytes as f64 / mem_limit_bytes as f64) * 100.0 } else { 0.0 }
|
||||
});
|
||||
let (net_rx_bytes, net_tx_bytes) = parse_pair_bytes(&raw.net_io);
|
||||
let (disk_read_bytes, disk_write_bytes) = parse_pair_bytes(&raw.block_io);
|
||||
let pids = raw.pids.trim().parse::<u64>().unwrap_or(0);
|
||||
Some(DockerContainerStatsSample {
|
||||
timestamp_ms,
|
||||
cpu_percent,
|
||||
online_cpus: None,
|
||||
mem_used_bytes,
|
||||
mem_limit_bytes,
|
||||
mem_percent,
|
||||
net_rx_bytes,
|
||||
net_tx_bytes,
|
||||
disk_read_bytes,
|
||||
disk_write_bytes,
|
||||
pids,
|
||||
approximate_io: true,
|
||||
})
|
||||
}
|
||||
|
||||
/// `docker info --format` template for daemon / VM CPU and memory capacity.
|
||||
pub const INFO_FORMAT: &str =
|
||||
r#"{"NCPU":{{json .NCPU}},"MemTotal":{{json .MemTotal}},"OperatingSystem":{{json .OperatingSystem}}}"#;
|
||||
@@ -937,4 +1304,100 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(found.id, "running-c");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_rfc3339_timestamps() {
|
||||
assert_eq!(parse_rfc3339_ms("1970-01-01T00:00:00Z"), Some(0));
|
||||
assert_eq!(parse_rfc3339_ms("2026-12-04T18:12:06.250999999Z"), Some(1_796_407_926_250));
|
||||
assert_eq!(parse_rfc3339_ms("2026-12-04T10:12:06.5-08:00"), Some(1_796_407_926_500));
|
||||
assert_eq!(parse_rfc3339_ms("0001-01-01T00:00:00Z"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_engine_stats_frames_for_cgroup_v1_v2_and_stopped_containers() {
|
||||
let mut state = EngineStatsState::default();
|
||||
// cgroup v2 frame with multi-core CPU (> 100%), multiple interfaces, and blkio.
|
||||
let frame = r#"{
|
||||
"read": "2026-12-04T18:12:06.500000000Z",
|
||||
"pids_stats": { "current": 17 },
|
||||
"blkio_stats": {
|
||||
"io_service_bytes_recursive": [
|
||||
{ "major": 259, "minor": 0, "op": "read", "value": 274000000 },
|
||||
{ "major": 259, "minor": 0, "op": "write", "value": 11400000000 },
|
||||
{ "major": 259, "minor": 0, "op": "sync", "value": 999 }
|
||||
]
|
||||
},
|
||||
"cpu_stats": {
|
||||
"cpu_usage": { "total_usage": 250000000 },
|
||||
"system_cpu_usage": 2000000000,
|
||||
"online_cpus": 4
|
||||
},
|
||||
"precpu_stats": {
|
||||
"cpu_usage": { "total_usage": 100000000 },
|
||||
"system_cpu_usage": 1500000000,
|
||||
"online_cpus": 4
|
||||
},
|
||||
"memory_stats": {
|
||||
"usage": 1000000000,
|
||||
"stats": { "inactive_file": 100000000 },
|
||||
"limit": 4000000000
|
||||
},
|
||||
"networks": {
|
||||
"eth0": { "rx_bytes": 280000000, "tx_bytes": 1000000 },
|
||||
"eth1": { "rx_bytes": 1000000, "tx_bytes": 200000 }
|
||||
}
|
||||
}"#;
|
||||
let sample = parse_engine_stats_frame(frame, &mut state, 0).unwrap();
|
||||
assert_eq!(sample.timestamp_ms, 1_796_407_926_500);
|
||||
// (150M / 500M) * 4 * 100 = 120%
|
||||
assert!((sample.cpu_percent - 120.0).abs() < 1e-6);
|
||||
assert_eq!(sample.online_cpus, Some(4));
|
||||
assert_eq!(sample.mem_used_bytes, 900_000_000);
|
||||
assert_eq!(sample.mem_limit_bytes, 4_000_000_000);
|
||||
assert!((sample.mem_percent - 22.5).abs() < 1e-6);
|
||||
assert_eq!(sample.net_rx_bytes, 281_000_000);
|
||||
assert_eq!(sample.net_tx_bytes, 1_200_000);
|
||||
assert_eq!(sample.disk_read_bytes, 274_000_000);
|
||||
assert_eq!(sample.disk_write_bytes, 11_400_000_000);
|
||||
assert_eq!(sample.pids, 17);
|
||||
assert!(!sample.approximate_io);
|
||||
|
||||
// Next frame omits `precpu_stats`: uses saved EngineStatsState from previous frame.
|
||||
let frame2 = r#"{
|
||||
"read": "2026-12-04T18:12:07.500000000Z",
|
||||
"cpu_stats": {
|
||||
"cpu_usage": { "total_usage": 300000000 },
|
||||
"system_cpu_usage": 2500000000,
|
||||
"online_cpus": 4
|
||||
},
|
||||
"memory_stats": {
|
||||
"usage": 500000000,
|
||||
"stats": { "total_inactive_file": 50000000 },
|
||||
"limit": 4000000000
|
||||
}
|
||||
}"#;
|
||||
let sample2 = parse_engine_stats_frame(frame2, &mut state, 0).unwrap();
|
||||
// (50M / 500M) * 4 * 100 = 40%
|
||||
assert!((sample2.cpu_percent - 40.0).abs() < 1e-6);
|
||||
assert_eq!(sample2.mem_used_bytes, 450_000_000);
|
||||
|
||||
// Final stopped-container empty frame is ignored.
|
||||
let stopped = r#"{"read":"0001-01-01T00:00:00Z","cpu_stats":{},"memory_stats":{}}"#;
|
||||
assert_eq!(parse_engine_stats_frame(stopped, &mut state, 1234), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_cli_stats_stream_lines_with_ansi_screen_clear() {
|
||||
let line = "\x1b[2J\x1b[H{\"CPUPerc\":\"12.34%\",\"MemUsage\":\"891.8MiB / 114.3GiB\",\"MemPerc\":\"0.76%\",\"NetIO\":\"281MB / 1.2MB\",\"BlockIO\":\"274MB / 11.4GB\",\"PIDs\":\"17\"}";
|
||||
let sample = parse_cli_stats_sample(line, 42_000).unwrap();
|
||||
assert_eq!(sample.timestamp_ms, 42_000);
|
||||
assert!((sample.cpu_percent - 12.34).abs() < 1e-6);
|
||||
assert!(sample.mem_used_bytes > 930_000_000 && sample.mem_used_bytes < 940_000_000);
|
||||
assert_eq!(sample.net_rx_bytes, 281_000_000);
|
||||
assert_eq!(sample.net_tx_bytes, 1_200_000);
|
||||
assert_eq!(sample.disk_read_bytes, 274_000_000);
|
||||
assert_eq!(sample.disk_write_bytes, 11_400_000_000);
|
||||
assert_eq!(sample.pids, 17);
|
||||
assert!(sample.approximate_io);
|
||||
}
|
||||
}
|
||||
@@ -75,6 +75,10 @@ pub enum Capability {
|
||||
JavaAgent,
|
||||
/// Fork a recorded native agent session into a new task in the open project (API 1.18).
|
||||
Agents,
|
||||
/// Read stdout and stderr lines from Run and Debug consoles in trusted projects (API 1.21).
|
||||
RunOutput,
|
||||
/// Query running IDE language servers for symbol types, definitions, references and outlines (API 1.21).
|
||||
CodeSemantics,
|
||||
}
|
||||
|
||||
/// How a grant is presented (plan 4.2).
|
||||
@@ -92,9 +96,13 @@ pub enum Risk {
|
||||
impl Capability {
|
||||
pub fn risk(&self) -> Risk {
|
||||
match self {
|
||||
Self::ProjectRead | Self::EditorRead | Self::Storage | Self::Events | Self::VcsRead | Self::BuildRead => {
|
||||
Risk::Low
|
||||
}
|
||||
Self::ProjectRead
|
||||
| Self::EditorRead
|
||||
| Self::Storage
|
||||
| Self::Events
|
||||
| Self::VcsRead
|
||||
| Self::BuildRead
|
||||
| Self::CodeSemantics => Risk::Low,
|
||||
Self::EditorWrite
|
||||
| Self::DatabaseSources
|
||||
| Self::DatabaseSchema
|
||||
@@ -107,7 +115,8 @@ impl Capability {
|
||||
| Self::InputEvents
|
||||
| Self::Clipboard
|
||||
| Self::ClipboardRead
|
||||
| Self::Agents => Risk::Medium,
|
||||
| Self::Agents
|
||||
| Self::RunOutput => Risk::Medium,
|
||||
// A trusted project's own files name the programs the IDE starts (its settings, its
|
||||
// build scripts), so writing them is running code.
|
||||
Self::ProjectWrite
|
||||
@@ -175,6 +184,10 @@ impl Capability {
|
||||
Self::FsWrite(path) => format!("Change files under {path}, outside the project"),
|
||||
Self::JavaAgent => "Run code inside the Java applications you start".into(),
|
||||
Self::Agents => "Fork a recorded agent session into a new task in the open project".into(),
|
||||
Self::RunOutput => "Read stdout and stderr output from Run and Debug consoles in trusted projects".into(),
|
||||
Self::CodeSemantics => {
|
||||
"Query language server symbol definitions, types, references and outlines in trusted projects".into()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,6 +333,8 @@ impl fmt::Display for Capability {
|
||||
Self::FsWrite(p) => write!(f, "fs.write:{p}"),
|
||||
Self::JavaAgent => f.write_str("java.agent"),
|
||||
Self::Agents => f.write_str("agents"),
|
||||
Self::RunOutput => f.write_str("run.output"),
|
||||
Self::CodeSemantics => f.write_str("code.semantics"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -406,6 +421,8 @@ impl FromStr for Capability {
|
||||
"clipboard.read" => Self::ClipboardRead,
|
||||
"java.agent" => Self::JavaAgent,
|
||||
"agents" => Self::Agents,
|
||||
"run.output" => Self::RunOutput,
|
||||
"code.semantics" => Self::CodeSemantics,
|
||||
_ => return Err(format!("unknown capability {s:?}")),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -169,6 +169,7 @@ pub const EVENT_KINDS: &[&str] = &[
|
||||
"document-changed",
|
||||
"websocket-ready",
|
||||
"run-started",
|
||||
"run-output",
|
||||
"run-exited",
|
||||
"terminal-exited",
|
||||
"content-tab-action",
|
||||
@@ -186,6 +187,7 @@ pub const EVENT_KINDS: &[&str] = &[
|
||||
"problems-changed",
|
||||
"project-closed",
|
||||
"watched-files-changed",
|
||||
"project-tree-expanded",
|
||||
];
|
||||
|
||||
impl std::fmt::Display for ActivationEvent {
|
||||
@@ -436,6 +438,9 @@ impl Manifest {
|
||||
if matches!(cap, Capability::Agents) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 18)?;
|
||||
}
|
||||
if matches!(cap, Capability::RunOutput | Capability::CodeSemantics) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 21)?;
|
||||
}
|
||||
if matches!(cap, Capability::NetSetting { .. }) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 18)?;
|
||||
}
|
||||
@@ -479,7 +484,8 @@ impl Manifest {
|
||||
{
|
||||
self.needs_api(&format!("`{event}`"), 18)?;
|
||||
}
|
||||
if matches!(event, ActivationEvent::Event(kind) if kind == "run-started") {
|
||||
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) {
|
||||
@@ -701,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");
|
||||
@@ -1122,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"] {
|
||||
|
||||
@@ -1999,6 +1999,7 @@ impl AutomationService {
|
||||
config: auto.config.clone(),
|
||||
isolation,
|
||||
base,
|
||||
worktree_path: None,
|
||||
mcp_overrides: auto.mcp_overrides.clone(),
|
||||
skill_overrides: auto.skill_overrides.clone(),
|
||||
memory_overrides: auto.memory_overrides.clone(),
|
||||
|
||||
@@ -31,6 +31,7 @@ pub mod relay;
|
||||
mod requests;
|
||||
pub mod rpc;
|
||||
pub mod shell_env;
|
||||
pub(crate) mod singleflight;
|
||||
pub mod svn;
|
||||
mod swiftlint;
|
||||
pub mod trust;
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -7,12 +7,12 @@ use ide_agent::registry::{AgentRegistry, RegistryPaths};
|
||||
use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentAutomation, AgentChange, AgentChanges, AgentChangesView,
|
||||
AgentCliInstallResult, AgentCliOffer, AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry,
|
||||
AgentEvent, AgentLoginEvent, AgentMarketplaceBrowseResult, AgentMemoryCatalog, AgentMemoryEntryPolicy,
|
||||
AgentMemoryMode, AgentMemoryOverrides, AgentMemorySettings, AgentModelCatalog, AgentPluginCatalog,
|
||||
AgentPluginPreview, AgentPluginSettings, AgentProbe, AgentPrompt, AgentProvider, AgentProviderMemoryPolicy,
|
||||
AgentQueued, AgentRecoveryReport, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode,
|
||||
AutomationRun, AutomationRunsPage, AutomationSnapshot, AutomationTrigger, AutomationWorkspace, CopilotAuthStatus,
|
||||
CreateAgentMemoryInput, CreateSessionScheduleInput, CustomAgentInput, ExternalSession, InstallAgentPluginRequest,
|
||||
AgentEvent, AgentLoginEvent, AgentMarketplaceBrowseResult, AgentMemoryCatalog, AgentMemoryOverrides,
|
||||
AgentMemorySettings, AgentModelCatalog, AgentPluginCatalog, AgentPluginPreview, AgentPluginSettings, AgentProbe,
|
||||
AgentPrompt, AgentProvider, AgentProviderMemoryPolicy, AgentQueued, AgentRecoveryReport, AgentSkillMode,
|
||||
AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode, AutomationRun, AutomationRunsPage,
|
||||
AutomationSnapshot, AutomationTrigger, AutomationWorkspace, CopilotAuthStatus, CreateAgentMemoryInput,
|
||||
CreateSessionScheduleInput, CustomAgentInput, ExternalSession, InstallAgentPluginRequest,
|
||||
InstallRemoteSkillRequest, Isolation, LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult,
|
||||
McpRegistryPage, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput,
|
||||
RemoteSkillBrowseResult, RemoteSkillPreview, SaveAutomationInput, SessionSchedule, SkillsPolicy,
|
||||
@@ -543,6 +543,19 @@ pub async fn agent_create(host: &Host, window: &str, request: NewAgentTask) -> I
|
||||
project.agents.create(request).await
|
||||
}
|
||||
|
||||
/// Checks out (or creates and checks out) a Git branch in an idle task's working directory.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_checkout_branch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
task: String,
|
||||
branch: String,
|
||||
create: bool,
|
||||
) -> IdeResult<ide_vcs::CheckoutOutcome> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.checkout_branch(&task, &branch, create).await
|
||||
}
|
||||
|
||||
/// Sends a message; while the agent works it is queued, or with `now` it interrupts the turn.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_prompt(host: &Host, window: &str, task: String, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
|
||||
@@ -1793,7 +1806,7 @@ fn memory_settings_layers(
|
||||
}
|
||||
|
||||
fn is_default_memory_settings(s: &AgentMemorySettings) -> bool {
|
||||
s.auto_memory == AutoMemoryMode::Inherit && s.providers.is_empty() && s.entries.is_empty()
|
||||
s.providers.is_empty()
|
||||
}
|
||||
|
||||
fn persist_memory_settings(
|
||||
@@ -1854,81 +1867,53 @@ pub async fn agent_memory_list(host: &Host, window: &str) -> IdeResult<AgentMemo
|
||||
current_memory_catalog(host, project.as_deref()).await
|
||||
}
|
||||
|
||||
/// Sets how memory entry `id` runs in `scope` (`settings.toml` vs `.openidea/settings.toml`),
|
||||
/// never modifying the file on disk.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_memory_set_mode(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
scope: McpScope,
|
||||
mode: AgentMemoryMode,
|
||||
agents: Vec<String>,
|
||||
) -> IdeResult<AgentMemoryCatalog> {
|
||||
let id = id.trim().to_owned();
|
||||
if id.is_empty() {
|
||||
return Err(IdeError::invalid("a memory entry needs an id"));
|
||||
}
|
||||
let clean_agents: Vec<String> = agents.into_iter().map(|a| a.trim().to_owned()).filter(|a| !a.is_empty()).collect();
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
let (mut user, mut workspace) = memory_settings_layers(host, project.as_ref());
|
||||
let apply = |layer: &mut AgentMemorySettings| -> bool {
|
||||
if mode == AgentMemoryMode::Auto && clean_agents.is_empty() {
|
||||
layer.entries.remove(&id).is_some()
|
||||
} else {
|
||||
let next = AgentMemoryEntryPolicy { mode, agents: clean_agents.clone() };
|
||||
layer.entries.insert(id.clone(), next.clone()).as_ref() != Some(&next)
|
||||
}
|
||||
};
|
||||
match scope {
|
||||
McpScope::User => {
|
||||
if apply(&mut user) {
|
||||
persist_memory_settings(host, None, scope, &user)?;
|
||||
}
|
||||
}
|
||||
McpScope::Workspace => {
|
||||
let ws =
|
||||
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace memory"))?;
|
||||
if apply(ws) {
|
||||
let updated = ws.clone();
|
||||
persist_memory_settings(host, project.as_ref(), scope, &updated)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
current_memory_catalog(host, project.as_deref()).await
|
||||
}
|
||||
|
||||
/// Sets the cross-session auto-memory policy (`Inherit`, `ReadWrite`, `ReadOnly`, `Off`)
|
||||
/// globally or for one `provider` in `scope`.
|
||||
/// Sets the cross-session auto-memory policy for one `provider` in `scope`.
|
||||
/// For native-config providers (Hermes), writes the agent's own config file directly.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_memory_set_auto(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
scope: McpScope,
|
||||
provider: Option<String>,
|
||||
provider: String,
|
||||
mode: AutoMemoryMode,
|
||||
) -> IdeResult<AgentMemoryCatalog> {
|
||||
let raw_provider = provider.trim();
|
||||
if raw_provider.is_empty() {
|
||||
return Err(IdeError::invalid("a provider id is required to configure auto-memory"));
|
||||
}
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
let base = project.as_ref().map(|p| p.agents.base_provider_id(raw_provider));
|
||||
let resolved_provider = base.as_deref().unwrap_or(raw_provider);
|
||||
let supported = ide_agent::memory::supported_auto_memory_modes(resolved_provider);
|
||||
if supported.is_empty() {
|
||||
return Err(IdeError::invalid(format!("Auto-memory control is not supported for `{raw_provider}`")));
|
||||
}
|
||||
if !supported.contains(&mode) {
|
||||
return Err(IdeError::invalid(format!("Auto-memory mode `{mode:?}` is not supported for `{raw_provider}`")));
|
||||
}
|
||||
|
||||
if ide_agent::memory::is_native_config_auto_memory(resolved_provider) {
|
||||
let provider_owned = resolved_provider.to_owned();
|
||||
let home = host.home_dir();
|
||||
blocking(move || {
|
||||
ide_agent::memory::set_hermes_auto_memory(&provider_owned, mode, home.as_deref()).map_err(IdeError::invalid)
|
||||
})
|
||||
.await?;
|
||||
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
|
||||
for p in host.projects() {
|
||||
p.sink.emit(event.clone());
|
||||
}
|
||||
return current_memory_catalog(host, project.as_deref()).await;
|
||||
}
|
||||
|
||||
let key = ide_agent::memory::provider_key(resolved_provider).to_owned();
|
||||
let (mut user, mut workspace) = memory_settings_layers(host, project.as_ref());
|
||||
let prov_key = provider.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(|s| {
|
||||
let base = project.as_ref().map(|p| p.agents.base_provider_id(s));
|
||||
ide_agent::memory::normalize_provider_id(base.as_deref().unwrap_or(s)).to_owned()
|
||||
});
|
||||
let apply = |layer: &mut AgentMemorySettings| -> bool {
|
||||
match &prov_key {
|
||||
None => {
|
||||
let changed = layer.auto_memory != mode;
|
||||
layer.auto_memory = mode;
|
||||
changed
|
||||
}
|
||||
Some(key) => {
|
||||
if mode == AutoMemoryMode::Inherit {
|
||||
layer.providers.remove(key).is_some()
|
||||
} else {
|
||||
let next = AgentProviderMemoryPolicy { auto_memory: mode };
|
||||
layer.providers.insert(key.clone(), next.clone()).as_ref() != Some(&next)
|
||||
}
|
||||
}
|
||||
if mode == AutoMemoryMode::Inherit {
|
||||
layer.providers.remove(&key).is_some()
|
||||
} else {
|
||||
let next = AgentProviderMemoryPolicy { auto_memory: mode };
|
||||
layer.providers.insert(key.clone(), next.clone()).as_ref() != Some(&next)
|
||||
}
|
||||
};
|
||||
match scope {
|
||||
@@ -2969,6 +2954,7 @@ ide_command::domain!(
|
||||
agent_automation_save,
|
||||
agent_automation_set_enabled,
|
||||
agent_automation_snapshot,
|
||||
agent_checkout_branch,
|
||||
agent_cli_update_check,
|
||||
agent_commands,
|
||||
agent_copilot_auth_status,
|
||||
@@ -3004,7 +2990,6 @@ ide_command::domain!(
|
||||
agent_memory_promote,
|
||||
agent_memory_reset_provider,
|
||||
agent_memory_set_auto,
|
||||
agent_memory_set_mode,
|
||||
agent_plugins_add_marketplace,
|
||||
agent_plugins_browse_marketplace,
|
||||
agent_plugins_install,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Maven / Gradle tool windows (the build model and its background sync) and
|
||||
//! Build › Build Project (compiling with the project's build system).
|
||||
mod source_encoding;
|
||||
pub(super) mod workspace;
|
||||
|
||||
use super::dependencies::{MavenCentralArtifacts, MavenCentralGroups, MavenCentralVersions};
|
||||
@@ -135,8 +136,33 @@ fn load_synced(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
|
||||
)
|
||||
}
|
||||
|
||||
/// Report directories are searched only in the projects of the launched build, not
|
||||
/// every nested build under the opened project. Maven's reactor may include siblings.
|
||||
pub(super) fn junit_report_modules(scope: &workspace::Scope, cwd: &Path, tool: BuildTool) -> Vec<PathBuf> {
|
||||
let cwd = ide_core::project_roots::resolve(&scope.root, cwd);
|
||||
match tool {
|
||||
BuildTool::Maven => {
|
||||
let activation = ide_build::maven::ProfileActivation::new(
|
||||
&scope.root,
|
||||
&scope.settings.languages.java.maven,
|
||||
&ide_build::maven_profiles(&scope.cache),
|
||||
maven_jdk_version(&scope.root, &scope.settings),
|
||||
);
|
||||
ide_build::maven::reactor_member_dirs(&cwd, &activation)
|
||||
}
|
||||
BuildTool::Gradle => {
|
||||
let model = load_synced(&scope.root, &scope.cache, &scope.settings);
|
||||
model
|
||||
.gradle_for_module(&scope.root, &cwd)
|
||||
.into_iter()
|
||||
.flat_map(|build| build.projects.iter().map(|p| scope.root.join(&p.dir)))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The JDK `<activation><jdk>` profiles are matched against.
|
||||
fn maven_jdk_version(root: &Path, settings: &Settings) -> Option<u32> {
|
||||
pub(super) fn maven_jdk_version(root: &Path, settings: &Settings) -> Option<u32> {
|
||||
ide_sdk::apply::maven_jdk(root, settings, None).map(|jdk| jdk.major)
|
||||
}
|
||||
|
||||
@@ -168,7 +194,8 @@ fn sync_options(
|
||||
/// POM navigation follows the same profile choices as the last Maven sync and
|
||||
/// resolves JDK-activated profiles with the project's selected Maven runtime.
|
||||
fn pom_navigation_options(project: &Project, settings: &Settings) -> PomNavigationOptions {
|
||||
let mut profiles = settings.languages.java.maven.profiles(&[]);
|
||||
let maven = &settings.languages.java.maven;
|
||||
let mut profiles = ide_build::maven::ProfileActivation::new(&project.root, maven, &[], None).profiles;
|
||||
for profile in ide_build::maven_profiles(&project.build_cache_dir()) {
|
||||
if !profiles.contains(&profile) {
|
||||
profiles.push(profile);
|
||||
@@ -182,13 +209,51 @@ fn pom_navigation_options(project: &Project, settings: &Settings) -> PomNavigati
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a CMake configuration's Visual Studio toolchain, when the toolchain it names
|
||||
/// (empty = the default) is one. vcvarsall runs here, at launch time, not during detection.
|
||||
pub(super) fn apply_cmake_toolchain(config: &mut ide_run::RunConfig, settings: &Settings) -> IdeResult<()> {
|
||||
let Some(name) = config.extras.params.get("cmakeToolchain") else { return Ok(()) };
|
||||
let Some(toolchain) = ide_run::cmake_toolchain::find(&settings.toolchains, name) else { return Ok(()) };
|
||||
if toolchain.kind == ide_core::settings::ToolchainKind::VisualStudio {
|
||||
ide_sdk::msvc::apply_toolchain(&mut config.env, toolchain)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Build Project of a CMake project builds with its active profile, so with that profile's
|
||||
/// Visual Studio environment when its toolchain is one.
|
||||
fn apply_cmake_profile_toolchain(plan: &mut compile::BuildPlan, root: &Path, settings: &Settings) -> IdeResult<()> {
|
||||
if plan.system != compile::BuildSystem::CMake {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(profile) =
|
||||
ide_run::cmake_profiles(root, &settings.cmake, &settings.toolchains).and_then(|p| p.into_iter().next())
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(toolchain) = ide_run::cmake_toolchain::find(&settings.toolchains, &profile.toolchain) else {
|
||||
return Ok(());
|
||||
};
|
||||
if toolchain.kind != ide_core::settings::ToolchainKind::VisualStudio {
|
||||
return Ok(());
|
||||
}
|
||||
for step in &mut plan.steps {
|
||||
ide_sdk::msvc::apply_toolchain(&mut step.env, toolchain)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Build and Run use the same selected toolchain and module-local runtime discovery.
|
||||
fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings) -> compile::BuildPlan {
|
||||
fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings) -> IdeResult<compile::BuildPlan> {
|
||||
if plan.system == compile::BuildSystem::CMake {
|
||||
apply_cmake_profile_toolchain(&mut plan, root, settings)?;
|
||||
return Ok(plan);
|
||||
}
|
||||
let kind = match plan.system {
|
||||
compile::BuildSystem::Cargo => "cargo",
|
||||
compile::BuildSystem::Go => "go",
|
||||
compile::BuildSystem::TypeScript => "npm",
|
||||
_ => return plan,
|
||||
_ => return Ok(plan),
|
||||
};
|
||||
for step in &mut plan.steps {
|
||||
let mut config = ide_run::RunConfig {
|
||||
@@ -215,7 +280,7 @@ fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings)
|
||||
step.args = config.args;
|
||||
step.env = config.env;
|
||||
}
|
||||
plan
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
/// `model` building with the Maven profiles of the last sync (`-P`), as Maven runs from
|
||||
@@ -236,7 +301,30 @@ pub async fn build_model(host: &Host, window: &str) -> IdeResult<BuildModel> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let config = host.config_dir.clone();
|
||||
blocking(move || workspace::load_project(&project, &config)).await
|
||||
blocking(move || load_project(&project, &config)).await
|
||||
}
|
||||
|
||||
/// The project's build model. Each load hands the source encodings of its Maven modules
|
||||
/// to the document layer, so the editor follows the POMs as they are now.
|
||||
fn load_project(project: &Project, config: &Path) -> IdeResult<BuildModel> {
|
||||
let model = workspace::load_project(project, config)?;
|
||||
apply_source_encodings(project, &model);
|
||||
Ok(model)
|
||||
}
|
||||
|
||||
/// The source encodings for a project that is opening. A project without a Maven build
|
||||
/// has none, so its build model is not loaded for them.
|
||||
pub(crate) fn load_source_encodings(project: &Project, config: &Path) -> IdeResult<()> {
|
||||
let scopes = workspace::scopes(project, config)?;
|
||||
let maven = |s: &workspace::Scope| ide_build::maven::has_projects(&s.root, &s.settings.languages.java.maven);
|
||||
if scopes.iter().any(maven) {
|
||||
apply_source_encodings(project, &workspace::load_scopes(&project.root, &scopes));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_source_encodings(project: &Project, model: &BuildModel) {
|
||||
project.documents.set_pom_encodings(source_encoding::pom_encodings(&project.root, model));
|
||||
}
|
||||
|
||||
/// Settings › Build Tools › Maven: the local repository the field's placeholder shows —
|
||||
@@ -403,15 +491,32 @@ pub async fn toolchain_check(toolchain: ide_core::settings::Toolchain) -> IdeRes
|
||||
_ => tools.debugger.clone(),
|
||||
}
|
||||
};
|
||||
let search = match &tools.path {
|
||||
Some(bin) => std::env::join_paths(
|
||||
std::iter::once(bin.clone()).chain(std::env::split_paths(&ide_core::tool_path::search_path())),
|
||||
)
|
||||
.unwrap_or_else(|_| ide_core::tool_path::search_path()),
|
||||
None => ide_core::tool_path::search_path(),
|
||||
let system_path = ide_core::tool_path::search_path();
|
||||
let visual_studio_path = if toolchain.kind == ide_core::settings::ToolchainKind::VisualStudio {
|
||||
let tc = toolchain.clone();
|
||||
blocking(move || {
|
||||
let mut env = std::collections::BTreeMap::new();
|
||||
Ok(ide_sdk::msvc::apply_toolchain(&mut env, &tc)
|
||||
.ok()
|
||||
.and_then(|()| env.into_iter().find(|(name, _)| name.eq_ignore_ascii_case("path")).map(|(_, v)| v)))
|
||||
})
|
||||
.await?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let search = match (&tools.path, visual_studio_path) {
|
||||
(Some(bin), _) => std::env::join_paths(std::iter::once(bin.clone()).chain(std::env::split_paths(&system_path)))
|
||||
.unwrap_or_else(|_| system_path.clone()),
|
||||
(None, Some(path)) => std::ffi::OsString::from(path),
|
||||
(None, None) => system_path.clone(),
|
||||
};
|
||||
let fallbacks = if toolchain.kind == ide_core::settings::ToolchainKind::VisualStudio {
|
||||
ide_run::cmake_toolchain::VISUAL_STUDIO_FALLBACKS
|
||||
} else {
|
||||
ide_run::cmake_toolchain::FALLBACKS
|
||||
};
|
||||
let mut out = ToolchainCheck::new();
|
||||
for (key, names) in ide_run::cmake_toolchain::FALLBACKS {
|
||||
for (key, names) in fallbacks {
|
||||
let path = chosen(key)
|
||||
.map(|p| {
|
||||
// A bare name ("clang++") is looked up like CMake would.
|
||||
@@ -427,11 +532,11 @@ pub async fn toolchain_check(toolchain: ide_core::settings::Toolchain) -> IdeRes
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Settings › Toolchains: a toolchain for each MinGW / MSYS2 install found (Windows).
|
||||
/// Settings › Toolchains: toolchains for the MinGW / MSYS2 and Visual Studio installs found (Windows).
|
||||
#[command(trust = always)]
|
||||
pub async fn toolchains_detect() -> IdeResult<Vec<ide_core::settings::Toolchain>> {
|
||||
blocking(|| {
|
||||
Ok(ide_run::cmake_toolchain::detect_mingw()
|
||||
let mut found: Vec<_> = ide_run::cmake_toolchain::detect_mingw()
|
||||
.into_iter()
|
||||
.map(|dir| {
|
||||
let name = match dir.parent().and_then(|p| p.file_name()) {
|
||||
@@ -448,7 +553,9 @@ pub async fn toolchains_detect() -> IdeResult<Vec<ide_core::settings::Toolchain>
|
||||
..Default::default()
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
.collect();
|
||||
found.extend(ide_sdk::msvc::detect_toolchains());
|
||||
Ok(found)
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -643,6 +750,7 @@ pub async fn build_sync(
|
||||
}
|
||||
let scopes = workspace::scopes(&p, &config)?;
|
||||
let model = workspace::load_scopes(&p.root, &scopes);
|
||||
apply_source_encodings(&p, &model);
|
||||
let updates = workspace::update_files(&p.root, &scopes, &model, tool);
|
||||
let snapshots = if tool == BuildTool::Maven && !offline {
|
||||
cached_maven_sources(&model, scopes, &p.root, build_dir.as_deref())
|
||||
@@ -668,6 +776,11 @@ pub async fn build_sync(
|
||||
{
|
||||
bridge.configure_maven(offline, bridge_profiles.clone());
|
||||
}
|
||||
if tool == BuildTool::Maven && model.maven.is_some() {
|
||||
// Sources a generator wrote since the language server last heard of them.
|
||||
let (lsp, root) = (project.lsp.clone(), project.root.clone());
|
||||
tokio::spawn(async move { lsp.notify_generated_sources(&root).await });
|
||||
}
|
||||
let lsp = project.lsp.clone();
|
||||
let documents = project.documents.clone();
|
||||
if snapshots.is_empty() {
|
||||
@@ -1159,12 +1272,19 @@ pub(crate) fn structure_inputs(
|
||||
(ps, roots, jdk)
|
||||
}
|
||||
|
||||
fn cmake_plan(root: &Path, kind: BuildKind, configs: &[ide_run::RunConfig], id: &str) -> IdeResult<compile::BuildPlan> {
|
||||
fn cmake_plan(
|
||||
root: &Path,
|
||||
kind: BuildKind,
|
||||
configs: &[ide_run::RunConfig],
|
||||
id: &str,
|
||||
settings: &Settings,
|
||||
) -> IdeResult<compile::BuildPlan> {
|
||||
let commands = ide_run::cmake_build_configs(configs, id)?;
|
||||
let title = commands.last().map(|c| c.name.clone()).unwrap_or_default();
|
||||
let mut steps = Vec::new();
|
||||
for mut config in commands {
|
||||
let cwd = ide_core::project_roots::resolve(root, config.cwd.as_deref().unwrap_or(Path::new("")));
|
||||
apply_cmake_toolchain(&mut config, settings)?;
|
||||
ide_run::prepare_cmake(&config, &cwd)?;
|
||||
if kind == BuildKind::Rebuild && config.args.first().is_some_and(|a| a == "--build") {
|
||||
config.args.insert(2, "--clean-first".into());
|
||||
@@ -1247,7 +1367,7 @@ pub async fn build_run(
|
||||
)?,
|
||||
&root,
|
||||
&settings,
|
||||
);
|
||||
)?;
|
||||
let _ = on_event.send(BuildEvent::Started { system: plan.system, title: plan.title.clone() });
|
||||
let _ = on_event.send(BuildEvent::Output {
|
||||
text: "Up to date: no changes, build skipped.\n".into(),
|
||||
@@ -1275,7 +1395,7 @@ pub async fn build_run(
|
||||
let plan = if let Some(id) = cmake {
|
||||
launch_caches.push(cache.clone());
|
||||
let configs = super::run::project_configs(&root, &settings, &config_dir)?;
|
||||
cmake_plan(&root, kind, &configs, &id)?
|
||||
cmake_plan(&root, kind, &configs, &id, &settings)?
|
||||
} else if let Some(workspace) = ide_workspace::workspace::Workspace::load(&root)? {
|
||||
let mut combined: Option<compile::BuildPlan> = None;
|
||||
for member in workspace.projects.iter().filter(|p| file.as_ref().is_none_or(|f| f.starts_with(p))) {
|
||||
@@ -1295,7 +1415,7 @@ pub async fn build_run(
|
||||
)?,
|
||||
member,
|
||||
&settings,
|
||||
);
|
||||
)?;
|
||||
match &mut combined {
|
||||
Some(combined) => combined.steps.extend(plan.steps),
|
||||
None => combined = Some(plan),
|
||||
@@ -1316,7 +1436,7 @@ pub async fn build_run(
|
||||
Some(&cache),
|
||||
&token,
|
||||
) {
|
||||
Ok(plan) => prepare_plan(plan, &root, &settings),
|
||||
Ok(plan) => prepare_plan(plan, &root, &settings)?,
|
||||
// No build tool: a Java project builds from its Project Structure.
|
||||
Err(e) if e.kind == ide_core::error::ErrorKind::NotFound => {
|
||||
let (ps, roots, jdk) = structure_inputs(&root, &settings, &detected);
|
||||
@@ -1656,6 +1776,128 @@ async fn run_dotnet_plan(
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod junit_report_module_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn maven_reports_use_the_declared_reactor_not_every_nested_pom() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("workspace");
|
||||
let scope = workspace::Scope { root: root.clone(), cache: base.join("cache"), settings: Settings::default() };
|
||||
let write = |dir: &Path, contents: &str| {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
std::fs::write(dir.join("pom.xml"), format!("<project><artifactId>demo</artifactId>{contents}</project>"))
|
||||
.unwrap();
|
||||
};
|
||||
let module = root.join("module");
|
||||
let nested = module.join("nested");
|
||||
let sibling = base.join("sibling");
|
||||
let profile = root.join("profile");
|
||||
write(
|
||||
&root,
|
||||
"<modules><module>module</module><module>../sibling</module></modules>
|
||||
<profiles><profile><id>extra</id><modules><module>profile</module></modules></profile></profiles>",
|
||||
);
|
||||
write(&module, "<modules><module>nested</module></modules>");
|
||||
for dir in [&nested, &sibling, &profile, &root.join("unrelated")] {
|
||||
write(dir, "");
|
||||
}
|
||||
let modules = |dir: &Path| {
|
||||
let mut modules = junit_report_modules(&scope, dir, BuildTool::Maven);
|
||||
modules.sort();
|
||||
modules
|
||||
};
|
||||
assert_eq!(modules(&root), [sibling.clone(), root.clone(), module.clone(), nested.clone()]);
|
||||
assert_eq!(modules(&module), [module.clone(), nested.clone()]);
|
||||
ide_build::save_maven_profiles(&scope.cache, &["extra".into()]).unwrap();
|
||||
assert_eq!(modules(&root), [sibling, root, module, nested, profile]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_reports_cover_the_modules_of_profiles_maven_turns_on_by_itself() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("workspace");
|
||||
let jdk = base.join("jdk-21");
|
||||
std::fs::create_dir_all(jdk.join("bin")).unwrap();
|
||||
std::fs::write(jdk.join("bin").join(if cfg!(windows) { "java.exe" } else { "java" }), "").unwrap();
|
||||
std::fs::write(jdk.join("release"), "JAVA_VERSION=\"21.0.4\"\n").unwrap();
|
||||
let mut settings = Settings::default();
|
||||
settings.languages.java.maven.runner_jre = jdk.to_string_lossy().into_owned();
|
||||
settings.languages.java.maven.user_settings = base.join("settings.xml").to_string_lossy().into_owned();
|
||||
let scope = workspace::Scope { root: root.clone(), cache: base.join("cache"), settings };
|
||||
let family = if cfg!(windows) {
|
||||
"windows"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"mac"
|
||||
} else {
|
||||
"unix"
|
||||
};
|
||||
let profile = |id: &str, activation: &str| {
|
||||
format!("<profile><id>{id}</id>{activation}<modules><module>{id}</module></modules></profile>")
|
||||
};
|
||||
let profiles = [
|
||||
profile("extras", "<activation><property><name>!quick</name></property></activation>"),
|
||||
profile("native", &format!("<activation><os><family>{family}</family></os></activation>")),
|
||||
profile("docs", "<activation><file><exists>${basedir}/docs-src</exists></file></activation>"),
|
||||
profile("modern", "<activation><jdk>[17,)</jdk></activation>"),
|
||||
profile("it", ""),
|
||||
];
|
||||
std::fs::create_dir_all(root.join("docs-src")).unwrap();
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
format!(
|
||||
"<project><artifactId>root</artifactId><modules><module>core</module></modules><profiles>{}</profiles></project>",
|
||||
profiles.concat()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
for module in ["core", "extras", "native", "docs", "modern", "it"] {
|
||||
std::fs::create_dir_all(root.join(module)).unwrap();
|
||||
std::fs::write(root.join(module).join("pom.xml"), "<project><artifactId>m</artifactId></project>").unwrap();
|
||||
}
|
||||
std::fs::create_dir_all(root.join(".mvn")).unwrap();
|
||||
std::fs::write(root.join(".mvn/maven.config"), "-Pit\n").unwrap();
|
||||
|
||||
let mut modules = junit_report_modules(&scope, &root, BuildTool::Maven);
|
||||
modules.sort();
|
||||
let mut expected: Vec<PathBuf> =
|
||||
["core", "docs", "extras", "it", "modern", "native"].iter().map(|m| root.join(m)).collect();
|
||||
expected.push(root);
|
||||
expected.sort();
|
||||
assert_eq!(modules, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradle_reports_use_the_owning_build_not_independent_linked_builds() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(temp.path()).unwrap();
|
||||
let independent = root.join("independent");
|
||||
let child = root.join("child");
|
||||
let nested = child.join("nested");
|
||||
for dir in [&root, &independent, &child, &nested] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
std::fs::write(dir.join("build.gradle"), "").unwrap();
|
||||
}
|
||||
std::fs::write(root.join("settings.gradle"), "include ':child', ':child:nested'").unwrap();
|
||||
std::fs::write(independent.join("settings.gradle"), "rootProject.name = 'other'").unwrap();
|
||||
let mut settings = Settings::default();
|
||||
settings.languages.java.gradle.linked_projects =
|
||||
Some(vec![root.to_string_lossy().into_owned(), independent.to_string_lossy().into_owned()]);
|
||||
let scope = workspace::Scope { root: root.clone(), cache: root.join("cache"), settings };
|
||||
let modules = |dir: &Path| {
|
||||
let mut modules = junit_report_modules(&scope, dir, BuildTool::Gradle);
|
||||
modules.sort();
|
||||
modules
|
||||
};
|
||||
assert_eq!(modules(&root), [root.clone(), child.clone(), nested.clone()]);
|
||||
assert_eq!(modules(&child), [root, child, nested]);
|
||||
assert_eq!(modules(&independent), [independent]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod build_tool_settings_tests {
|
||||
use super::*;
|
||||
@@ -1683,7 +1925,7 @@ mod build_tool_settings_tests {
|
||||
});
|
||||
let configs = [configure, build];
|
||||
for kind in [BuildKind::Build, BuildKind::Rebuild] {
|
||||
let plan = cmake_plan(root.path(), kind, &configs, "target").unwrap();
|
||||
let plan = cmake_plan(root.path(), kind, &configs, "target", &Settings::default()).unwrap();
|
||||
assert_eq!(plan.system, compile::BuildSystem::CMake);
|
||||
assert_eq!(plan.steps.len(), 2);
|
||||
assert_eq!(plan.steps[0].args, configs[0].args);
|
||||
@@ -1740,7 +1982,8 @@ mod build_tool_settings_tests {
|
||||
.unwrap(),
|
||||
root,
|
||||
&settings,
|
||||
);
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(plan.steps[0].program, program);
|
||||
assert_eq!(plan.steps[0].cwd, dir);
|
||||
if marker == "go.mod" {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Maven's `project.build.sourceEncoding`, handed to the document layer as the encoding
|
||||
//! of each module's `src` folder.
|
||||
use ide_build::BuildModel;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// `src` folder and WHATWG label of every Maven project of `model` that names a source
|
||||
/// encoding the editor can apply. The module folder itself is left out: its `pom.xml`
|
||||
/// declares its own encoding, and `target` is not source.
|
||||
pub(super) fn pom_encodings(root: &Path, model: &BuildModel) -> Vec<(PathBuf, String)> {
|
||||
let Some(maven) = &model.maven else { return Vec::new() };
|
||||
maven
|
||||
.projects
|
||||
.iter()
|
||||
.filter_map(|p| {
|
||||
let name = p.source_encoding.as_deref()?;
|
||||
let Some(label) = whatwg_label(name) else {
|
||||
tracing::info!("{}: project.build.sourceEncoding {name:?} is not applied to its sources", p.pom);
|
||||
return None;
|
||||
};
|
||||
let dir = Path::new(&p.dir);
|
||||
let module = if dir.is_absolute() { dir.to_path_buf() } else { root.join(dir) };
|
||||
Some((module.join("src"), label))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A POM spells a Java charset name (`ISO-8859-15`, `Cp1252`, `ISO8859_15`). `None` for one
|
||||
/// without a codec here, or in which ASCII text is not the same bytes (UTF-16).
|
||||
fn whatwg_label(java_name: &str) -> Option<String> {
|
||||
let name = java_name.trim().to_ascii_lowercase();
|
||||
let encoding = encoding_rs::Encoding::for_label(name.as_bytes())
|
||||
.or_else(|| encoding_rs::Encoding::for_label(name.replace('_', "-").as_bytes()))?;
|
||||
encoding.is_ascii_compatible().then(|| encoding.name().to_ascii_lowercase())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn java_charset_names_become_whatwg_labels() {
|
||||
for (java, label) in [
|
||||
("ISO-8859-15", Some("iso-8859-15")),
|
||||
("ISO8859_15", Some("iso-8859-15")),
|
||||
("iso-8859-15", Some("iso-8859-15")),
|
||||
("Cp1252", Some("windows-1252")),
|
||||
("windows-1252", Some("windows-1252")),
|
||||
("ISO-8859-1", Some("windows-1252")),
|
||||
("ISO8859_1", Some("windows-1252")),
|
||||
("UTF-8", Some("utf-8")),
|
||||
("UTF8", Some("utf-8")),
|
||||
(" GBK ", Some("gbk")),
|
||||
("EUC_JP", Some("euc-jp")),
|
||||
("MS932", Some("shift_jis")),
|
||||
("UTF-16", None),
|
||||
("Cp850", None),
|
||||
("", None),
|
||||
("X-NO-SUCH-CHARSET", None),
|
||||
] {
|
||||
assert_eq!(whatwg_label(java).as_deref(), label, "{java}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -637,6 +637,10 @@ async fn execute_statements(
|
||||
) -> IdeResult<()> {
|
||||
let db = host.project(window)?.db.clone();
|
||||
let (cancel, console) = console_request(host, window, request, console, console_manual)?;
|
||||
// Without a console, several statements still share one connection and its session: what one
|
||||
// sets, locks or begins holds for the next, and none of it is left on the pool afterwards.
|
||||
let run = format!("\0script {request}");
|
||||
let script = (console.is_none() && statements.len() > 1).then(|| ConsoleId::script(window, &run));
|
||||
let result = async {
|
||||
db.validate_console_script(id, &statements, console).await?;
|
||||
for (index, statement) in statements.into_iter().enumerate() {
|
||||
@@ -652,7 +656,7 @@ async fn execute_statements(
|
||||
max_rows.max(1) as usize,
|
||||
&cancel,
|
||||
schema,
|
||||
console,
|
||||
console.or(script),
|
||||
)
|
||||
.await
|
||||
{
|
||||
@@ -676,6 +680,12 @@ async fn execute_statements(
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
// Rolls back what the script left open and closes its connection.
|
||||
if let Some(script) = script
|
||||
&& let Err(error) = db.release_target_console(script, Some(id)).await
|
||||
{
|
||||
tracing::warn!("closing the connection of a script on {id}: {}", error.message);
|
||||
}
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
@@ -1175,6 +1185,162 @@ mod tests {
|
||||
assert_eq!(outcomes[0].result.as_ref().unwrap().rows, vec![vec![Some("0".into())]]);
|
||||
}
|
||||
|
||||
/// What Run SQL Script sends: every statement of `script` in one run, without a console.
|
||||
async fn run_script(host: &Host, request: u32, id: &str, driver: DbDriver, script: &str) -> Vec<StatementOutcome> {
|
||||
let statements = ide_db::split::split(script, driver);
|
||||
db_execute(host, "main", RequestId(request), id.into(), statements, 0, 10, None, None, None, None)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn errors(outcomes: &[StatementOutcome]) -> Vec<String> {
|
||||
outcomes.iter().filter_map(|o| o.error.clone()).collect()
|
||||
}
|
||||
|
||||
fn cell(outcome: &StatementOutcome) -> Option<String> {
|
||||
outcome.result.as_ref().and_then(|r| r.rows.first()?.first()?.clone())
|
||||
}
|
||||
|
||||
/// Leaves `n` idle connections in `id`'s pool, as the database tree's loading does.
|
||||
async fn warm_pool(host: &Host, id: &str, n: usize) {
|
||||
let pool = host.project("main").unwrap().db.pool(id).await.unwrap();
|
||||
let mut held = Vec::new();
|
||||
for _ in 0..n {
|
||||
held.push(ide_db::Held::acquire(&pool).await.unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_script_runs_its_statements_on_one_connection() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let host = host_with_sqlite(&temp).await;
|
||||
let id = "test";
|
||||
run_script(&host, 1, id, DbDriver::Sqlite, "CREATE TABLE items (n INTEGER)").await;
|
||||
warm_pool(&host, id, 4).await;
|
||||
// A temporary table, a transaction and a setting belong to their connection.
|
||||
let outcomes = run_script(
|
||||
&host,
|
||||
2,
|
||||
id,
|
||||
DbDriver::Sqlite,
|
||||
"CREATE TEMP TABLE scratch (n INTEGER); INSERT INTO scratch VALUES (7); BEGIN; \
|
||||
INSERT INTO items SELECT n FROM scratch; COMMIT; PRAGMA cache_size = -1234; PRAGMA cache_size",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(errors(&outcomes), Vec::<String>::new());
|
||||
assert_eq!(cell(outcomes.last().unwrap()).as_deref(), Some("-1234"));
|
||||
let items = run_script(&host, 3, id, DbDriver::Sqlite, "SELECT n FROM items").await;
|
||||
assert_eq!(cell(&items[0]).as_deref(), Some("7"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_script_leaves_no_session_state_on_the_pool() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let host = host_with_sqlite(&temp).await;
|
||||
let id = "test";
|
||||
warm_pool(&host, id, 4).await;
|
||||
let script = "PRAGMA cache_size = -1234; CREATE TEMP TABLE leftover (n INTEGER)";
|
||||
assert_eq!(errors(&run_script(&host, 1, id, DbDriver::Sqlite, script).await), Vec::<String>::new());
|
||||
// Each idle connection of the pool serves one of these in turn.
|
||||
for request in 2..12 {
|
||||
let probe = "PRAGMA cache_size; SELECT count(*) FROM sqlite_temp_master";
|
||||
let outcomes = run_script(&host, request, id, DbDriver::Sqlite, probe).await;
|
||||
assert_ne!(cell(&outcomes[0]).as_deref(), Some("-1234"), "request {request}");
|
||||
assert_eq!(cell(&outcomes[1]).as_deref(), Some("0"), "request {request}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A data source `id` on the server that `variable` (`host:port:user:password`) names.
|
||||
async fn server_source(host: &Host, variable: &str, id: &str, driver: DbDriver, database: &str) -> bool {
|
||||
let Ok(server) = std::env::var(variable) else { return false };
|
||||
let mut parts = server.splitn(4, ':');
|
||||
let source = DataSource {
|
||||
id: id.into(),
|
||||
name: id.into(),
|
||||
driver,
|
||||
host: parts.next().unwrap().into(),
|
||||
port: Some(parts.next().unwrap().parse().unwrap()),
|
||||
user: parts.next().unwrap().into(),
|
||||
database: database.into(),
|
||||
..Default::default()
|
||||
};
|
||||
// The SQL Server test containers have no certificate the driver accepts.
|
||||
let source = if driver == DbDriver::SqlServer {
|
||||
DataSource { ssl: ide_db::DbSslMode::Disable, ..source }
|
||||
} else {
|
||||
source
|
||||
};
|
||||
let mut sources = host.project("main").unwrap().db.sources().unwrap();
|
||||
sources.push(source);
|
||||
db_save_sources(host, "main", sources).await.unwrap();
|
||||
db_set_password(host, "main", id.into(), parts.next().map(str::to_owned), false).await.unwrap();
|
||||
true
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn server_scripts_keep_their_settings_to_themselves() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let host = host_with_sqlite(&temp).await;
|
||||
let mut failures = Vec::new();
|
||||
for (variable, driver, database, set, show, value) in [
|
||||
("OPENIDEA_TEST_POSTGRES", DbDriver::Postgres, "postgres", "SET work_mem = '7MB'", "SHOW work_mem", "7MB"),
|
||||
(
|
||||
"OPENIDEA_TEST_MYSQL",
|
||||
DbDriver::Mysql,
|
||||
"",
|
||||
"SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION'",
|
||||
"SELECT @@SESSION.sql_mode",
|
||||
"NO_ENGINE_SUBSTITUTION",
|
||||
),
|
||||
("OPENIDEA_TEST_SQLSERVER", DbDriver::SqlServer, "tempdb", "SET DATEFIRST 3", "SELECT @@DATEFIRST", "3"),
|
||||
] {
|
||||
let id = format!("{driver:?}");
|
||||
if !server_source(&host, variable, &id, driver, database).await {
|
||||
continue;
|
||||
}
|
||||
warm_pool(&host, &id, 4).await;
|
||||
let outcomes = run_script(&host, 1, &id, driver, &format!("{set};\n{show}")).await;
|
||||
assert_eq!(errors(&outcomes), Vec::<String>::new(), "{driver:?}");
|
||||
let next = cell(&outcomes[1]);
|
||||
// Each idle connection of the pool serves one of these in turn.
|
||||
let mut leaked = Vec::new();
|
||||
for request in 2..12 {
|
||||
if cell(&run_script(&host, request, &id, driver, show).await[0]).as_deref() == Some(value) {
|
||||
leaked.push(request);
|
||||
}
|
||||
}
|
||||
if next.as_deref() != Some(value) || !leaked.is_empty() {
|
||||
failures.push(format!(
|
||||
"{driver:?}: the script's next statement got {next:?}; requests {leaked:?} got {value}"
|
||||
));
|
||||
}
|
||||
}
|
||||
assert_eq!(failures, Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_mysql_script_inserts_into_the_table_it_locked() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let host = host_with_sqlite(&temp).await;
|
||||
if !server_source(&host, "OPENIDEA_TEST_MYSQL", "my", DbDriver::Mysql, "").await {
|
||||
return;
|
||||
}
|
||||
let setup = "DROP DATABASE IF EXISTS oi_script_lock; CREATE DATABASE oi_script_lock; \
|
||||
CREATE TABLE oi_script_lock.t (n INT)";
|
||||
assert_eq!(errors(&run_script(&host, 1, "my", DbDriver::Mysql, setup).await), Vec::<String>::new());
|
||||
warm_pool(&host, "my", 4).await;
|
||||
// How mysqldump writes a table's rows.
|
||||
let rows = "LOCK TABLES oi_script_lock.t WRITE; INSERT INTO oi_script_lock.t VALUES (1); UNLOCK TABLES";
|
||||
let run = run_script(&host, 2, "my", DbDriver::Mysql, rows);
|
||||
let outcomes = tokio::time::timeout(std::time::Duration::from_secs(15), run)
|
||||
.await
|
||||
.expect("the INSERT waited for the LOCK TABLES of its own script");
|
||||
assert_eq!(errors(&outcomes), Vec::<String>::new());
|
||||
let counted = run_script(&host, 3, "my", DbDriver::Mysql, "SELECT count(*) FROM oi_script_lock.t").await;
|
||||
assert_eq!(cell(&counted[0]).as_deref(), Some("1"));
|
||||
run_script(&host, 4, "my", DbDriver::Mysql, "DROP DATABASE oi_script_lock").await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_page_with_a_cell_limit_carries_prefixes_and_each_whole_value_is_read_on_demand() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -79,7 +79,13 @@ pub async fn debug_start(host: &Host, window: &str, mut config: LaunchConfig) ->
|
||||
)?;
|
||||
}
|
||||
let label = window;
|
||||
let (sink, flush_output) = output::coalescing_sink(host.window_sink(label));
|
||||
let mut window_sink = host.window_sink(label);
|
||||
if let (Ok(project), Some(plugins)) = (host.project(label), host.plugin_host())
|
||||
&& project.require_trust().is_ok()
|
||||
{
|
||||
window_sink = plugins.wrap_debug_output_sink(label, None, window_sink);
|
||||
}
|
||||
let (sink, flush_output) = output::coalescing_sink(window_sink);
|
||||
let owner = SessionOwner::new(host.owner_window(label), sink);
|
||||
let settings = match host.project(label) {
|
||||
Ok(project) => project.settings.effective(),
|
||||
|
||||
@@ -106,7 +106,7 @@ fn remember_encoding(project: &Project, path: &Path, encoding: &str) -> IdeResul
|
||||
return Ok(());
|
||||
}
|
||||
let settings = project.settings.set_map_entry(SettingsScope::Project, MAPPINGS, &file, encoding.into())?;
|
||||
project.documents.set_file_defaults(FileDefaults::from_settings(&settings, Some(&project.root)));
|
||||
project.documents.set_settings_defaults(FileDefaults::from_settings(&settings, Some(&project.root)));
|
||||
project.sink.emit(IdeEvent::SettingsChanged { key: MAPPINGS.into() });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -15,6 +15,13 @@ struct Fixture {
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let f = Self::with_background_sync();
|
||||
// Keep background unwatched-file polling out of focus-sync tests so they exercise `doc_sync_from_disk` directly.
|
||||
f.project.stop_unwatched_document_sync();
|
||||
f
|
||||
}
|
||||
|
||||
fn with_background_sync() -> Self {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
@@ -169,6 +176,88 @@ async fn outside_project_document_reloads() {
|
||||
assert_eq!(f.project.documents.snapshot(original.id).unwrap().text, "outside changed externally\n");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn open_external_document_reloads_without_window_focus() {
|
||||
let f = Fixture::with_background_sync();
|
||||
let original = f.open(&f.outside).await;
|
||||
std::fs::write(&f.outside, "newly materialized source\n").unwrap();
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
loop {
|
||||
let loaded = f.project.documents.snapshot(original.id).unwrap();
|
||||
if loaded.text == "newly materialized source\n" {
|
||||
assert!(!loaded.dirty);
|
||||
assert!(loaded.version > original.version);
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("open external file should refresh while the IDE is still focused");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn open_generated_document_reloads_without_window_focus() {
|
||||
let f = Fixture::with_background_sync();
|
||||
let generated = f.project.root.join("target/generated-sources/OwnersApi.java");
|
||||
std::fs::create_dir_all(generated.parent().unwrap()).unwrap();
|
||||
std::fs::write(&generated, "interface OwnersApi { void listOwners(String lastName); }\n").unwrap();
|
||||
let original = f.open(&generated).await;
|
||||
let rewritten = "interface OwnersApi { void listOwners(String lastName, String city); }\n";
|
||||
std::fs::write(&generated, rewritten).unwrap();
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
loop {
|
||||
let loaded = f.project.documents.snapshot(original.id).unwrap();
|
||||
if loaded.text == rewritten {
|
||||
assert!(!loaded.dirty);
|
||||
assert!(loaded.version > original.version);
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("an open generated source should refresh while the IDE is still focused");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn dirty_unwatched_documents_keep_edits_on_background_sync() {
|
||||
let f = Fixture::with_background_sync();
|
||||
let mut dirty = Vec::new();
|
||||
for path in [&f.outside, &f.path] {
|
||||
let original = f.open(path).await;
|
||||
doc_edit(
|
||||
&f.host,
|
||||
"main",
|
||||
original.id,
|
||||
original.version,
|
||||
ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "local ".into() }] },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
std::fs::write(path, "external replacement\n").unwrap();
|
||||
dirty.push((original.id, format!("local {}", original.text)));
|
||||
}
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
loop {
|
||||
let events = f.document_events();
|
||||
if dirty.iter().all(|(id, _)| {
|
||||
events.iter().any(|event| matches!(event, IdeEvent::DocDiskConflict { doc, .. } if doc == id))
|
||||
}) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("background sync should report both conflicts");
|
||||
for (id, expected) in dirty {
|
||||
let loaded = f.project.documents.snapshot(id).unwrap();
|
||||
assert_eq!(loaded.text, expected);
|
||||
assert!(loaded.dirty);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn setting_defaults_on_and_disabled_sync_keeps_buffer() {
|
||||
let f = Fixture::new();
|
||||
@@ -226,6 +315,7 @@ async fn synchronization_only_changes_the_calling_windows_documents() {
|
||||
let other_root = f.outside.parent().unwrap().join("other-project");
|
||||
std::fs::create_dir(&other_root).unwrap();
|
||||
let other = f.host.open_project("other", &other_root).unwrap();
|
||||
other.stop_unwatched_document_sync();
|
||||
let other_doc = doc_open(&f.host, "other", f.outside.clone()).await.unwrap();
|
||||
std::fs::write(&f.outside, "external change in shared file\n").unwrap();
|
||||
f.sync().await;
|
||||
|
||||
@@ -6,9 +6,9 @@ use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
|
||||
use ide_docker::{
|
||||
ComposeOp, ContainerOp, DockerContainer, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer,
|
||||
DockerLogLine, DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget,
|
||||
RegistryAuth,
|
||||
ComposeOp, ContainerOp, DockerContainer, DockerContainerStats, DockerContainerStatsSample, DockerEndpoint,
|
||||
DockerEvent, DockerImageLayer, DockerLogLine, DockerObject, DockerProcessList, DockerRegistry, DockerSettings,
|
||||
DockerSnapshot, PruneTarget, RegistryAuth,
|
||||
};
|
||||
use ide_ssh::Tunnel;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
@@ -186,6 +186,24 @@ pub async fn docker_container_stats(
|
||||
host.blocking(move || ide_docker::container_stats(&endpoint, &id)).await
|
||||
}
|
||||
|
||||
/// Streams live resource samples of a running container until it stops or the request is cancelled.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_container_stats_stream(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
id: String,
|
||||
on_sample: Channel<DockerContainerStatsSample>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::stream_container_stats(&endpoint, &id, cancel, &|sample| {
|
||||
let _ = on_sample.send(sample);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Dev container resource limits, live usage (`docker stats`), `hostRequirements` and OOM state.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_devcontainer_status(
|
||||
@@ -367,6 +385,7 @@ ide_command::domain!(
|
||||
docker_compose_op,
|
||||
docker_container_op,
|
||||
docker_container_stats,
|
||||
docker_container_stats_stream,
|
||||
docker_container_top,
|
||||
docker_devcontainer_status,
|
||||
docker_disconnect,
|
||||
|
||||
@@ -37,6 +37,11 @@ pub async fn history_restore(host: &Host, window: &str, path: PathBuf, id: Strin
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
if !path.exists() {
|
||||
// An empty file would open with the defaults for new files, not the file's own BOM,
|
||||
// line endings and encoding.
|
||||
if project.history.restore_deleted(&path, &id)? {
|
||||
return Ok(());
|
||||
}
|
||||
ide_vfs::create_file(&path)?;
|
||||
}
|
||||
let doc = project.documents.open(&path)?.id;
|
||||
@@ -48,3 +53,85 @@ pub async fn history_restore(host: &Host, window: &str, path: PathBuf, id: Strin
|
||||
}
|
||||
|
||||
ide_command::domain!(history: history_list_dir, history_put_label, history_restore);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::HostConfig;
|
||||
use ide_core::{ChangeSet, TextChange};
|
||||
use std::fs;
|
||||
|
||||
/// Opens `path` in the editor, adds `text` at its end and saves it.
|
||||
fn append_and_save(project: &crate::Project, path: &std::path::Path, text: &str) -> ide_core::DocId {
|
||||
let info = project.documents.open(path).unwrap();
|
||||
let end = info.text.encode_utf16().count() as u32;
|
||||
let edit = ChangeSet { changes: vec![TextChange { from: end, to: end, insert: text.into() }] };
|
||||
project.documents.edit(info.id, info.version, edit).unwrap();
|
||||
project.documents.save(info.id).unwrap();
|
||||
info.id
|
||||
}
|
||||
|
||||
/// Deletes `path` outside the IDE (a branch switch, `git rm`) unless it is gone already, then
|
||||
/// reverts it to its "Deleted" entry in Local History.
|
||||
async fn revert_deleted(host: &Host, path: &std::path::Path) -> Vec<u8> {
|
||||
let project = host.project("main").unwrap();
|
||||
if path.exists() {
|
||||
fs::remove_file(path).unwrap();
|
||||
project.history.note_removed(&[path.to_path_buf()]).unwrap();
|
||||
}
|
||||
let entries = project.history.list(path).unwrap();
|
||||
let deleted = entries.into_iter().find(|e| e.label == ide_workspace::history::DELETED).unwrap();
|
||||
history_restore(host, "main", path.to_path_buf(), deleted.id).await.unwrap();
|
||||
fs::read(path).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn reverting_a_deleted_file_writes_back_its_bytes() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
// Excluded from the watcher, whose own snapshots would race the test's.
|
||||
let dir = root.join("node_modules");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let host = Host::new(HostConfig::for_test(&base));
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
let mut wrong = Vec::new();
|
||||
let mut check = |name: &str, restored: Vec<u8>, expected: &[u8]| {
|
||||
if restored != expected {
|
||||
wrong.push(format!("{name}: {:?}", String::from_utf8_lossy(&restored)));
|
||||
}
|
||||
};
|
||||
|
||||
let (gbk, _, _) = encoding_rs::GBK.encode("// 中文注释,用于测试文件编码的检测与保存。\nclass A {}\n");
|
||||
for (name, bytes) in [
|
||||
("run.bat", b"@echo off\r\necho one\r\n".to_vec()),
|
||||
("bom.txt", b"\xEF\xBB\xBFline one\nline two\n".to_vec()),
|
||||
("Legacy.java", gbk.into_owned()),
|
||||
] {
|
||||
let path = dir.join(name);
|
||||
fs::write(&path, &bytes).unwrap();
|
||||
project.documents.close(append_and_save(&project, &path, "// edited\n"));
|
||||
let saved = fs::read(&path).unwrap();
|
||||
check(name, revert_deleted(&host, &path).await, &saved);
|
||||
}
|
||||
|
||||
// Saved again with only its line endings changed: the same text in other bytes.
|
||||
let path = dir.join("converted.txt");
|
||||
fs::write(&path, "one\n").unwrap();
|
||||
let doc = append_and_save(&project, &path, "two\n");
|
||||
project.documents.set_line_ending(doc, ide_text::LineEnding::CrLf).unwrap();
|
||||
project.documents.save(doc).unwrap();
|
||||
project.documents.close(doc);
|
||||
check("converted.txt", revert_deleted(&host, &path).await, b"one\r\ntwo\r\n");
|
||||
|
||||
// Deleted in the Project view, which keeps the file's bytes for its Undo.
|
||||
let path = dir.join("never-opened.bat");
|
||||
fs::write(&path, b"echo crlf\r\n").unwrap();
|
||||
project.history.capture_deletion_undo(std::slice::from_ref(&path), 10);
|
||||
fs::remove_file(&path).unwrap();
|
||||
check("never-opened.bat", revert_deleted(&host, &path).await, b"echo crlf\r\n");
|
||||
|
||||
host.close_project("main");
|
||||
assert!(wrong.is_empty(), "restored with other bytes: {wrong:#?}");
|
||||
}
|
||||
}
|
||||
@@ -93,7 +93,7 @@ pub async fn lsp_completion(
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let mut items = kept;
|
||||
items.extend(answer.items.into_iter().map(|(_, item)| plugin_completion(item)));
|
||||
items.extend(answer.items.into_iter().map(|(plugin, item, data)| plugin_completion(plugin, item, data)));
|
||||
let mut session = project.completion_session.lock();
|
||||
if let Some(s) = session.as_mut().filter(|s| s.incomplete == only) {
|
||||
s.incomplete = answer.incomplete.clone();
|
||||
@@ -121,9 +121,10 @@ pub async fn lsp_completion(
|
||||
let mut list = result.unwrap_or(CompletionList { is_incomplete: false, items: Vec::new() });
|
||||
let server_complete = !list.is_incomplete;
|
||||
let mut fresh = Vec::new();
|
||||
for (id, item) in answer.items {
|
||||
let item = plugin_completion(item);
|
||||
if answer.incomplete.contains(&id) { fresh.push(item) } else { list.items.push(item) }
|
||||
for (id, item, data) in answer.items {
|
||||
let incomplete_plugin = answer.incomplete.contains(&id);
|
||||
let item = plugin_completion(id, item, data);
|
||||
if incomplete_plugin { fresh.push(item) } else { list.items.push(item) }
|
||||
}
|
||||
if !answer.incomplete.is_empty() {
|
||||
// Only a complete server list can be kept; else typing on asks everyone, as before.
|
||||
@@ -262,6 +263,12 @@ struct PluginActionRef {
|
||||
file: bool,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
struct PluginCompletionRef {
|
||||
plugin: String,
|
||||
data: String,
|
||||
}
|
||||
|
||||
/// A plugin's `completion-item.kind` (wit/providers.wit lists them).
|
||||
fn plugin_completion_kind(kind: &str) -> Option<CompletionKind> {
|
||||
Some(match kind {
|
||||
@@ -294,7 +301,37 @@ fn plugin_completion_kind(kind: &str) -> Option<CompletionKind> {
|
||||
})
|
||||
}
|
||||
|
||||
fn plugin_completion(item: ide_plugin::CompletionItem) -> CompletionItem {
|
||||
fn completion_kind_to_plugin(kind: CompletionKind) -> &'static str {
|
||||
match kind {
|
||||
CompletionKind::Text => "text",
|
||||
CompletionKind::Method => "method",
|
||||
CompletionKind::Function => "function",
|
||||
CompletionKind::Constructor => "constructor",
|
||||
CompletionKind::Field => "field",
|
||||
CompletionKind::Variable => "variable",
|
||||
CompletionKind::Class => "class",
|
||||
CompletionKind::Interface => "interface",
|
||||
CompletionKind::Module => "module",
|
||||
CompletionKind::Property => "property",
|
||||
CompletionKind::Unit => "unit",
|
||||
CompletionKind::Value => "value",
|
||||
CompletionKind::Enum => "enum",
|
||||
CompletionKind::Keyword => "keyword",
|
||||
CompletionKind::Snippet => "snippet",
|
||||
CompletionKind::Color => "color",
|
||||
CompletionKind::File => "file",
|
||||
CompletionKind::Reference => "reference",
|
||||
CompletionKind::Folder => "folder",
|
||||
CompletionKind::EnumMember => "enum-member",
|
||||
CompletionKind::Constant => "constant",
|
||||
CompletionKind::Struct => "struct",
|
||||
CompletionKind::Event => "event",
|
||||
CompletionKind::Operator => "operator",
|
||||
CompletionKind::TypeParameter => "type-parameter",
|
||||
}
|
||||
}
|
||||
|
||||
fn plugin_completion(plugin: String, item: ide_plugin::CompletionItem, data: Option<String>) -> CompletionItem {
|
||||
let kind = item.kind.as_deref().and_then(plugin_completion_kind);
|
||||
CompletionItem {
|
||||
label: item.label,
|
||||
@@ -314,7 +351,7 @@ fn plugin_completion(item: ide_plugin::CompletionItem) -> CompletionItem {
|
||||
additional_edits: item.additional_edits,
|
||||
commit_characters: Vec::new(),
|
||||
command: None,
|
||||
data: None,
|
||||
data: data.and_then(|d| serde_json::to_value(PluginCompletionRef { plugin, data: d }).ok()),
|
||||
server: PLUGIN_SERVER,
|
||||
}
|
||||
}
|
||||
@@ -376,6 +413,51 @@ pub async fn lsp_resolve_completion(
|
||||
doc: DocId,
|
||||
item: CompletionItem,
|
||||
) -> IdeResult<CompletionItem> {
|
||||
if item.server == PLUGIN_SERVER {
|
||||
let Some(r) = item.data.clone().and_then(|d| serde_json::from_value::<PluginCompletionRef>(d).ok()) else {
|
||||
return Ok(item);
|
||||
};
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Completion) else {
|
||||
return Ok(item);
|
||||
};
|
||||
let item_ref = ide_plugin::PluginCompletionItemRef {
|
||||
item: ide_plugin::CompletionItem {
|
||||
label: item.label.clone(),
|
||||
detail: item.detail.clone(),
|
||||
kind: item.kind.map(completion_kind_to_plugin).map(str::to_owned),
|
||||
insert_text: item.insert_text.clone(),
|
||||
snippet: item.is_snippet,
|
||||
replace: item.replace_range,
|
||||
sort_text: item.sort_text.clone(),
|
||||
filter_text: item.filter_text.clone(),
|
||||
documentation: item.documentation.as_ref().map(|m| m.value.clone()),
|
||||
additional_edits: item.additional_edits.clone(),
|
||||
},
|
||||
data: Some(r.data),
|
||||
};
|
||||
let plugin = r.plugin.clone();
|
||||
let invocation = ide_plugin::Invocation {
|
||||
client: Some(window.to_owned()),
|
||||
workspace_root: host.project(window).ok().map(|p| p.root.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
let resolved = blocking(move || plugins.resolve_completion_item(&plugin, &d, item_ref, invocation)).await?;
|
||||
// Like LSP `completionItem/resolve`: only the details are filled in; what the item inserts
|
||||
// stays as listed, since the user may already be choosing it.
|
||||
let resolved = plugin_completion(r.plugin, resolved, None);
|
||||
return Ok(CompletionItem {
|
||||
detail: resolved.detail.or(item.detail),
|
||||
documentation: resolved.documentation.or(item.documentation),
|
||||
additional_edits: if resolved.additional_edits.is_empty() {
|
||||
item.additional_edits
|
||||
} else {
|
||||
resolved.additional_edits
|
||||
},
|
||||
// Resolved: nothing left to ask the plugin for.
|
||||
data: None,
|
||||
..item
|
||||
});
|
||||
}
|
||||
host.project(window)?.lsp.resolve_completion(doc, item).await
|
||||
}
|
||||
|
||||
@@ -615,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,
|
||||
@@ -633,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
|
||||
@@ -897,6 +993,63 @@ pub async fn lsp_virtual_document(host: &Host, window: &str, uri: String) -> Ide
|
||||
host.project(window)?.lsp.virtual_document(&uri).await
|
||||
}
|
||||
|
||||
const JAVA_SOURCE_ATTACHMENTS_FILE: &str = "java-source-attachments.json";
|
||||
|
||||
pub(crate) fn load_java_source_attachments(
|
||||
cache_dir: &Path,
|
||||
) -> std::collections::HashMap<std::path::PathBuf, std::path::PathBuf> {
|
||||
let path = cache_dir.join(JAVA_SOURCE_ATTACHMENTS_FILE);
|
||||
let Ok(bytes) = std::fs::read(path) else { return Default::default() };
|
||||
serde_json::from_slice(&bytes).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn save_java_source_attachments(
|
||||
cache_dir: &Path,
|
||||
attachments: &std::collections::HashMap<std::path::PathBuf, std::path::PathBuf>,
|
||||
) {
|
||||
if std::fs::create_dir_all(cache_dir).is_err() {
|
||||
return;
|
||||
}
|
||||
let Ok(bytes) = serde_json::to_vec_pretty(attachments) else { return };
|
||||
let _ = std::fs::write(cache_dir.join(JAVA_SOURCE_ATTACHMENTS_FILE), bytes);
|
||||
}
|
||||
|
||||
async fn download_maven_sources(
|
||||
host: &Host,
|
||||
project: &std::sync::Arc<crate::project::Project>,
|
||||
jar: std::path::PathBuf,
|
||||
cancel: &ide_core::CancellationToken,
|
||||
) -> IdeResult<Option<std::path::PathBuf>> {
|
||||
let project = project.clone();
|
||||
let cancel = cancel.clone();
|
||||
host.blocking(move || {
|
||||
let settings = project.settings.effective();
|
||||
let repository = ide_sdk::apply::maven_local_repository(&project.root, &settings)
|
||||
.or_else(ide_build::maven::default_local_repo)
|
||||
.ok_or_else(|| IdeError::unavailable("Maven local repository is unavailable"))?;
|
||||
let artifact = ide_build::maven::sources::artifact(&jar, &repository)
|
||||
.ok_or_else(|| IdeError::invalid("not an artifact in the Maven local repository"))?;
|
||||
let model = super::build::load(&project.root, &project.build_cache_dir(), &settings);
|
||||
let maven = model.maven.ok_or_else(|| IdeError::unavailable("no Maven project"))?;
|
||||
let owns = |p: &&ide_build::maven::MavenProject| {
|
||||
p.dependencies.iter().any(|d| d.group_id == artifact.group && d.artifact_id == artifact.name)
|
||||
};
|
||||
let mut owner = maven
|
||||
.projects
|
||||
.iter()
|
||||
.find(owns)
|
||||
.or_else(|| maven.projects.first())
|
||||
.cloned()
|
||||
.ok_or_else(|| IdeError::unavailable("no Maven project"))?;
|
||||
let profiles = settings.languages.java.maven.profiles(&ide_build::maven_profiles(&project.build_cache_dir()));
|
||||
if !profiles.is_empty() {
|
||||
owner.options.push(format!("-P{}", profiles.join(",")));
|
||||
}
|
||||
ide_build::maven::sources::download(&project.root, &owner, &artifact, &repository, &cancel)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_can_download_sources(host: &Host, window: &str, uri: String) -> IdeResult<bool> {
|
||||
// Whether this class belongs to the project's Maven local repository.
|
||||
@@ -904,7 +1057,16 @@ pub async fn lsp_can_download_sources(host: &Host, window: &str, uri: String) ->
|
||||
if !project.is_trusted() {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(jar) = ide_lsp::LspManager::library_archive(&uri) else { return Ok(false) };
|
||||
let jar = match ide_lsp::LspManager::library_archive(&uri) {
|
||||
Some(jar) => jar,
|
||||
None => match project.lsp.java_source_origin(Path::new(&uri)).await? {
|
||||
Some(origin) => match origin.binary_jar() {
|
||||
Some(jar) => jar,
|
||||
None => return Ok(false),
|
||||
},
|
||||
None => return Ok(false),
|
||||
},
|
||||
};
|
||||
host.blocking(move || {
|
||||
let settings = project.settings.effective();
|
||||
let repository = ide_sdk::apply::maven_local_repository(&project.root, &settings)
|
||||
@@ -929,45 +1091,50 @@ pub async fn lsp_library_sources(
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = async {
|
||||
let sources = match sources {
|
||||
Some(sources) => Some(sources),
|
||||
if let Some(jar) = ide_lsp::LspManager::library_archive(&uri) {
|
||||
let sources = match sources {
|
||||
Some(sources) => Some(sources),
|
||||
None => download_maven_sources(host, &project, jar, &cancel).await?,
|
||||
};
|
||||
return match sources {
|
||||
Some(sources) => project.lsp.library_source_location(&uri, sources, pos, &cancel).await,
|
||||
None => Ok(None),
|
||||
};
|
||||
}
|
||||
let path = Path::new(&uri);
|
||||
let jar = project
|
||||
.lsp
|
||||
.java_source_origin(path)
|
||||
.await?
|
||||
.and_then(|origin| origin.binary_jar())
|
||||
.ok_or_else(|| IdeError::invalid("not a library class"))?;
|
||||
let attached = match sources {
|
||||
Some(chosen) => project.lsp.java_attach_library_sources(path, Some(chosen), pos, &cancel).await?,
|
||||
None => {
|
||||
let jar = ide_lsp::LspManager::library_archive(&uri)
|
||||
.ok_or_else(|| IdeError::invalid("not a library class"))?;
|
||||
let project = project.clone();
|
||||
let cancel = cancel.clone();
|
||||
host.blocking(move || {
|
||||
let settings = project.settings.effective();
|
||||
let repository = ide_sdk::apply::maven_local_repository(&project.root, &settings)
|
||||
.or_else(ide_build::maven::default_local_repo)
|
||||
.ok_or_else(|| IdeError::unavailable("Maven local repository is unavailable"))?;
|
||||
let artifact = ide_build::maven::sources::artifact(&jar, &repository)
|
||||
.ok_or_else(|| IdeError::invalid("not an artifact in the Maven local repository"))?;
|
||||
let model = super::build::load(&project.root, &project.build_cache_dir(), &settings);
|
||||
let maven = model.maven.ok_or_else(|| IdeError::unavailable("no Maven project"))?;
|
||||
let owns = |p: &&ide_build::maven::MavenProject| {
|
||||
p.dependencies.iter().any(|d| d.group_id == artifact.group && d.artifact_id == artifact.name)
|
||||
};
|
||||
let mut owner = maven
|
||||
.projects
|
||||
.iter()
|
||||
.find(owns)
|
||||
.or_else(|| maven.projects.first())
|
||||
.cloned()
|
||||
.ok_or_else(|| IdeError::unavailable("no Maven project"))?;
|
||||
let profiles =
|
||||
settings.languages.java.maven.profiles(&ide_build::maven_profiles(&project.build_cache_dir()));
|
||||
if !profiles.is_empty() {
|
||||
owner.options.push(format!("-P{}", profiles.join(",")));
|
||||
}
|
||||
ide_build::maven::sources::download(&project.root, &owner, &artifact, &repository, &cancel)
|
||||
})
|
||||
.await?
|
||||
// Attach an already-local sources jar immediately before invoking Maven.
|
||||
match project.lsp.java_attach_library_sources(path, None, pos, &cancel).await? {
|
||||
Some(found) => Some(found),
|
||||
None => match download_maven_sources(host, &project, jar, &cancel).await? {
|
||||
Some(downloaded) => {
|
||||
project.lsp.java_attach_library_sources(path, Some(downloaded), pos, &cancel).await?
|
||||
}
|
||||
None => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
match sources {
|
||||
Some(sources) => project.lsp.library_source_location(&uri, sources, pos, &cancel).await,
|
||||
None => Ok(None),
|
||||
if let Some((location, _, _)) = attached {
|
||||
let cache_dir = project.build_cache_dir();
|
||||
let attachments = project.lsp.java_source_attachments();
|
||||
let _ = host
|
||||
.blocking(move || {
|
||||
save_java_source_attachments(&cache_dir, &attachments);
|
||||
Ok(())
|
||||
})
|
||||
.await;
|
||||
Ok(Some(location))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
.await;
|
||||
@@ -981,6 +1148,17 @@ pub async fn lsp_resolve_class_file(host: &Host, window: &str, path: std::path::
|
||||
host.project(window)?.lsp.java_class_file(&path, archive, read_internal_class_name(&path)).await
|
||||
}
|
||||
|
||||
/// The archive entry behind a library file in java-analyzer's cache, for selecting it under
|
||||
/// External Libraries. `None` for other files and servers without the request.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_library_source_origin(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: std::path::PathBuf,
|
||||
) -> IdeResult<Option<LibrarySourceOrigin>> {
|
||||
host.project(window)?.lsp.java_source_origin(&path).await
|
||||
}
|
||||
|
||||
async fn read_internal_class_name(path: &Path) -> IdeResult<String> {
|
||||
let bytes = tokio::fs::read(path).await?;
|
||||
ide_build::jbuild::class_file_name(&bytes)
|
||||
@@ -1528,7 +1706,24 @@ pub async fn lsp_prepare_rename(host: &Host, window: &str, doc: DocId, pos: Pos)
|
||||
})
|
||||
.await;
|
||||
}
|
||||
host.project(window)?.lsp.prepare_rename(doc, pos).await
|
||||
let result = host.project(window)?.lsp.prepare_rename(doc, pos).await;
|
||||
let should_query_plugin = matches!(&result, Ok(None))
|
||||
|| matches!(
|
||||
&result,
|
||||
Err(e) if matches!(e.kind, ErrorKind::NotFound | ErrorKind::Unavailable | ErrorKind::Protocol)
|
||||
);
|
||||
if should_query_plugin && let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Rename) {
|
||||
let invocation = ide_plugin::Invocation {
|
||||
client: Some(window.to_owned()),
|
||||
workspace_root: host.project(window).ok().map(|p| p.root.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
let found = plugin_call(move || plugins.provide_prepare_rename(&d, pos, invocation)).await.unwrap_or_default();
|
||||
if let Some((_, first)) = found.into_iter().next() {
|
||||
return Ok(Some(first.range));
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The Throwable class the caret at `pos` names, for the exception breakpoint intention.
|
||||
@@ -1599,6 +1794,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,
|
||||
@@ -1833,6 +2070,41 @@ pub async fn lsp_rename(
|
||||
}
|
||||
Renamed { incomplete, ..Default::default() }
|
||||
}
|
||||
Err(e) if matches!(e.kind, ErrorKind::NotFound | ErrorKind::Unavailable | ErrorKind::Protocol) => {
|
||||
if let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Rename) {
|
||||
let cancel_ref = cancel.clone();
|
||||
let name_clone = new_name.clone();
|
||||
let invocation = ide_plugin::Invocation {
|
||||
client: Some(window.to_owned()),
|
||||
workspace_root: Some(project.root.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
let plugin_answers =
|
||||
plugin_call(move || plugins.provide_rename(&d, pos, &name_clone, invocation, &cancel_ref))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let mut plugin_renamed = Renamed::default();
|
||||
if merge_plugin_rename(&project, &mut plugin_renamed, plugin_answers)? {
|
||||
let plugin_docs = project.clone();
|
||||
let cancel_post = cancel.clone();
|
||||
return blocking(move || {
|
||||
if plugin_docs.documents.version(doc)? != version {
|
||||
return Err(ide_core::IdeError::new(
|
||||
ErrorKind::OutOfSync,
|
||||
"document changed while computing rename; request it again",
|
||||
));
|
||||
}
|
||||
plugin_docs.documents.prepare_workspace_edit(&mut plugin_renamed.edit)?;
|
||||
if cancel_post.is_cancelled() {
|
||||
return Err(ide_core::IdeError::cancelled());
|
||||
}
|
||||
Ok(plugin_renamed)
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if native_owned
|
||||
@@ -1843,6 +2115,20 @@ pub async fn lsp_rename(
|
||||
{
|
||||
return Err(ide_core::IdeError::invalid("Native server declined rename"));
|
||||
}
|
||||
let plugin_answers = if let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Rename) {
|
||||
let cancel_ref = cancel.clone();
|
||||
let name_clone = new_name.clone();
|
||||
let invocation = ide_plugin::Invocation {
|
||||
client: Some(window.to_owned()),
|
||||
workspace_root: Some(project.root.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
plugin_call(move || plugins.provide_rename(&d, pos, &name_clone, invocation, &cancel_ref))
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
blocking(move || {
|
||||
if project.documents.version(doc)? != version {
|
||||
return Err(ide_core::IdeError::new(
|
||||
@@ -1853,6 +2139,7 @@ pub async fn lsp_rename(
|
||||
if let Some(symbol) = &symbol {
|
||||
merge_indexed_rename(&mut renamed, symbol, &new_name, &project.documents);
|
||||
}
|
||||
merge_plugin_rename(&project, &mut renamed, plugin_answers)?;
|
||||
project.documents.prepare_workspace_edit(&mut renamed.edit)?;
|
||||
if let Some(symbol) = &symbol {
|
||||
validate_indexed_symbol(&project, symbol, Some(&cancel))?;
|
||||
@@ -1902,6 +2189,47 @@ async fn indexed_code_identifier(
|
||||
.await
|
||||
}
|
||||
|
||||
fn merge_plugin_rename(
|
||||
project: &crate::Project,
|
||||
renamed: &mut Renamed,
|
||||
answers: Vec<(String, crate::plugins::RenameEdits)>,
|
||||
) -> IdeResult<bool> {
|
||||
use ide_core::FileEdit;
|
||||
let roots = plugin_edit_roots(project);
|
||||
let had_existing = !renamed.edit.files.is_empty();
|
||||
let mut added = false;
|
||||
for (_plugin, files) in answers {
|
||||
for (raw_path, edits) in files {
|
||||
if edits.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let path = ide_plugin::resolve_writable_in_roots(&roots, &raw_path.to_string_lossy())
|
||||
.map_err(IdeError::invalid)?;
|
||||
let simplified = dunce::simplified(&path).to_path_buf();
|
||||
if let Some(FileEdit::Edit { edits: existing, .. }) = renamed.edit.files.iter_mut().find(|op| {
|
||||
matches!(op, FileEdit::Edit { path: target, .. } if dunce::simplified(target) == simplified.as_path())
|
||||
}) {
|
||||
for edit in edits {
|
||||
let overlaps = existing.iter().any(|e| {
|
||||
edit.range.start < e.range.end && e.range.start < edit.range.end || (edit.range == e.range)
|
||||
});
|
||||
if !overlaps {
|
||||
existing.push(edit);
|
||||
added = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
renamed.edit.files.push(FileEdit::Edit { path: path.into(), edits, version: None });
|
||||
added = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if added && (had_existing || renamed.edit.files.len() > 1) {
|
||||
renamed.preview = true;
|
||||
}
|
||||
Ok(added)
|
||||
}
|
||||
|
||||
fn merge_indexed_rename(
|
||||
renamed: &mut Renamed,
|
||||
symbol: &crate::plugins::navigation::IndexedSymbol,
|
||||
@@ -3480,6 +3808,8 @@ 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,
|
||||
@@ -3494,6 +3824,7 @@ ide_command::domain!(
|
||||
lsp_java_move,
|
||||
lsp_java_move_destinations,
|
||||
lsp_java_source_types,
|
||||
lsp_library_source_origin,
|
||||
lsp_library_sources,
|
||||
lsp_message_request_answer,
|
||||
lsp_prepare_rename,
|
||||
@@ -3518,6 +3849,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,
|
||||
|
||||
@@ -223,6 +223,7 @@ pub fn project_workspace_member_set(
|
||||
p.settings.reload();
|
||||
p.sink.emit(IdeEvent::SettingsChanged { key: key.clone() });
|
||||
}
|
||||
p.invalidate_scans();
|
||||
p.refresh_index_scope();
|
||||
p.sink.emit(IdeEvent::ProjectRootsChanged { root: p.root.clone().into() });
|
||||
}
|
||||
@@ -279,6 +280,7 @@ pub fn save_workspace(host: &Host, window: &str, name: &str, paths: Vec<std::pat
|
||||
let workspace = ide_workspace::workspace::Workspace::save(&project.root, name, paths, false)?;
|
||||
keep_attachment_private(&project.root, &workspace)?;
|
||||
}
|
||||
project.invalidate_scans();
|
||||
refresh_workspace(&project);
|
||||
Ok(info(&project))
|
||||
}
|
||||
@@ -412,7 +414,7 @@ pub fn set_settings(
|
||||
None => host.global_settings.set(SettingsScope::Global, key, value)?,
|
||||
};
|
||||
if let Some(p) = ¤t {
|
||||
p.documents.set_file_defaults(ide_workspace::FileDefaults::from_settings(&settings, Some(&p.root)));
|
||||
p.documents.set_settings_defaults(ide_workspace::FileDefaults::from_settings(&settings, Some(&p.root)));
|
||||
}
|
||||
// A global value reaches every other open project too.
|
||||
if !project_scope {
|
||||
@@ -423,10 +425,13 @@ pub fn set_settings(
|
||||
let effective = project.settings.reload();
|
||||
project
|
||||
.documents
|
||||
.set_file_defaults(ide_workspace::FileDefaults::from_settings(&effective, Some(&project.root)));
|
||||
.set_settings_defaults(ide_workspace::FileDefaults::from_settings(&effective, Some(&project.root)));
|
||||
}
|
||||
}
|
||||
let affected = || if project_scope { current.iter().cloned().collect() } else { host.projects() };
|
||||
for project in affected() {
|
||||
project.invalidate_scans();
|
||||
}
|
||||
if key == "editor" || key == "editor.encodings" || key == "editor.encodings.nativeToAscii" {
|
||||
let affected = affected();
|
||||
host.runtime.spawn_blocking(move || {
|
||||
@@ -527,6 +532,8 @@ pub fn set_settings(
|
||||
let toolchain = ["languages", "tools", "languageServers", "projectStructure"]
|
||||
.iter()
|
||||
.any(|k| key == *k || key.starts_with(&format!("{k}.")));
|
||||
// Changing the UI language restarts running language servers so they re-initialize with the new locale.
|
||||
let appearance_locale = key == "appearance" || key == "appearance.locale";
|
||||
// A run target chosen as the Python interpreter (or changed) needs a snapshot of its libraries.
|
||||
if ["languages", "languages.python", "languages.python.interpreter", "runTargets"].contains(&key) {
|
||||
for project in affected() {
|
||||
@@ -534,9 +541,11 @@ pub fn set_settings(
|
||||
}
|
||||
}
|
||||
// Code style only reaches servers as settings (e.g. jdtls' formatter profile); builds don't depend on it.
|
||||
if code_style || toolchain {
|
||||
if code_style || toolchain || appearance_locale {
|
||||
for project in affected() {
|
||||
if toolchain && let Some(bridge) = &project.kotlin_bridge {
|
||||
if (toolchain || appearance_locale)
|
||||
&& let Some(bridge) = &project.kotlin_bridge
|
||||
{
|
||||
bridge.schedule();
|
||||
}
|
||||
let lsp = project.lsp.clone();
|
||||
|
||||
Loaded 100 of 1168 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача