mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-07 10:16:03 -10:00
Compare commits
213
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1446d5592c | ||
|
|
fbf57bed23 | ||
|
|
292ddc4d2a | ||
|
|
af19880390 | ||
|
|
30a0521d0d | ||
|
|
4a78310f76 | ||
|
|
7cedf0b9be | ||
|
|
0bee9b7aab | ||
|
|
3efec1c848 | ||
|
|
e024c13db7 | ||
|
|
780e57d0c5 | ||
|
|
200ab10e65 | ||
|
|
dfcdd8d764 | ||
|
|
27e73ea2cb | ||
|
|
bb99c7c4d1 | ||
|
|
f6531542de | ||
|
|
9e6cb7b93e | ||
|
|
0b88599463 | ||
|
|
da3d996e10 | ||
|
|
4c6e535560 | ||
|
|
705f3557a8 | ||
|
|
4dcf7b0fb2 | ||
|
|
a6d24e684f | ||
|
|
1b889a5147 | ||
|
|
4d088c35ff | ||
|
|
60d7dcdca0 | ||
|
|
7479b7ad9d | ||
|
|
053a2c37d8 | ||
|
|
a40a909db5 | ||
|
|
c1e32b091a | ||
|
|
72b39d819f | ||
|
|
b790a9ddb6 | ||
|
|
f407880204 | ||
|
|
daad91777f | ||
|
|
c3671d782c | ||
|
|
a232850b88 | ||
|
|
0d939c774d | ||
|
|
3407195dc0 | ||
|
|
96eaced1cf | ||
|
|
3f65cb0f57 | ||
|
|
b43d9bf7fb | ||
|
|
fdb07e580c | ||
|
|
32ac603e87 | ||
|
|
377a8c8379 | ||
|
|
dc69c36604 | ||
|
|
1891119f9d | ||
|
|
8509ca671f | ||
|
|
ebc1c21836 | ||
|
|
429b8f0efe | ||
|
|
257fb0f50f | ||
|
|
668206ddfd | ||
|
|
4ef4adf9b3 | ||
|
|
d509ed6e81 | ||
|
|
112ed773fb | ||
|
|
f3837e0fe7 | ||
|
|
c720024b42 | ||
|
|
90cca59462 | ||
|
|
f96ca468a8 | ||
|
|
25d930b780 | ||
|
|
1ab4edc0d7 | ||
|
|
309bb48f2c | ||
|
|
75773dd889 | ||
|
|
1cab24fea1 | ||
|
|
bbbdcb465e | ||
|
|
e367f6757e | ||
|
|
619daa1489 | ||
|
|
2945d20208 | ||
|
|
e68b35f534 | ||
|
|
adc308eb99 | ||
|
|
e0408cc7d7 | ||
|
|
56796fb2c6 | ||
|
|
c614355753 | ||
|
|
7a9c72ca24 | ||
|
|
b23b95ec00 | ||
|
|
17a121e7f5 | ||
|
|
303d5950bf | ||
|
|
4cfdb972eb | ||
|
|
d235c432ec | ||
|
|
d3ea6f6daf | ||
|
|
a36c7ed3d5 | ||
|
|
50567473f7 | ||
|
|
de4c325a28 | ||
|
|
a4a3c2105f | ||
|
|
6efff739dd | ||
|
|
8ca6e4bc01 | ||
|
|
8d909598d5 | ||
|
|
b99fe1704b | ||
|
|
159c2d6fd2 | ||
|
|
5084388a68 | ||
|
|
68342b32bf | ||
|
|
352efc02a7 | ||
|
|
24ffb9f16e | ||
|
|
8ebf839d8e | ||
|
|
14a31fe8a1 | ||
|
|
1af1744290 | ||
|
|
ee6786d573 | ||
|
|
5804fcad16 | ||
|
|
7a0c9354fa | ||
|
|
7e7da950fc | ||
|
|
9298be8798 | ||
|
|
715ebf19e2 | ||
|
|
438ab158ad | ||
|
|
7965d171f0 | ||
|
|
c004e50751 | ||
|
|
daac8e80b0 | ||
|
|
39f6162c12 | ||
|
|
809bc1cc2f | ||
|
|
4beca55a54 | ||
|
|
fc5a7d8c91 | ||
|
|
61b12269a1 | ||
|
|
39dc5db079 | ||
|
|
2d34bc956d | ||
|
|
99fafffaac | ||
|
|
66ecf4c967 | ||
|
|
88ecaf9ccd | ||
|
|
d018771a8d | ||
|
|
0eca4366d0 | ||
|
|
c4b9912036 | ||
|
|
8259a81335 | ||
|
|
1b3f9ac6f7 | ||
|
|
6c813d501e | ||
|
|
c3e8f20f53 | ||
|
|
0f0458b966 | ||
|
|
34d830c247 | ||
|
|
ab9bb7c266 | ||
|
|
fa36733f80 | ||
|
|
aa3323ddc5 | ||
|
|
b5974ab3ac | ||
|
|
ebac061a1f | ||
|
|
d4db7bb290 | ||
|
|
b2253a8bc8 | ||
|
|
d0c3b9ba34 | ||
|
|
eae363908d | ||
|
|
410761e0f7 | ||
|
|
ebbda4bb1f | ||
|
|
64398dde3a | ||
|
|
d36cf83f78 | ||
|
|
b1171ecd23 | ||
|
|
7a6b1601d5 | ||
|
|
4dd51a1101 | ||
|
|
bb508d4118 | ||
|
|
fa5d6d3d47 | ||
|
|
fb694aaceb | ||
|
|
1f969694a0 | ||
|
|
5b6dd007c6 | ||
|
|
0ac3f82dfb | ||
|
|
c08657ba17 | ||
|
|
6e18f32a32 | ||
|
|
148ae62681 | ||
|
|
632a98987f | ||
|
|
9c5372c7ab | ||
|
|
abdbc39d0d | ||
|
|
52eed40fc8 | ||
|
|
dbba16686c | ||
|
|
a3d5336642 | ||
|
|
708f1b051b | ||
|
|
068dcfdb0a | ||
|
|
3a6c77dce4 | ||
|
|
4f65f030ce | ||
|
|
e65825e661 | ||
|
|
2dc59ef2e2 | ||
|
|
ee84185b91 | ||
|
|
58f567c954 | ||
|
|
798da979a1 | ||
|
|
b54a745d6d | ||
|
|
954ad354a1 | ||
|
|
8e5507b9f2 | ||
|
|
a3ca40ccf4 | ||
|
|
b6dfde07bf | ||
|
|
576e55cbe1 | ||
|
|
a6d17543fd | ||
|
|
ef95cd1716 | ||
|
|
e2d82e2ec8 | ||
|
|
796f3f1512 | ||
|
|
47db04a3aa | ||
|
|
73322b04a6 | ||
|
|
9d75f27a1c | ||
|
|
84e1863ebf | ||
|
|
a80ed81ca8 | ||
|
|
b5ab3eed1f | ||
|
|
37975fd71a | ||
|
|
2028772ab2 | ||
|
|
5b53b579d9 | ||
|
|
9db90c7141 | ||
|
|
3bb58ff542 | ||
|
|
f0ad100a25 | ||
|
|
20cd00aaaf | ||
|
|
0d526be1c3 | ||
|
|
82ff476e8a | ||
|
|
43409c2229 | ||
|
|
2591bbac8f | ||
|
|
0341b697ce | ||
|
|
74f5ef8090 | ||
|
|
fca9d1e08f | ||
|
|
a268b2c488 | ||
|
|
d942f59dcd | ||
|
|
ba9ce1d842 | ||
|
|
763bcc056c | ||
|
|
fc978292cc | ||
|
|
cf94ab7203 | ||
|
|
1c2eceb55f | ||
|
|
f76c297fe9 | ||
|
|
c75a630ede | ||
|
|
266e4eeb03 | ||
|
|
c1aa092d75 | ||
|
|
b370bb0564 | ||
|
|
c8859b4d3f | ||
|
|
ff187a10f6 | ||
|
|
d984695e79 | ||
|
|
b7d886ea34 | ||
|
|
09c0af504e | ||
|
|
dadda6cf59 | ||
|
|
b1d8d61cb1 |
No files matched your search
@@ -0,0 +1,52 @@
|
||||
name: CNB mirror
|
||||
|
||||
# Copies a published release to cnb.cool/l0ng-ai/openidea, the updater's CNB source
|
||||
# (scripts/cnb-mirror.ts). Release runs it after publishing; run it by hand to mirror
|
||||
# an existing tag again. Skipped without the CNB_TOKEN secret.
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
tag: { type: string, required: true }
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Published release to mirror (e.g. v0.1.38)"
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: cnb-mirror-${{ inputs.tag }}
|
||||
|
||||
jobs:
|
||||
mirror:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
CNB_TOKEN: ${{ secrets.CNB_TOKEN }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- name: Check token
|
||||
id: token
|
||||
run: |
|
||||
if [ -z "$CNB_TOKEN" ]; then
|
||||
echo "::notice::CNB_TOKEN unset: not mirroring $TAG"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.token.outputs.skip != 'true'
|
||||
with: { sparse-checkout: scripts }
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.token.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
- name: Download release
|
||||
if: steps.token.outputs.skip != 'true'
|
||||
run: |
|
||||
gh release download "$TAG" -R "$GITHUB_REPOSITORY" -D assets
|
||||
gh release view "$TAG" -R "$GITHUB_REPOSITORY" --json body,isPrerelease > assets/release.json
|
||||
du -sh assets
|
||||
- name: Upload to CNB
|
||||
if: steps.token.outputs.skip != 'true'
|
||||
run: node scripts/cnb-mirror.ts "$TAG" assets
|
||||
@@ -166,6 +166,28 @@ jobs:
|
||||
xcrun stapler staple "$dmg"
|
||||
gh release upload "$TAG" "$dmg" --clobber
|
||||
done
|
||||
# Portable Windows builds (#1857): on Windows Tauri embeds the
|
||||
# frontend in the exe and WebView2 is a system component, so zipping
|
||||
# the raw exe gives an unpack-and-run alternative to the installers.
|
||||
- name: Portable zip
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
$target = "${{ matrix.target }}"
|
||||
$arch = if ($target -like "x86_64*") { "x64" } else { "arm64" }
|
||||
$version = $env:TAG -replace '^v', ''
|
||||
$asset = "OpenIDEA_${version}_windows_${arch}_portable.zip"
|
||||
$dir = "target/$target/release"
|
||||
$files = @("$dir/openidea.exe")
|
||||
if (Test-Path "$dir/WebView2Loader.dll") {
|
||||
$files += "$dir/WebView2Loader.dll"
|
||||
}
|
||||
Compress-Archive -Path $files -DestinationPath $asset -Force
|
||||
$hash = (Get-FileHash $asset -Algorithm SHA256).Hash.ToLower()
|
||||
"$hash $asset" | Out-File -Encoding ascii "$asset.sha256"
|
||||
gh release upload $env:TAG $asset "$asset.sha256" --clobber
|
||||
|
||||
# The remote development server, per host platform it can run on. The desktop
|
||||
# app downloads the one for the host (ide-tools `server`) and installs it over SSH.
|
||||
@@ -355,3 +377,10 @@ jobs:
|
||||
await github.rest.repos.updateRelease({
|
||||
...context.repo, release_id: Number(process.env.RELEASE_ID), draft: false,
|
||||
});
|
||||
|
||||
# The China mirror the updater's CNB source reads; a failure here leaves the GitHub release as is.
|
||||
cnb-mirror:
|
||||
needs: publish
|
||||
uses: ./.github/workflows/cnb-mirror.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
Generated
+44
-92
@@ -4106,7 +4106,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4129,7 +4129,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4143,7 +4143,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4154,7 +4154,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dirs 6.0.0",
|
||||
@@ -4170,7 +4170,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
@@ -4179,7 +4179,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4196,7 +4196,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4210,11 +4210,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
"ide-language",
|
||||
"libc",
|
||||
"memchr",
|
||||
"parking_lot",
|
||||
"portable-pty",
|
||||
@@ -4229,7 +4231,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"bb8",
|
||||
"dirs 6.0.0",
|
||||
@@ -4256,7 +4258,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4269,7 +4271,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4289,7 +4291,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4301,7 +4303,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4314,9 +4316,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
"criterion",
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4375,7 +4378,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4393,7 +4396,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4415,7 +4418,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4432,7 +4435,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4488,7 +4491,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4514,7 +4517,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4537,7 +4540,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"ide-core",
|
||||
@@ -4558,7 +4561,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4571,7 +4574,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"globset",
|
||||
"ide-core",
|
||||
@@ -4589,12 +4592,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"ide-build",
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"portable-pty",
|
||||
@@ -4612,7 +4616,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4631,7 +4635,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"globset",
|
||||
@@ -4651,7 +4655,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4664,7 +4668,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4673,7 +4677,6 @@ dependencies = [
|
||||
"keyring-core",
|
||||
"parking_lot",
|
||||
"russh",
|
||||
"russh-config",
|
||||
"russh-sftp",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4686,7 +4689,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4701,7 +4704,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4714,7 +4717,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4727,7 +4730,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4748,7 +4751,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4769,7 +4772,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4791,7 +4794,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"open",
|
||||
@@ -4807,7 +4810,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5423,10 +5426,7 @@ version = "0.1.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"libc",
|
||||
"plain",
|
||||
"redox_syscall 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6012,7 +6012,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.6.2",
|
||||
"dispatch2",
|
||||
"objc2 0.6.5",
|
||||
]
|
||||
@@ -6357,7 +6356,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -6403,7 +6402,6 @@ dependencies = [
|
||||
"ide-workspace",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-web-kit 0.3.2",
|
||||
"parking_lot",
|
||||
@@ -6603,7 +6601,7 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"redox_syscall 0.5.18",
|
||||
"redox_syscall",
|
||||
"smallvec",
|
||||
"windows-link",
|
||||
]
|
||||
@@ -6773,12 +6771,6 @@ version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
|
||||
[[package]]
|
||||
name = "plain"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
|
||||
|
||||
[[package]]
|
||||
name = "plist"
|
||||
version = "1.10.2"
|
||||
@@ -7236,15 +7228,6 @@ dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_users"
|
||||
version = "0.5.3"
|
||||
@@ -7529,20 +7512,6 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "russh-config"
|
||||
version = "0.58.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "993346101d4741a59c82bafc6b645c52ce3e7b0820f13e4b5d48cdb591e3d955"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"globset",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"whoami 1.6.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "russh-cryptovec"
|
||||
version = "0.62.0"
|
||||
@@ -8360,7 +8329,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-quartz-core 0.3.2",
|
||||
"raw-window-handle",
|
||||
"redox_syscall 0.5.18",
|
||||
"redox_syscall",
|
||||
"tracing",
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
@@ -8624,7 +8593,7 @@ dependencies = [
|
||||
"stringprep",
|
||||
"thiserror 2.0.21",
|
||||
"tracing",
|
||||
"whoami 2.1.3",
|
||||
"whoami",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -10566,12 +10535,6 @@ dependencies = [
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasite"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.129"
|
||||
@@ -11146,17 +11109,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "whoami"
|
||||
version = "1.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d"
|
||||
dependencies = [
|
||||
"libredox",
|
||||
"wasite",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "whoami"
|
||||
version = "2.1.3"
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.37"
|
||||
version = "0.1.38"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -25,7 +25,9 @@ OpenIDEA brings the IntelliJ IDEA way of working — its keymap, its tool window
|
||||
its search-everything habits — to a native app with a Rust core.
|
||||
|
||||
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
|
||||
for 60+ languages. Builds for macOS, Windows and Linux.
|
||||
for 60+ languages. Builds for macOS, Windows and Linux. On Windows, if you'd
|
||||
rather skip the installer, each release also ships a portable zip — unpack it
|
||||
and run `openidea.exe`.
|
||||
|
||||
## Benchmark
|
||||
|
||||
@@ -64,11 +66,14 @@ the [official plugins](plugins/official). The plugin API is still a preview.
|
||||
|
||||
<img src="docs/assets/wechat-group.png" alt="WeChat group QR code" width="200">
|
||||
|
||||
### Contributors
|
||||
|
||||
<a href="https://github.com/l0ng-ai/openidea/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=l0ng-ai/openidea&max=100" alt="OpenIDEA contributors">
|
||||
</a>
|
||||
|
||||
## License
|
||||
|
||||
[Apache 2.0](LICENSE). Bundled third-party assets are listed in [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md).
|
||||
|
||||
Database tool window notes, including Oracle Instant Client setup, are in
|
||||
[`docs/databases.md`](docs/databases.md).
|
||||
|
||||
<sub>Not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.</sub>
|
||||
+273
-23
@@ -54,6 +54,9 @@ const SESSION_STATE: [&str; 5] =
|
||||
pub(crate) const RETRY_UPDATE: &str = "openidea_retry";
|
||||
/// A native agent's own update: the usage limits of its account (see [`AgentLimit`]).
|
||||
pub(crate) const LIMITS_UPDATE: &str = "openidea_limits";
|
||||
/// A native agent's own update: the background tasks its session runs
|
||||
/// (see [`TaskState::background_tasks`]).
|
||||
pub(crate) const BACKGROUND_TASKS_UPDATE: &str = "openidea_background_tasks";
|
||||
/// Referenced files up to this size are embedded in the prompt (when the agent takes it).
|
||||
const MAX_EMBED: u64 = 256 * 1024;
|
||||
/// How long a probe waits for the agent to answer `initialize`.
|
||||
@@ -106,6 +109,9 @@ struct Shared {
|
||||
struct Known {
|
||||
#[serde(default)]
|
||||
config: Vec<AgentConfigOption>,
|
||||
/// Thinking levels reported for each model value, including its last choice.
|
||||
#[serde(default, rename = "thoughtLevels")]
|
||||
thought_levels: BTreeMap<String, Vec<AgentConfigOption>>,
|
||||
/// By project root: skills and custom commands differ per project.
|
||||
#[serde(default, rename = "projectCommands")]
|
||||
commands: HashMap<String, Vec<AgentCommand>>,
|
||||
@@ -125,6 +131,8 @@ impl Shared {
|
||||
|
||||
fn known_config(&self, provider: &str) -> Vec<AgentConfigOption> {
|
||||
let mut config = self.known.lock().get(provider).map(|k| k.config.clone()).unwrap_or_default();
|
||||
// Model-specific options are offered separately, never as provider-wide defaults.
|
||||
config.retain(|o| o.category.as_deref() != Some("thought_level"));
|
||||
config::add_client_options(provider, &mut config);
|
||||
if let Some((o, v)) = config::bypass_mode(&config).map(|(o, v)| (o.id.clone(), v.value.clone()))
|
||||
&& let Some(o) = config.iter_mut().find(|c| c.id == o)
|
||||
@@ -147,14 +155,31 @@ impl Shared {
|
||||
self.paths.project_root.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn remember(&self, provider: &str, config: Option<&[AgentConfigOption]>, commands: Option<&[AgentCommand]>) {
|
||||
/// Cache levels only when `model` confirms which model the session reported them for.
|
||||
fn remember(
|
||||
&self,
|
||||
provider: &str,
|
||||
config: Option<&[AgentConfigOption]>,
|
||||
commands: Option<&[AgentCommand]>,
|
||||
model: Option<&str>,
|
||||
) {
|
||||
let snapshot = {
|
||||
let mut cache = self.known.lock();
|
||||
let known = cache.entry(provider.to_owned()).or_default();
|
||||
let mut changed = false;
|
||||
if let Some(c) = config.filter(|c| !c.is_empty() && known.config != *c) {
|
||||
known.config = c.to_vec();
|
||||
changed = true;
|
||||
if let Some(c) = config {
|
||||
if let Some(model) = model {
|
||||
let levels: Vec<_> =
|
||||
c.iter().filter(|o| o.category.as_deref() == Some("thought_level")).cloned().collect();
|
||||
if known.thought_levels.get(model) != Some(&levels) {
|
||||
known.thought_levels.insert(model.to_owned(), levels);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if !c.is_empty() && known.config != c {
|
||||
known.config = c.to_vec();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
let root = self.root_key();
|
||||
if let Some(c) =
|
||||
@@ -204,11 +229,16 @@ struct TaskState {
|
||||
pending_rollback: u32,
|
||||
/// A turn is running or about to (prompts arriving now are queued).
|
||||
busy: bool,
|
||||
/// Background tasks the agent reported as running (`run_in_background` commands and
|
||||
/// the like), as it sent them: unlike a turn they outlive it, so an idle release
|
||||
/// waits for the last one. A (re)started process runs nothing yet.
|
||||
background_tasks: Vec<Value>,
|
||||
}
|
||||
|
||||
/// A running agent and its session.
|
||||
#[derive(Clone)]
|
||||
struct Live {
|
||||
sign_in_message: String,
|
||||
peer: acp::Conn,
|
||||
session: String,
|
||||
capabilities: AgentCapabilities,
|
||||
@@ -239,6 +269,9 @@ struct Task {
|
||||
turn_started: AtomicBool,
|
||||
/// Turns sent so far: an idle release scheduled before the latest one is void.
|
||||
turns: AtomicU64,
|
||||
/// Bumped when the agent's last background task finishes: an idle release scheduled
|
||||
/// before that is void, the usual delay starts over from the report.
|
||||
idle_epoch: AtomicU64,
|
||||
/// Settings already sent this session (`(option, value)`), so a refusal is not retried.
|
||||
config_sent: Mutex<HashSet<(String, String)>>,
|
||||
dirty: Mutex<BTreeSet<(Session, usize)>>,
|
||||
@@ -297,6 +330,7 @@ impl AgentManager {
|
||||
f.task.status = AgentStatus::Ready;
|
||||
}
|
||||
f.task.retry = None;
|
||||
f.task.background.clear();
|
||||
let task = Task::restore(f, shared.clone());
|
||||
task.state.lock().conversation.settle(now_ms());
|
||||
tasks.insert(task.id.clone(), task);
|
||||
@@ -323,6 +357,8 @@ impl AgentManager {
|
||||
.map(|p| {
|
||||
let mut info = provider::describe(p);
|
||||
info.config = self.shared.known_config(&p.id);
|
||||
info.thought_levels =
|
||||
self.shared.known.lock().get(&p.id).map(|k| k.thought_levels.clone()).unwrap_or_default();
|
||||
info.commands = self.shared.known_commands(&p.id);
|
||||
info
|
||||
})
|
||||
@@ -442,6 +478,18 @@ impl AgentManager {
|
||||
o.current = Some(choice.value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(model) = model_of(&config)
|
||||
&& let Some(levels) = self.shared.known.lock().get(&spec.id).and_then(|k| k.thought_levels.get(&model))
|
||||
{
|
||||
config.extend(levels.iter().cloned().map(|mut o| {
|
||||
if let Some(choice) =
|
||||
req.config.iter().find(|c| c.id == o.id && o.values.iter().any(|v| v.value == c.value))
|
||||
{
|
||||
o.current = Some(choice.value.clone());
|
||||
}
|
||||
o
|
||||
}));
|
||||
}
|
||||
let now = now_ms();
|
||||
let task = AgentTask {
|
||||
project_root,
|
||||
@@ -465,6 +513,7 @@ impl AgentManager {
|
||||
capabilities: self.shared.probes.lock().get(&spec.id).map(|p| p.capabilities).unwrap_or_default(),
|
||||
resets_ms: None,
|
||||
retry: None,
|
||||
background: Box::default(),
|
||||
};
|
||||
let file = TaskFile {
|
||||
task: task.clone(),
|
||||
@@ -588,6 +637,8 @@ impl AgentManager {
|
||||
o.clone()
|
||||
};
|
||||
let live = task.live.lock().clone().filter(|l| !l.peer.is_closed());
|
||||
let mut model_options =
|
||||
target.category.as_deref() != Some("model") || target.current.as_deref() == Some(value.as_str());
|
||||
if let Some(live) = live.filter(|_| option != config::CURSOR_APPROVAL) {
|
||||
let (method, mut params) = config::set_request(&target, &value);
|
||||
params["sessionId"] = json!(live.session);
|
||||
@@ -595,10 +646,14 @@ impl AgentManager {
|
||||
live.peer.request(method, params, None).await.map_err(|e| IdeError::internal(task.describe(e)))?;
|
||||
if let Some(options) = reply.get("configOptions") {
|
||||
config::merge_update(&mut task.state.lock().task.config, options);
|
||||
model_options = true;
|
||||
}
|
||||
}
|
||||
{
|
||||
let mut s = task.state.lock();
|
||||
if !model_options {
|
||||
s.task.config.retain(|o| o.category.as_deref() != Some("thought_level"));
|
||||
}
|
||||
s.wanted.retain(|c| c.id != option);
|
||||
s.wanted.push(AgentConfigChoice { id: option.to_owned(), value: value.clone() });
|
||||
if let Some(o) = s.task.config.iter_mut().find(|o| o.id == option) {
|
||||
@@ -607,8 +662,9 @@ impl AgentManager {
|
||||
s.task.model = model_of(&s.task.config).or(s.task.model.take());
|
||||
let provider = s.task.provider.clone();
|
||||
let config = s.task.config.clone();
|
||||
let model = s.task.model.clone().filter(|_| model_options);
|
||||
drop(s);
|
||||
task.shared.remember(&provider, Some(&config), None);
|
||||
task.shared.remember(&provider, Some(&config), None, model.as_deref());
|
||||
}
|
||||
task.approve_pending();
|
||||
task.persist();
|
||||
@@ -659,6 +715,7 @@ impl AgentManager {
|
||||
queue: Vec::new(),
|
||||
resets_ms: None,
|
||||
retry: None,
|
||||
background: Box::default(),
|
||||
..s.task.clone()
|
||||
};
|
||||
TaskFile {
|
||||
@@ -797,6 +854,21 @@ impl AgentManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stops background task `background` of task `id`.
|
||||
pub async fn stop_background(&self, id: &str, background: &str) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
let live = task.live.lock().clone().ok_or_else(|| IdeError::invalid("the agent is not running"))?;
|
||||
if !live.capabilities.background_tasks {
|
||||
return Err(IdeError::invalid("this agent can't stop a background task"));
|
||||
}
|
||||
let _: Value = live
|
||||
.peer
|
||||
.request("_openidea/stop_task", json!({ "sessionId": live.session, "taskId": background }), None)
|
||||
.await
|
||||
.map_err(|error| IdeError::internal(task.describe(error)))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Answers permission request `permission` with option `option` (`None` cancels it).
|
||||
pub fn respond(&self, id: &str, permission: u32, option: Option<String>) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
@@ -909,6 +981,7 @@ impl Task {
|
||||
before: Arc::new(file.before),
|
||||
pending_rollback: file.pending_rollback,
|
||||
busy: false,
|
||||
background_tasks: Vec::new(),
|
||||
}),
|
||||
live: Mutex::new(None),
|
||||
connecting: tokio::sync::Mutex::new(()),
|
||||
@@ -919,6 +992,7 @@ impl Task {
|
||||
cancel_pending: AtomicBool::new(false),
|
||||
turn_started: AtomicBool::new(false),
|
||||
turns: AtomicU64::new(0),
|
||||
idle_epoch: AtomicU64::new(0),
|
||||
config_sent: Mutex::new(HashSet::new()),
|
||||
dirty: Mutex::new(BTreeSet::new()),
|
||||
flush_scheduled: AtomicBool::new(false),
|
||||
@@ -955,6 +1029,39 @@ impl Task {
|
||||
self.emit_task();
|
||||
}
|
||||
|
||||
/// Keeps the agent's background tasks that outlive its turn. Returns whether the last
|
||||
/// one just finished, so the idle release starts over from this report.
|
||||
fn set_background_tasks(&self, tasks: Vec<Value>) -> bool {
|
||||
let (emptied, shown) = {
|
||||
let mut state = self.state.lock();
|
||||
if state.background_tasks == tasks {
|
||||
return false;
|
||||
}
|
||||
let emptied = !state.background_tasks.is_empty() && tasks.is_empty();
|
||||
let background = shown_background(&tasks, &state.task.background);
|
||||
let shown = background != *state.task.background;
|
||||
*state.task.background = background;
|
||||
state.background_tasks = tasks;
|
||||
if emptied {
|
||||
// Void a release scheduled while the tasks still ran: it would stop the
|
||||
// agent sooner than the usual delay after this one.
|
||||
self.idle_epoch.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
(emptied, shown)
|
||||
};
|
||||
if shown {
|
||||
self.emit_task();
|
||||
}
|
||||
emptied
|
||||
}
|
||||
|
||||
fn clear_shown_background(&self) {
|
||||
let cleared = !std::mem::take(&mut self.state.lock().task.background).is_empty();
|
||||
if cleared {
|
||||
self.emit_task();
|
||||
}
|
||||
}
|
||||
|
||||
fn set_status(&self, status: AgentStatus, error: Option<String>) {
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
@@ -1073,19 +1180,32 @@ impl Task {
|
||||
/// Stops the agent's process once the task has stayed idle for [`IDLE_RELEASE`], so
|
||||
/// finished tasks don't keep an agent (and what it started) running. Only an agent that
|
||||
/// reloads its session: the next message starts it again with the conversation intact.
|
||||
/// A turn's background tasks outlive it: the release waits for the last one, and the
|
||||
/// delay runs again once the agent reports it done.
|
||||
fn release_when_idle(self: &Arc<Self>) {
|
||||
let turn = self.turns.load(Ordering::Acquire);
|
||||
let epoch = self.idle_epoch.load(Ordering::Acquire);
|
||||
let delay = Duration::from_millis(self.shared.idle_release_ms.load(Ordering::Relaxed));
|
||||
let task = Arc::downgrade(self);
|
||||
self.shared.runtime.spawn(async move {
|
||||
tokio::time::sleep(delay).await;
|
||||
let Some(task) = task.upgrade() else { return };
|
||||
if task.turns.load(Ordering::Acquire) != turn
|
||||
|| task.idle_epoch.load(Ordering::Acquire) != epoch
|
||||
|| task.state.lock().busy
|
||||
|| !task.permissions.lock().is_empty()
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Stopping now would orphan what the agent still runs in the background: its
|
||||
// result would never reach the conversation. Wait for the last task; when it
|
||||
// is done, its report voids this schedule and starts the delay over.
|
||||
let waiting = !task.state.lock().background_tasks.is_empty();
|
||||
if waiting && task.live.lock().as_ref().is_some_and(|l| l.resumable && !l.peer.is_closed()) {
|
||||
tracing::debug!("agent task {}: idle, waiting for its background tasks", task.id);
|
||||
task.release_when_idle();
|
||||
return;
|
||||
}
|
||||
let live = {
|
||||
let mut live = task.live.lock();
|
||||
if live.as_ref().is_some_and(|l| l.resumable && !l.peer.is_closed()) { live.take() } else { None }
|
||||
@@ -1093,6 +1213,7 @@ impl Task {
|
||||
if let Some(live) = live {
|
||||
tracing::debug!("agent task {}: idle, stopping the agent until the next message", task.id);
|
||||
live.peer.kill();
|
||||
task.clear_shown_background();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1111,6 +1232,7 @@ impl Task {
|
||||
if !gone && let Some(live) = self.live.lock().take() {
|
||||
live.peer.kill();
|
||||
}
|
||||
self.clear_shown_background();
|
||||
match failure.limit {
|
||||
Some(resets) => {
|
||||
self.state.lock().task.resets_ms = resets;
|
||||
@@ -1218,11 +1340,7 @@ impl Task {
|
||||
match e {
|
||||
// Signed out, or the account was refused (Claude Code: "API Error: 403").
|
||||
RpcError::Server { message, .. } if message.to_lowercase().contains("auth") => {
|
||||
let provider = self.state.lock().task.provider.clone();
|
||||
Failure::from(match self.shared.spec(&provider) {
|
||||
Some(spec) => format!("{} needs you to sign in. {}", spec.name, spec.login_hint),
|
||||
None => message,
|
||||
})
|
||||
Failure::from(self.live.lock().as_ref().map(|live| live.sign_in_message.clone()).unwrap_or(message))
|
||||
}
|
||||
e => Failure::from(self.describe(e)),
|
||||
}
|
||||
@@ -1240,6 +1358,11 @@ impl Task {
|
||||
(s.task.provider.clone(), s.task.cwd.0.clone(), s.session_id.clone())
|
||||
};
|
||||
let spec = self.shared.spec(&provider_id).ok_or_else(|| format!("unknown agent {provider_id}"))?;
|
||||
let launch_cwd = cwd.clone();
|
||||
let spec = tokio::task::spawn_blocking(move || spec.resolve_for_launch(&launch_cwd))
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let sign_in_message = spec.sign_in_message();
|
||||
self.stderr.lock().clear();
|
||||
self.config_sent.lock().clear();
|
||||
let weak = Arc::downgrade(self);
|
||||
@@ -1285,7 +1408,7 @@ impl Task {
|
||||
.await
|
||||
.map_err(|e| match e {
|
||||
RpcError::Server { ref message, .. } if message.to_lowercase().contains("auth") => {
|
||||
format!("{} needs you to sign in. {}", spec.name, spec.login_hint)
|
||||
sign_in_message.clone()
|
||||
}
|
||||
e => self.describe(e),
|
||||
})?;
|
||||
@@ -1311,11 +1434,21 @@ impl Task {
|
||||
// A session that reports none keeps the last known ones, but what is set is unknown.
|
||||
let reported = config::options_of(&result);
|
||||
let known = !reported.is_empty();
|
||||
let (mut options, wanted) = {
|
||||
if known {
|
||||
self.shared.remember(&provider_id, Some(&reported), None, model_of(&reported).as_deref());
|
||||
}
|
||||
let (mut options, mut wanted) = {
|
||||
let s = self.state.lock();
|
||||
(if known { reported } else { s.task.config.clone() }, s.wanted.clone())
|
||||
};
|
||||
config::add_client_options(&provider_id, &mut options);
|
||||
// Changing model can replace the effort choices; validate those only afterwards.
|
||||
wanted.sort_by_key(|c| match options.iter().find(|o| o.id == c.id).and_then(|o| o.category.as_deref()) {
|
||||
Some("model") => 0,
|
||||
Some("thought_level") => 2,
|
||||
_ => 1,
|
||||
});
|
||||
let mut model_options = known;
|
||||
for choice in &wanted {
|
||||
// An option the session doesn't offer yet is set once it does (`apply_late_choices`).
|
||||
let Some(o) = options.iter().find(|o| o.id == choice.id).cloned() else { continue };
|
||||
@@ -1325,6 +1458,9 @@ impl Task {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if o.category.as_deref() == Some("thought_level") && !model_options {
|
||||
continue;
|
||||
}
|
||||
let already = known && o.current.as_deref() == Some(choice.value.as_str());
|
||||
if already || !o.values.iter().any(|v| v.value == choice.value) {
|
||||
continue;
|
||||
@@ -1336,6 +1472,12 @@ impl Task {
|
||||
Ok(reply) => {
|
||||
if let Some(fresh) = reply.get("configOptions") {
|
||||
config::merge_update(&mut options, fresh);
|
||||
model_options = true;
|
||||
} else if o.category.as_deref() == Some("model") {
|
||||
if o.current.as_deref() != Some(choice.value.as_str()) {
|
||||
options.retain(|o| o.category.as_deref() != Some("thought_level"));
|
||||
}
|
||||
model_options = false;
|
||||
}
|
||||
if let Some(o) = options.iter_mut().find(|o| o.id == choice.id) {
|
||||
o.current = Some(choice.value.clone());
|
||||
@@ -1344,17 +1486,21 @@ impl Task {
|
||||
Err(e) => tracing::warn!("agent task {}: setting {} to {} failed: {e}", self.id, o.id, choice.value),
|
||||
}
|
||||
}
|
||||
self.shared.remember(&provider_id, Some(&options), None);
|
||||
let model = model_of(&options).filter(|_| model_options);
|
||||
self.shared.remember(&provider_id, Some(&options), None, model.as_deref());
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
s.task.model = model_of(&options).or(s.task.model.take());
|
||||
s.task.config = options;
|
||||
s.task.capabilities = capabilities;
|
||||
s.session_id = Some(session_id.clone());
|
||||
// The (re)started process runs nothing yet: whatever it reports next is all of it.
|
||||
s.background_tasks = Vec::new();
|
||||
s.task.background.clear();
|
||||
}
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
let live = Live { peer, session: session_id, capabilities, embedded, resumable: can_load };
|
||||
let live = Live { sign_in_message, peer, session: session_id, capabilities, embedded, resumable: can_load };
|
||||
*self.live.lock() = Some(live.clone());
|
||||
Ok(live)
|
||||
}
|
||||
@@ -1390,11 +1536,19 @@ impl Task {
|
||||
let mut s = task.state.lock();
|
||||
if let Some(fresh) = reply.get("configOptions") {
|
||||
config::merge_update(&mut s.task.config, fresh);
|
||||
} else if option.category.as_deref() == Some("model") {
|
||||
s.task.config.retain(|o| o.category.as_deref() != Some("thought_level"));
|
||||
}
|
||||
if let Some(o) = s.task.config.iter_mut().find(|o| o.id == option.id) {
|
||||
o.current = Some(value);
|
||||
}
|
||||
s.task.model = model_of(&s.task.config).or(s.task.model.take());
|
||||
let model = s.task.model.clone().filter(|_| {
|
||||
reply.get("configOptions").is_some() || option.category.as_deref() != Some("model")
|
||||
});
|
||||
let (provider, options) = (s.task.provider.clone(), s.task.config.clone());
|
||||
drop(s);
|
||||
task.shared.remember(&provider, Some(&options), None, model.as_deref());
|
||||
}
|
||||
Err(e) => tracing::warn!("agent task {}: setting {} to {value} failed: {e}", task.id, option.id),
|
||||
}
|
||||
@@ -1443,6 +1597,16 @@ impl Task {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if kind == BACKGROUND_TASKS_UPDATE {
|
||||
if !self.replaying.load(Ordering::Acquire) {
|
||||
let tasks = update.get("tasks").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
// The last one finished while the agent is up: the usual delay starts over.
|
||||
if self.set_background_tasks(tasks) {
|
||||
self.release_when_idle();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if kind == "session_info_update" {
|
||||
// The agent's own title for the session replaces the first line of the prompt.
|
||||
let title = update.get("title").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty());
|
||||
@@ -1483,11 +1647,15 @@ impl Task {
|
||||
}
|
||||
};
|
||||
if task_changed {
|
||||
let (config, commands) = {
|
||||
let (config, commands, model) = {
|
||||
let s = self.state.lock();
|
||||
(s.task.config.clone(), s.task.commands.clone())
|
||||
(
|
||||
s.task.config.clone(),
|
||||
s.task.commands.clone(),
|
||||
s.task.model.clone().filter(|_| kind == "config_option_update"),
|
||||
)
|
||||
};
|
||||
self.shared.remember(&provider, Some(&config), Some(&commands));
|
||||
self.shared.remember(&provider, Some(&config), Some(&commands), model.as_deref());
|
||||
if kind != "usage_update" {
|
||||
self.persist();
|
||||
}
|
||||
@@ -1524,12 +1692,17 @@ impl Task {
|
||||
/// Blocks the calling (blocking-pool) thread until the user answers.
|
||||
fn ask_permission(self: &Arc<Self>, params: &Value) -> Value {
|
||||
let id = self.next_permission.fetch_add(1, Ordering::Relaxed);
|
||||
let (questions, by_index) = asked_questions(params);
|
||||
let title = params
|
||||
.pointer("/toolCall/title")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|t| !t.is_empty())
|
||||
.unwrap_or("The agent asks for permission")
|
||||
.to_owned();
|
||||
// An agent that answers by index titles its request "Ask user N question(s)"; its
|
||||
// first question says what it wants, as the Claude Code adapter titles its own.
|
||||
let title =
|
||||
if by_index { questions.first().map(|question| question.question.clone()).unwrap_or(title) } else { title };
|
||||
// A subagent's request is answered in the task's conversation, named after the subagent.
|
||||
let session = params.get("sessionId").and_then(Value::as_str);
|
||||
let title = match session.and_then(|s| self.state.lock().conversation.label(s)) {
|
||||
@@ -1551,17 +1724,34 @@ impl Task {
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let asked: Vec<String> = questions.iter().map(|question| question.question.clone()).collect();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let entry = self.push_entry(AgentEntry::Permission { id, title, options: options.clone(), chosen: None });
|
||||
let entry =
|
||||
self.push_entry(AgentEntry::Permission { id, title, options: options.clone(), questions, chosen: None });
|
||||
self.permissions.lock().insert(id, tx);
|
||||
self.set_status(AgentStatus::NeedsInput, None);
|
||||
self.approve_pending();
|
||||
|
||||
let answer = rx.recv().ok().flatten();
|
||||
let name = answer
|
||||
.as_ref()
|
||||
.and_then(|a| options.iter().find(|o| &o.id == a))
|
||||
.map_or_else(|| "Cancelled".to_owned(), |o| o.name.clone());
|
||||
let answers = answer
|
||||
.as_deref()
|
||||
.filter(|_| !asked.is_empty())
|
||||
.and_then(|reply| serde_json::from_str::<serde_json::Map<String, Value>>(reply).ok());
|
||||
let name = match &answers {
|
||||
Some(answers) => asked
|
||||
.iter()
|
||||
.filter_map(|question| answers.get(question))
|
||||
.map(|items| match items {
|
||||
Value::Array(items) => items.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", "),
|
||||
item => item.as_str().unwrap_or_default().to_owned(),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("; "),
|
||||
None => answer
|
||||
.as_ref()
|
||||
.and_then(|reply| options.iter().find(|option| &option.id == reply))
|
||||
.map_or_else(|| "Cancelled".to_owned(), |option| option.name.clone()),
|
||||
};
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
if let Some(AgentEntry::Permission { chosen, .. }) = s.conversation.main.entries.get_mut(entry) {
|
||||
@@ -1573,6 +1763,31 @@ impl Task {
|
||||
if !still_asking && self.state.lock().task.status == AgentStatus::NeedsInput {
|
||||
self.set_status(AgentStatus::Running, None);
|
||||
}
|
||||
// An agent that answers by index reads the answers beside the outcome, keyed by
|
||||
// question index, with its Submit option chosen; anything less cancels the request.
|
||||
if by_index {
|
||||
let submit = options.iter().find(|option| option.kind == "allow_once").or_else(|| options.first());
|
||||
return match (answers.as_ref(), submit) {
|
||||
(Some(answers), Some(submit)) => {
|
||||
let picked: serde_json::Map<String, Value> = asked
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, question)| {
|
||||
let items = answers.get(question)?;
|
||||
let answer = match items {
|
||||
Value::Array(items) => {
|
||||
items.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
item => item.as_str().unwrap_or_default().to_owned(),
|
||||
};
|
||||
Some((index.to_string(), json!(answer)))
|
||||
})
|
||||
.collect();
|
||||
json!({ "outcome": { "outcome": "selected", "optionId": submit.id }, "answers": picked })
|
||||
}
|
||||
_ => json!({ "outcome": { "outcome": "cancelled" } }),
|
||||
};
|
||||
}
|
||||
match answer {
|
||||
Some(option) => json!({ "outcome": { "outcome": "selected", "optionId": option } }),
|
||||
None => json!({ "outcome": { "outcome": "cancelled" } }),
|
||||
@@ -1586,7 +1801,10 @@ impl Task {
|
||||
}
|
||||
let mut pending = self.permissions.lock();
|
||||
for entry in s.conversation.main.entries.iter().rev() {
|
||||
if let AgentEntry::Permission { id, options, chosen: None, .. } = entry
|
||||
// A request with questions is never satisfied by a bypass: its Submit option
|
||||
// would answer with no answers.
|
||||
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)
|
||||
{
|
||||
@@ -1617,6 +1835,7 @@ impl Task {
|
||||
self.cancel_permissions();
|
||||
let live = self.live.lock().take()?;
|
||||
live.peer.kill();
|
||||
self.clear_shown_background();
|
||||
Some(live.peer)
|
||||
}
|
||||
}
|
||||
@@ -1650,6 +1869,23 @@ fn clean(mut prompt: AgentPrompt) -> Option<AgentPrompt> {
|
||||
(!prompt.text.is_empty() || !prompt.images.is_empty() || !prompt.files.is_empty()).then_some(prompt)
|
||||
}
|
||||
|
||||
/// The questions a permission request asks, and whether they answer by question index.
|
||||
/// The Claude Code adapter carries them as `_meta.questions`, answered as the option id;
|
||||
/// Qwen Code (ACP) as `_meta.qwenQuestions`, answered with `answers` keyed by index beside
|
||||
/// the id of its Submit option.
|
||||
fn asked_questions(params: &Value) -> (Vec<AgentQuestion>, bool) {
|
||||
for (pointer, by_index) in [("/toolCall/_meta/questions", false), ("/toolCall/_meta/qwenQuestions", true)] {
|
||||
if let Some(questions) = params
|
||||
.pointer(pointer)
|
||||
.and_then(|questions| serde_json::from_value::<Vec<AgentQuestion>>(questions.clone()).ok())
|
||||
.filter(|questions| !questions.is_empty())
|
||||
{
|
||||
return (questions, by_index);
|
||||
}
|
||||
}
|
||||
(Vec::new(), false)
|
||||
}
|
||||
|
||||
/// ACP content blocks: the text, each file (embedded when its text is in `contents`, else
|
||||
/// a `resource_link`), then the images.
|
||||
fn blocks(prompt: &AgentPrompt, contents: &[Option<String>]) -> Vec<Value> {
|
||||
@@ -1730,6 +1966,19 @@ fn client_info() -> Value {
|
||||
}
|
||||
|
||||
/// What the agent said it can do, and whether it takes embedded files.
|
||||
fn shown_background(tasks: &[Value], known: &[AgentBackgroundTask]) -> Vec<AgentBackgroundTask> {
|
||||
let now = now_ms();
|
||||
tasks
|
||||
.iter()
|
||||
.filter_map(|task| {
|
||||
let id = task.get("task_id")?.as_str()?.to_owned();
|
||||
let started_ms = known.iter().find(|seen| seen.id == id).map_or(now, |seen| seen.started_ms);
|
||||
let text = |key: &str| task.get(key).and_then(Value::as_str).unwrap_or_default().to_owned();
|
||||
Some(AgentBackgroundTask { id, kind: text("task_type"), description: text("description"), started_ms })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn capabilities_of(init: &acp::Negotiated) -> (AgentCapabilities, bool) {
|
||||
let meta = |p: &str| init.meta(p).and_then(Value::as_bool) == Some(true);
|
||||
let capabilities = AgentCapabilities {
|
||||
@@ -1737,6 +1986,7 @@ fn capabilities_of(init: &acp::Negotiated) -> (AgentCapabilities, bool) {
|
||||
fork: init.session("fork"),
|
||||
rollback: meta("/openidea/rollback"),
|
||||
steer: meta("/openidea/steer"),
|
||||
background_tasks: meta("/openidea/backgroundTasks"),
|
||||
};
|
||||
(capabilities, init.prompt("embeddedContext"))
|
||||
}
|
||||
|
||||
@@ -34,6 +34,8 @@ pub struct AgentCapabilities {
|
||||
pub rollback: bool,
|
||||
/// A message can join the running turn instead of waiting for it.
|
||||
pub steer: bool,
|
||||
/// It reports its background tasks and stops them one by one.
|
||||
pub background_tasks: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -89,6 +91,22 @@ pub struct AgentTask {
|
||||
/// by its next output or any status change.
|
||||
#[serde(default)]
|
||||
pub retry: Option<AgentRetry>,
|
||||
/// What the agent runs in the background (shells, subagents, monitors), oldest first.
|
||||
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
|
||||
#[serde(default)]
|
||||
pub background: Box<Vec<AgentBackgroundTask>>,
|
||||
}
|
||||
|
||||
/// A task the agent runs in the background while the conversation goes on.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentBackgroundTask {
|
||||
pub id: String,
|
||||
/// What it is, as the agent names it (`local_bash`, `local_agent`, `monitor`…).
|
||||
pub kind: String,
|
||||
pub description: String,
|
||||
/// When the client first saw it (ms since the epoch).
|
||||
pub started_ms: f64,
|
||||
}
|
||||
|
||||
/// An API request the agent is about to retry.
|
||||
@@ -260,6 +278,28 @@ pub struct AgentPermissionOption {
|
||||
pub kind: String,
|
||||
}
|
||||
|
||||
/// A question the agent asks with `AskUserQuestion`, answered by picking options or typing.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentQuestion {
|
||||
#[serde(default)]
|
||||
pub header: String,
|
||||
pub question: String,
|
||||
#[serde(default)]
|
||||
pub multi_select: bool,
|
||||
pub options: Vec<AgentQuestionOption>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentQuestionOption {
|
||||
pub label: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
#[serde(default)]
|
||||
pub preview: Option<String>,
|
||||
}
|
||||
|
||||
/// One item of a task's conversation.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
@@ -332,6 +372,10 @@ pub enum AgentEntry {
|
||||
id: u32,
|
||||
title: String,
|
||||
options: Vec<AgentPermissionOption>,
|
||||
/// Set when the request asks `AskUserQuestion`'s questions; answered with a JSON object
|
||||
/// of question to answer instead of an option.
|
||||
#[serde(default)]
|
||||
questions: Vec<AgentQuestion>,
|
||||
/// Name of the chosen option, or `None` while pending. Cancelled requests read "Cancelled".
|
||||
chosen: Option<String>,
|
||||
},
|
||||
@@ -362,6 +406,9 @@ pub struct AgentProvider {
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Settings (models, modes…) the agent offered last time it ran; empty before its first session.
|
||||
pub config: Vec<AgentConfigOption>,
|
||||
/// Thinking-level options by model value; absent models have not reported their levels.
|
||||
#[serde(default)]
|
||||
pub thought_levels: BTreeMap<String, Vec<AgentConfigOption>>,
|
||||
/// Slash commands it offered last time.
|
||||
pub commands: Vec<AgentCommand>,
|
||||
pub source: AgentSource,
|
||||
|
||||
@@ -312,7 +312,7 @@ impl Shim {
|
||||
"loadSession": true,
|
||||
"promptCapabilities": { "image": true, "embeddedContext": true },
|
||||
"sessionCapabilities": { "fork": {} },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true } },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true } },
|
||||
},
|
||||
"agentInfo": { "name": "claude", "title": "Claude Code", "version": self.version() },
|
||||
"authMethods": [],
|
||||
@@ -396,6 +396,13 @@ impl Shim {
|
||||
session.steer(params.get("prompt").cloned().unwrap_or_default()).map_err(invalid)?;
|
||||
Ok(json!({}))
|
||||
}
|
||||
"_openidea/stop_task" => {
|
||||
let session = self.session(¶ms)?;
|
||||
let task = params.get("taskId").and_then(Value::as_str).ok_or_else(|| invalid("no taskId"))?;
|
||||
let proc = session.st.lock().proc.clone().ok_or_else(|| internal("Claude Code is not running"))?;
|
||||
rt.block_on(proc.control(json!({ "subtype": "stop_task", "task_id": task }))).map_err(internal)?;
|
||||
Ok(json!({}))
|
||||
}
|
||||
"_openidea/rollback" => {
|
||||
let session = self.session(¶ms)?;
|
||||
let turns = params.get("turns").and_then(Value::as_u64).unwrap_or(0) as usize;
|
||||
@@ -611,7 +618,8 @@ impl Session {
|
||||
session.on_exit(&reader_proc);
|
||||
}
|
||||
});
|
||||
let init = proc.control(json!({ "subtype": "initialize" })).await?;
|
||||
// Stop ends the turn only: the client stops background tasks one by one.
|
||||
let init = proc.control(json!({ "subtype": "initialize", "perTaskStopAffordance": true })).await?;
|
||||
let applied = proc.control(json!({ "subtype": "get_settings" })).await.unwrap_or_default();
|
||||
let chosen = {
|
||||
let mut st = self.st.lock();
|
||||
@@ -1109,38 +1117,46 @@ fn permission_result(
|
||||
}
|
||||
}
|
||||
|
||||
/// `AskUserQuestion`: each question as a permission request whose options are its
|
||||
/// answers; `None` when one is not answered.
|
||||
/// `AskUserQuestion`: one permission request carrying all its questions, answered with a
|
||||
/// JSON object of question to the chosen labels and typed text; `None` when skipped.
|
||||
async fn ask_questions<F, Fut>(input: &Value, call: &Value, ask: F) -> Option<Value>
|
||||
where
|
||||
F: Fn(Value, Value) -> Fut,
|
||||
Fut: std::future::Future<Output = Option<String>>,
|
||||
{
|
||||
let mut answers = serde_json::Map::new();
|
||||
for q in input.get("questions").and_then(Value::as_array).into_iter().flatten() {
|
||||
let question = q.get("question").and_then(Value::as_str).unwrap_or_default();
|
||||
let labels: Vec<&str> = q
|
||||
.get("options")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|o| o.get("label")?.as_str())
|
||||
.collect();
|
||||
let mut options: Vec<Value> = labels
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, l)| json!({ "optionId": format!("answer-{i}"), "name": l, "kind": "allow_once" }))
|
||||
.collect();
|
||||
options.push(json!({ "optionId": "reject", "name": "Skip", "kind": "reject_once" }));
|
||||
let mut call = call.clone();
|
||||
call["title"] = json!(question);
|
||||
let chosen = ask(call, Value::Array(options)).await?;
|
||||
let i: usize = chosen.strip_prefix("answer-")?.parse().ok()?;
|
||||
answers.insert(question.to_owned(), json!(labels.get(i)?));
|
||||
}
|
||||
let questions = input.get("questions")?;
|
||||
let mut call = call.clone();
|
||||
call["title"] = questions.pointer("/0/question").cloned().unwrap_or_else(|| json!("Claude has a question"));
|
||||
call["_meta"] = json!({ "questions": questions });
|
||||
let options = json!([{ "optionId": "reject", "name": "Skip", "kind": "reject_once" }]);
|
||||
let chosen = ask(call, options).await?;
|
||||
let chosen: serde_json::Map<String, Value> = serde_json::from_str(&chosen).ok()?;
|
||||
let answers = questions
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter_map(|entry| {
|
||||
let question = entry.get("question")?.as_str()?;
|
||||
let items: Vec<&str> = chosen.get(question)?.as_array()?.iter().filter_map(Value::as_str).collect();
|
||||
let multi = entry.get("multiSelect").and_then(Value::as_bool) == Some(true);
|
||||
let answer = if multi { join_answers(&items) } else { items.first()?.to_string() };
|
||||
Some((question.to_owned(), json!(answer)))
|
||||
})
|
||||
.collect();
|
||||
Some(Value::Object(answers))
|
||||
}
|
||||
|
||||
/// A multi-select answer as Claude Code's own question UI writes it: comma-joined, with an
|
||||
/// item that holds the separator or a quote JSON-quoted so it reads back as one item.
|
||||
fn join_answers(items: &[&str]) -> String {
|
||||
items
|
||||
.iter()
|
||||
.map(
|
||||
|item| if item.contains(", ") || item.contains('"') { json!(item).to_string() } else { (*item).to_owned() },
|
||||
)
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
/// Whether `result` ends `turn`: it answers the turn's last message, or (stopped) any of
|
||||
/// its messages, or names none (the CLI's own error before the turn began).
|
||||
fn belongs(turn: &Turn, result: &Value) -> bool {
|
||||
|
||||
@@ -976,6 +976,19 @@ fn api_retries_are_announced() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_tasks_are_announced_wholesale() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), true);
|
||||
let tasks = json!([{"task_id": "bsh1", "task_type": "local_bash", "description": "sleep 900"}]);
|
||||
let out = t.on_message(&json!({"type": "system", "subtype": "background_tasks_changed", "tasks": tasks}));
|
||||
assert_eq!(out.len(), 1);
|
||||
assert_eq!(out[0].session, "s");
|
||||
assert_eq!(out[0].update, json!({"sessionUpdate": crate::BACKGROUND_TASKS_UPDATE, "tasks": tasks}));
|
||||
// The list is replaced with every report: an empty one says every task is done.
|
||||
let out = t.on_message(&json!({"type": "system", "subtype": "background_tasks_changed", "tasks": []}));
|
||||
assert_eq!(out[0].update, json!({"sessionUpdate": crate::BACKGROUND_TASKS_UPDATE, "tasks": []}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_text_is_not_sent_twice() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), true);
|
||||
@@ -1093,3 +1106,67 @@ fn tool_calls_plans_and_subagents() {
|
||||
assert_eq!(finished[1].update["content"][0]["text"], "It is x");
|
||||
assert_eq!(finished[1].update["senderSessionId"], "ag");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn questions_go_out_as_one_request() {
|
||||
let questions = json!([
|
||||
{"header": "Files", "question": "Where should they live?", "multiSelect": false,
|
||||
"options": [{"label": "Local", "description": "Kept out of git"}, {"label": "Committed", "description": "In the repo"}]},
|
||||
{"header": "Checks", "question": "Which checks?", "multiSelect": true,
|
||||
"options": [{"label": "Lint", "description": ""}, {"label": "Tests", "description": ""}]},
|
||||
]);
|
||||
let input = json!({ "questions": questions });
|
||||
let asked = std::sync::Mutex::new(Vec::new());
|
||||
let reply = json!({"Where should they live?": ["Local"], "Which checks?": ["Lint", "Tests"]}).to_string();
|
||||
let answers = json!({"Where should they live?": "Local", "Which checks?": "Lint, Tests"});
|
||||
let result = ask_questions(&input, &json!({"toolCallId": "t"}), |call, options| {
|
||||
asked.lock().unwrap().push((call, options));
|
||||
let reply = reply.clone();
|
||||
async move { Some(reply) }
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result, Some(answers));
|
||||
let asked = asked.into_inner().unwrap();
|
||||
assert_eq!(asked.len(), 1);
|
||||
let (call, options) = &asked[0];
|
||||
assert_eq!(call["title"], "Where should they live?");
|
||||
assert_eq!(call["_meta"]["questions"], questions);
|
||||
assert_eq!(options[0]["optionId"], "reject");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn answers_keep_claude_codes_format_with_other_text() {
|
||||
let input = json!({"questions": [
|
||||
{"question": "Which cache?", "multiSelect": false, "options": [{"label": "Redis"}, {"label": "None"}]},
|
||||
{"question": "Which checks?", "multiSelect": true, "options": [{"label": "Lint"}, {"label": "Tests"}]},
|
||||
{"question": "Which stores?", "multiSelect": true, "options": [{"label": "Disk"}, {"label": "S3"}]},
|
||||
]});
|
||||
let reply = json!({
|
||||
"Which cache?": ["Memcached, for now"],
|
||||
"Which checks?": ["Lint", "Tests"],
|
||||
"Which stores?": ["Disk", "Redis, not Memcached", "a \"cold\" tier"],
|
||||
})
|
||||
.to_string();
|
||||
let result = ask_questions(&input, &json!({}), |_, _| {
|
||||
let reply = reply.clone();
|
||||
async move { Some(reply) }
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
result,
|
||||
Some(json!({
|
||||
"Which cache?": "Memcached, for now",
|
||||
"Which checks?": "Lint, Tests",
|
||||
"Which stores?": "Disk, \"Redis, not Memcached\", \"a \\\"cold\\\" tier\"",
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn skipped_questions_have_no_answers() {
|
||||
let input = json!({"questions": [{"question": "Which?", "options": [{"label": "A"}]}]});
|
||||
let skipped = ask_questions(&input, &json!({}), |_, _| async { Some("reject".to_owned()) }).await;
|
||||
assert_eq!(skipped, None);
|
||||
let cancelled = ask_questions(&input, &json!({}), |_, _| async { None }).await;
|
||||
assert_eq!(cancelled, None);
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
//! Agent tool use that launched them: their messages carry it as `parent_tool_use_id`.
|
||||
|
||||
use super::tools;
|
||||
use crate::{LIMITS_UPDATE, RETRY_UPDATE};
|
||||
use crate::{BACKGROUND_TASKS_UPDATE, LIMITS_UPDATE, RETRY_UPDATE};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::path::PathBuf;
|
||||
@@ -458,6 +458,15 @@ impl Translator {
|
||||
let last = self.children.get(&tool_use).map(|c| c.last_text.clone()).filter(|t| !t.is_empty());
|
||||
self.finish_child(&tool_use, stop, last.or(summary))
|
||||
}
|
||||
// A turn's background tasks (`run_in_background`) outlive it: the task keeps
|
||||
// the list and stays up while it isn't empty (see `Task::release_when_idle`).
|
||||
Some("background_tasks_changed") => {
|
||||
let Some(tasks) = msg.get("tasks").and_then(Value::as_array).cloned() else { return Vec::new() };
|
||||
vec![Update {
|
||||
session: self.root.clone(),
|
||||
update: json!({ "sessionUpdate": BACKGROUND_TASKS_UPDATE, "tasks": tasks }),
|
||||
}]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,6 +81,64 @@ fn builtins() -> Vec<ProviderSpec> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl ProviderSpec {
|
||||
pub(crate) fn login_hint(&self, program: &Path) -> String {
|
||||
if !program.is_absolute() {
|
||||
return self.login_hint.clone();
|
||||
}
|
||||
let search = ide_core::process::host_var_os("PATH").unwrap_or_default();
|
||||
let builtin = builtin_spec(&self.id);
|
||||
let on_path = builtin.as_ref().and_then(|b| ide_core::process::find_executable(&b.command, &search));
|
||||
render_login_hint(self, program, on_path.as_deref(), cfg!(windows))
|
||||
}
|
||||
|
||||
pub(crate) fn sign_in_message(&self) -> String {
|
||||
let name = &self.name;
|
||||
let hint = self.login_hint(Path::new(&self.command));
|
||||
format!("{name} needs you to sign in. {hint}")
|
||||
}
|
||||
|
||||
/// Resolve once before connecting, so authentication guidance names that same install.
|
||||
pub(crate) fn resolve_for_launch(mut self, cwd: &Path) -> Self {
|
||||
if self.driver != Driver::Acp {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
|
||||
self.command =
|
||||
if program.components().count() > 1 && !program.is_absolute() { cwd.join(program) } else { program }
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>, windows: bool) -> String {
|
||||
let Some(builtin) = builtin_spec(&spec.id) else { return spec.login_hint.clone() };
|
||||
let prefix = format!("Run `{}", builtin.command);
|
||||
let Some(rest) = spec.login_hint.strip_prefix(&prefix).filter(|rest| rest.starts_with([' ', '`'])) else {
|
||||
return spec.login_hint.clone();
|
||||
};
|
||||
let same_path = |a: &Path, b: &Path| {
|
||||
a == b || dunce::canonicalize(a).ok().zip(dunce::canonicalize(b).ok()).is_some_and(|(a, b)| a == b)
|
||||
};
|
||||
if on_path.is_some_and(|path| same_path(path, program)) {
|
||||
return spec.login_hint.clone();
|
||||
}
|
||||
let path = program.to_string_lossy();
|
||||
let quoted = if windows {
|
||||
format!("& '{}'", path.replace('\'', "''"))
|
||||
} else {
|
||||
format!("'{}'", path.replace('\'', "'\\''"))
|
||||
};
|
||||
let (args, suffix) = rest.split_once('`').expect("built-in login hints delimit their command");
|
||||
let command = format!("{quoted}{args}");
|
||||
match suffix {
|
||||
" in a terminal." => format!("Run `{command}` in a terminal."),
|
||||
" in a terminal and sign in." => format!("Run `{command}` in a terminal and sign in."),
|
||||
_ => spec.login_hint.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `id` names a built-in agent that needs no registry install (native drivers
|
||||
/// and `npx -y` adapters). CLI built-ins (`copilot`, `gemini`, …) can be installed and
|
||||
/// updated from the ACP Registry into `<config>/agents/<id>.toml`.
|
||||
@@ -119,13 +177,14 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
args: spec.args.clone(),
|
||||
default_program: builtin.as_ref().map(|b| b.command.clone()),
|
||||
default_args: builtin.as_ref().map(|b| b.args.clone()).unwrap_or_default(),
|
||||
login_hint: Some(spec.login_hint.clone()),
|
||||
login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env))),
|
||||
command_overridden: builtin.as_ref().is_some_and(|b| b.command != spec.command),
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed(&spec.command),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
thought_levels: BTreeMap::new(),
|
||||
commands: vec![],
|
||||
source: spec.source.clone(),
|
||||
}
|
||||
@@ -312,6 +371,81 @@ fn is_executable(p: &Path) -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn login_hints_cover_all_builtin_commands_and_preserve_separate_login_tools() {
|
||||
for spec in builtins() {
|
||||
let separate = matches!(spec.id.as_str(), "claude-acp" | "codex-acp" | "vibe");
|
||||
for windows in [false, true] {
|
||||
let program =
|
||||
if windows { Path::new(r"C:\Agent Tools\renamed.cmd") } else { Path::new("/agent tools/renamed") };
|
||||
let hint = render_login_hint(&spec, program, None, windows);
|
||||
if separate {
|
||||
assert_eq!(hint, spec.login_hint, "{}", spec.id);
|
||||
} else {
|
||||
let prefix =
|
||||
if windows { "Run `& 'C:\\Agent Tools\\renamed.cmd'" } else { "Run `'/agent tools/renamed'" };
|
||||
assert!(hint.starts_with(prefix), "{}: {hint}", spec.id);
|
||||
assert_eq!(
|
||||
render_login_hint(&spec, program, Some(program), windows),
|
||||
spec.login_hint,
|
||||
"a PATH-resolved command stays bare: {}",
|
||||
spec.id
|
||||
);
|
||||
assert_eq!(render_login_hint(&spec, program, Some(Path::new("/other/install")), windows), hint);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_commands_quote_shell_metacharacters_and_keep_arguments() {
|
||||
let cursor = builtin_spec("cursor").unwrap();
|
||||
assert_eq!(
|
||||
render_login_hint(&cursor, Path::new("/agent's tools/$cli"), None, false),
|
||||
"Run `'/agent'\\''s tools/$cli' login` in a terminal."
|
||||
);
|
||||
assert_eq!(
|
||||
render_login_hint(&cursor, Path::new(r"C:\agent's tools\$cli.cmd"), None, true),
|
||||
r"Run `& 'C:\agent''s tools\$cli.cmd' login` in a terminal."
|
||||
);
|
||||
let opencode = builtin_spec("opencode").unwrap();
|
||||
assert_eq!(
|
||||
render_login_hint(&opencode, Path::new("/registry/opencode"), None, false),
|
||||
"Run `'/registry/opencode' auth login` in a terminal."
|
||||
);
|
||||
let mut custom = cursor;
|
||||
custom.id = "custom".into();
|
||||
custom.login_hint = "Sign in with the agent's own command line first.".into();
|
||||
assert_eq!(render_login_hint(&custom, Path::new("/custom"), None, false), custom.login_hint);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_resolution_uses_the_child_path_and_absolutizes_relative_overrides() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut cursor = builtin_spec("cursor").unwrap();
|
||||
let command = if cfg!(windows) { "cursor-agent.cmd" } else { "cursor-agent" };
|
||||
let program = dir.path().join(command);
|
||||
std::fs::write(&program, "").unwrap();
|
||||
cursor.env.push(("PATH".into(), dir.path().to_string_lossy().into_owned()));
|
||||
let resolved = cursor.clone().resolve_for_launch(dir.path());
|
||||
assert_eq!(Path::new(&resolved.command), program);
|
||||
assert!(resolved.sign_in_message().contains(&*program.to_string_lossy()));
|
||||
cursor.command = format!("tools/{command}");
|
||||
let resolved = cursor.resolve_for_launch(dir.path());
|
||||
assert_eq!(Path::new(&resolved.command), dir.path().join("tools").join(command));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn registry_login_hint_names_the_installed_executable() {
|
||||
let mut spec = builtin_spec("cursor").unwrap();
|
||||
spec.command = "/registry path/dist-package/cursor-agent".into();
|
||||
assert_eq!(
|
||||
describe(&spec).login_hint.as_deref(),
|
||||
Some("Run `'/registry path/dist-package/cursor-agent' login` in a terminal.")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_metadata_distinguishes_defaults_overrides_and_read_only_agents() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -9,11 +9,27 @@ struct FakeAgent {
|
||||
/// Every connection's agent side, kept open.
|
||||
servers: Mutex<Vec<Peer>>,
|
||||
calls: Mutex<Vec<String>>,
|
||||
permission_replies: Mutex<Vec<Value>>,
|
||||
/// Without `loadSession` (a session lives only as long as its process).
|
||||
no_load: bool,
|
||||
auth_on_new: bool,
|
||||
empty_config: AtomicBool,
|
||||
/// Config options `session/new` reports after the model one (per-model efforts, say).
|
||||
extra_options: Mutex<Vec<Value>>,
|
||||
model_options: Mutex<HashMap<String, Vec<Value>>>,
|
||||
}
|
||||
|
||||
impl FakeAgent {
|
||||
fn options_for(&self, model: &str) -> Vec<Value> {
|
||||
let mut options = vec![json!({"id": "model", "category": "model", "type": "select",
|
||||
"currentValue": model,
|
||||
"options": [{"value": "big", "name": "Big"}, {"value": "small", "name": "Small"},
|
||||
{"value": "plain", "name": "Plain"}, {"value": "unknown", "name": "Unknown"}]})];
|
||||
options
|
||||
.extend(self.model_options.lock().get(model).cloned().unwrap_or_else(|| self.extra_options.lock().clone()));
|
||||
options
|
||||
}
|
||||
|
||||
/// The connection opened last: the agent restarted, or a fork's.
|
||||
fn latest(&self) -> Peer {
|
||||
self.servers.lock().last().cloned().expect("a connection")
|
||||
@@ -85,6 +101,11 @@ impl Handler for FakeAgent {
|
||||
|
||||
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
|
||||
self.calls.lock().push(method.to_owned());
|
||||
if (method == "session/new" && self.auth_on_new)
|
||||
|| (method == "session/prompt" && params.pointer("/prompt/0/text") == Some(&json!("auth")))
|
||||
{
|
||||
return Err((codes::INTERNAL_ERROR, "Authentication required".into()));
|
||||
}
|
||||
let session = params.get("sessionId").and_then(Value::as_str).unwrap_or("s1").to_owned();
|
||||
match method {
|
||||
"initialize" => {
|
||||
@@ -92,13 +113,22 @@ impl Handler for FakeAgent {
|
||||
self.calls.lock().push("subagents".into());
|
||||
}
|
||||
Ok(json!({"protocolVersion": 1, "agentCapabilities": {"loadSession": !self.no_load,
|
||||
"sessionCapabilities": {"fork": {}}, "_meta": {"openidea": {"rollback": true, "steer": true}}}}))
|
||||
"sessionCapabilities": {"fork": {}}, "_meta": {"openidea": {"rollback": true, "steer": true, "backgroundTasks": true}}}}))
|
||||
}
|
||||
"session/new" => Ok(json!({"sessionId": "s1",
|
||||
"session/new" => {
|
||||
if self.empty_config.load(Ordering::Acquire) {
|
||||
return Ok(json!({"sessionId": "s1"}));
|
||||
}
|
||||
let options = self.options_for("big");
|
||||
Ok(json!({"sessionId": "s1",
|
||||
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]},
|
||||
"configOptions": [{"id": "model", "category": "model", "type": "select", "currentValue": "big",
|
||||
"options": [{"value": "big", "name": "Big"}, {"value": "small", "name": "Small"}]}]})),
|
||||
"configOptions": options}))
|
||||
}
|
||||
"session/fork" => Ok(json!({"sessionId": "s2"})),
|
||||
"_openidea/stop_task" => {
|
||||
self.calls.lock().push(format!("{method} {}", params["taskId"]));
|
||||
Ok(json!({}))
|
||||
}
|
||||
"_openidea/rollback" | "_openidea/steer" => {
|
||||
let detail = params.get("turns").cloned().unwrap_or_else(|| params["prompt"][0]["text"].clone());
|
||||
self.calls.lock().push(format!("{method} {detail}"));
|
||||
@@ -110,6 +140,9 @@ impl Handler for FakeAgent {
|
||||
}
|
||||
"session/set_config_option" | "session/set_mode" => {
|
||||
self.calls.lock().push(format!("{method} {}", params.get("value").or(params.get("modeId")).unwrap()));
|
||||
if params["configId"] == "model" && !self.model_options.lock().is_empty() {
|
||||
return Ok(json!({"configOptions": self.options_for(params["value"].as_str().unwrap())}));
|
||||
}
|
||||
Ok(json!({}))
|
||||
}
|
||||
"session/prompt" => {
|
||||
@@ -118,6 +151,16 @@ impl Handler for FakeAgent {
|
||||
self.say(&session, "second turn");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "background" {
|
||||
// A command that outlives the turn, as the agent reports it.
|
||||
self.update(
|
||||
&session,
|
||||
json!({"sessionUpdate": BACKGROUND_TASKS_UPDATE,
|
||||
"tasks": [{"task_id": "bsh1", "task_type": "local_bash", "description": "sleep 900"}]}),
|
||||
);
|
||||
self.say(&session, "running it in the background");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "delegate" {
|
||||
self.delegate(&session);
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
@@ -135,6 +178,52 @@ impl Handler for FakeAgent {
|
||||
self.say(&session, "ok");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "ask" {
|
||||
let peer = self.latest();
|
||||
let answer: Value = tokio::runtime::Handle::current()
|
||||
.block_on(peer.request(
|
||||
"session/request_permission",
|
||||
json!({"sessionId": session,
|
||||
"toolCall": {"toolCallId": "q1", "title": "AskUserQuestion", "_meta": {"questions": [
|
||||
{"question": "Which layout?", "options": [{"label": "List"}, {"label": "Grid"}]},
|
||||
{"question": "Which checks?", "multiSelect": true,
|
||||
"options": [{"label": "Disk"}, {"label": "GPU temps"}]}]}},
|
||||
"options": [{"optionId": "yes", "name": "Allow", "kind": "allow_once"}]}),
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
self.permission_replies.lock().push(answer.clone());
|
||||
let chosen = answer.pointer("/outcome/optionId").and_then(Value::as_str).unwrap_or("none");
|
||||
self.say(&session, &format!("answered {chosen}"));
|
||||
return Ok(json!({ "stopReason": "end_turn" }));
|
||||
}
|
||||
if text == "qwen ask" {
|
||||
// Qwen Code's ACP dialect: the questions as `qwenQuestions`, Submit and
|
||||
// Cancel as the options, the answers keyed by question index.
|
||||
let peer = self.latest();
|
||||
let answer: Value = tokio::runtime::Handle::current()
|
||||
.block_on(peer.request(
|
||||
"session/request_permission",
|
||||
json!({"sessionId": session,
|
||||
"toolCall": {"toolCallId": "q2", "title": "Ask user 2 questions", "kind": "think",
|
||||
"_meta": {"toolName": "ask_user_question", "qwenInteractionKind": "user_question",
|
||||
"qwenQuestions": [
|
||||
{"question": "Which database?", "header": "Database", "options": [
|
||||
{"label": "Postgres", "description": "Relational"},
|
||||
{"label": "Redis", "description": "Key-value"}]},
|
||||
{"question": "Which caches?", "header": "Caches", "multiSelect": true,
|
||||
"options": [{"label": "Disk"}, {"label": "Memory"}]}]}},
|
||||
"options": [{"optionId": "proceed_once", "name": "Submit", "kind": "allow_once"},
|
||||
{"optionId": "cancel", "name": "Cancel", "kind": "reject_once"}]}),
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
let outcome = answer.pointer("/outcome/outcome").and_then(Value::as_str).unwrap_or("none");
|
||||
let option = answer.pointer("/outcome/optionId").and_then(Value::as_str).unwrap_or("none");
|
||||
let answers = answer.get("answers").cloned().unwrap_or(Value::Null);
|
||||
self.say(&session, &format!("answered {outcome} {option} {answers}"));
|
||||
return Ok(json!({ "stopReason": "end_turn" }));
|
||||
}
|
||||
if text == "wait" {
|
||||
// Works until cancelled.
|
||||
while !self.calls.lock().iter().any(|c| c == "session/cancel") {
|
||||
@@ -211,6 +300,49 @@ fn manager_at(dir: &Path, models_file: &Path, agent: Arc<FakeAgent>) -> AgentMan
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn authentication_failures_name_the_session_executable_at_start_and_during_prompts() {
|
||||
for auth_on_new in [true, false] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent { auth_on_new, ..Default::default() });
|
||||
let mgr = manager(tmp.path(), agent);
|
||||
let program = tmp.path().join("Agent Tools").join("renamed-cursor.cmd");
|
||||
mgr.shared.providers.write().iter_mut().find(|s| s.id == "cursor").unwrap().command =
|
||||
program.to_string_lossy().into_owned();
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "cursor".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
if !auth_on_new {
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
// A settings change must not redirect guidance for the already running process.
|
||||
mgr.shared.providers.write().iter_mut().find(|s| s.id == "cursor").unwrap().command =
|
||||
"different-cursor".into();
|
||||
mgr.prompt(&task.id, text("auth"), false).await.unwrap();
|
||||
}
|
||||
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
let error = entries
|
||||
.iter()
|
||||
.find_map(|e| match e {
|
||||
AgentEntry::Error { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.expect("authentication error");
|
||||
assert!(error.starts_with("Cursor needs you to sign in. Run `"), "{error}");
|
||||
assert!(error.contains(&*program.to_string_lossy()), "{error}");
|
||||
assert!(error.ends_with(" login` in a terminal."), "{error}");
|
||||
mgr.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -588,6 +720,161 @@ fn prompts_become_acp_content_blocks() {
|
||||
assert!(clean(text(" ")).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn claude_questions_keep_the_answer_object_as_the_option_id() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("ask"),
|
||||
provider: "codex".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let question = mgr
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|e| match e {
|
||||
AgentEntry::Permission { id, title, questions, .. } => {
|
||||
assert_eq!(title, "AskUserQuestion");
|
||||
assert_eq!(questions.len(), 2);
|
||||
assert_eq!(questions[0].question, "Which layout?");
|
||||
assert!(!questions[0].multi_select);
|
||||
assert_eq!(questions[1].question, "Which checks?");
|
||||
assert!(questions[1].multi_select);
|
||||
Some(*id)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let reply = json!({"Which layout?": ["List"], "Which checks?": ["Disk", "GPU temps"]}).to_string();
|
||||
mgr.respond(&task.id, question, Some(reply.clone())).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(*agent.permission_replies.lock(), [json!({"outcome": {"outcome": "selected", "optionId": reply}})]);
|
||||
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert!(
|
||||
entries
|
||||
.iter()
|
||||
.any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c == "List; Disk, GPU temps")),
|
||||
"{entries:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Qwen Code asks its questions as `_meta.qwenQuestions` with Submit/Cancel options; the
|
||||
/// card answers with `answers` keyed by question index beside the Submit option's id.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn qwen_questions_answer_by_index_beside_the_submit_option() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("qwen ask"),
|
||||
provider: "codex".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let (id, title, questions) = mgr
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|e| match e {
|
||||
AgentEntry::Permission { id, title, questions, .. } => Some((*id, title.clone(), questions.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(title, "Which database?", "the first question, not the request's own title");
|
||||
assert_eq!(
|
||||
questions,
|
||||
vec![
|
||||
AgentQuestion {
|
||||
header: "Database".into(),
|
||||
question: "Which database?".into(),
|
||||
multi_select: false,
|
||||
options: vec![
|
||||
AgentQuestionOption { label: "Postgres".into(), description: "Relational".into(), preview: None },
|
||||
AgentQuestionOption { label: "Redis".into(), description: "Key-value".into(), preview: None },
|
||||
],
|
||||
},
|
||||
AgentQuestion {
|
||||
header: "Caches".into(),
|
||||
question: "Which caches?".into(),
|
||||
multi_select: true,
|
||||
options: vec![
|
||||
AgentQuestionOption { label: "Disk".into(), description: String::new(), preview: None },
|
||||
AgentQuestionOption { label: "Memory".into(), description: String::new(), preview: None },
|
||||
],
|
||||
},
|
||||
]
|
||||
);
|
||||
let reply = json!({"Which database?": ["Postgres"], "Which caches?": ["Disk", "Memory"]}).to_string();
|
||||
mgr.respond(&task.id, id, Some(reply)).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
let expected = format!("answered selected proceed_once {}", json!({"0": "Postgres", "1": "Disk, Memory"}));
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == &expected)), "{entries:?}");
|
||||
assert!(
|
||||
entries
|
||||
.iter()
|
||||
.any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c == "Postgres; Disk, Memory")),
|
||||
"{entries:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A skipped Qwen question cancels the request: qwen-code reads the answers it expects
|
||||
/// only beside a chosen option, and `reject` is none of the options it offered.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn skipped_qwen_questions_cancel_the_request() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("qwen ask"),
|
||||
provider: "codex".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let id = mgr
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|e| match e {
|
||||
AgentEntry::Permission { id, questions, .. } if !questions.is_empty() => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
mgr.respond(&task.id, id, Some("reject".into())).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert!(
|
||||
entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "answered cancelled none null")),
|
||||
"{entries:?}"
|
||||
);
|
||||
assert!(
|
||||
entries.iter().any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c == "Cancelled")),
|
||||
"{entries:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cancelling_resolves_the_open_permission_and_delete_forgets_the_task() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -786,6 +1073,230 @@ async fn usage_limits_and_late_settings() {
|
||||
assert!(agent.calls.lock().iter().any(|c| c == "session/set_config_option \"high\""));
|
||||
let config = mgr.task(&task.id).unwrap().state.lock().task.config.clone();
|
||||
assert_eq!(config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("high"));
|
||||
for _ in 0..100 {
|
||||
if mgr
|
||||
.shared
|
||||
.known
|
||||
.lock()
|
||||
.get("claude")
|
||||
.and_then(|k| k.thought_levels.get("big"))
|
||||
.and_then(|levels| levels.first())
|
||||
.and_then(|o| o.current.as_deref())
|
||||
== Some("high")
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(mgr.shared.known.lock()["claude"].thought_levels["big"][0].current.as_deref(), Some("high"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn remembered_settings_drop_per_model_choices_for_the_next_task() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
// The effort list depends on the model: what the last session ran means nothing once
|
||||
// the user picks another model, so provider-wide defaults never include it.
|
||||
*agent.extra_options.lock() = vec![json!({"id": "effort", "category": "thought_level",
|
||||
"type": "select", "currentValue": "high",
|
||||
"options": [{"value": "low", "name": "Low"}, {"value": "high", "name": "High"}]})];
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let provider = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
assert!(provider.config.iter().all(|o| o.id != "effort"), "a per-model option isn't offered stale");
|
||||
let model = provider.config.iter().find(|o| o.id == "model").unwrap();
|
||||
assert_eq!(model.current.as_deref(), Some("big"), "the model choice survives");
|
||||
}
|
||||
|
||||
fn effort_options(levels: &[&str], current: &str) -> Vec<Value> {
|
||||
vec![json!({"id": "effort", "category": "thought_level", "type": "select", "currentValue": current,
|
||||
"options": levels.iter().map(|v| json!({"value": v, "name": v})).collect::<Vec<_>>()})]
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn thinking_levels_are_remembered_per_provider_and_model() {
|
||||
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 {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.set_config(&task.id, "model", "small".into()).await.unwrap();
|
||||
mgr.set_config(&task.id, "effort", "medium".into()).await.unwrap();
|
||||
mgr.set_config(&task.id, "model", "plain".into()).await.unwrap();
|
||||
let p = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
let big = &p.thought_levels["big"][0];
|
||||
assert_eq!(big.current.as_deref(), Some("high"));
|
||||
assert_eq!(big.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["low", "high"]);
|
||||
let small = &p.thought_levels["small"][0];
|
||||
assert_eq!(small.current.as_deref(), Some("medium"));
|
||||
assert_eq!(small.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["minimal", "medium"]);
|
||||
assert!(p.thought_levels["plain"].is_empty());
|
||||
assert!(!p.thought_levels.contains_key("unknown"));
|
||||
assert!(mgr.providers().iter().find(|p| p.id == "codex").unwrap().thought_levels.is_empty());
|
||||
let saved: HashMap<String, Known> =
|
||||
serde_json::from_slice(&std::fs::read(&mgr.shared.paths.models_file).unwrap()).unwrap();
|
||||
assert_eq!(saved["claude"].thought_levels, p.thought_levels);
|
||||
mgr.shutdown();
|
||||
let restored = manager(tmp.path(), agent);
|
||||
assert_eq!(restored.providers().into_iter().find(|p| p.id == "claude").unwrap().thought_levels, p.thought_levels);
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn upfront_effort_is_validated_after_changing_model_before_the_prompt() {
|
||||
for (effort, applied) in [("medium", true), ("high", false)] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.model_options.lock() = HashMap::from([
|
||||
("big".into(), effort_options(&["low", "high"], "low")),
|
||||
("small".into(), effort_options(&["minimal", "medium"], "minimal")),
|
||||
]);
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
// Reversed on purpose: model must be set before validating effort.
|
||||
config: vec![
|
||||
AgentConfigChoice { id: "effort".into(), value: effort.into() },
|
||||
AgentConfigChoice { id: "model".into(), value: "small".into() },
|
||||
],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let calls = agent.calls.lock();
|
||||
let model = calls.iter().position(|c| c == "session/set_config_option \"small\"").unwrap();
|
||||
let effort_call = calls.iter().position(|c| c == &format!("session/set_config_option \"{effort}\""));
|
||||
assert_eq!(effort_call.is_some(), applied);
|
||||
if let Some(effort_call) = effort_call {
|
||||
let prompt = calls.iter().position(|c| c == "session/prompt").unwrap();
|
||||
assert!(model < effort_call && effort_call < prompt);
|
||||
}
|
||||
drop(calls);
|
||||
mgr.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn unreported_model_switch_does_not_cache_the_previous_models_levels() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.extra_options.lock() = effort_options(&["low", "high"], "high");
|
||||
let mgr = manager(tmp.path(), agent);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.set_config(&task.id, "model", "small".into()).await.unwrap();
|
||||
let p = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
assert!(!p.thought_levels.contains_key("small"));
|
||||
assert_eq!(p.thought_levels["big"][0].current.as_deref(), Some("high"));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cached_effort_is_not_sent_without_real_session_options() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.extra_options.lock() = effort_options(&["low", "high"], "low");
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let new = |config| NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config,
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
};
|
||||
let warm = mgr.create(new(vec![])).await.unwrap();
|
||||
wait_for(&mgr, &warm.id, AgentStatus::Ready).await;
|
||||
agent.calls.lock().clear();
|
||||
agent.empty_config.store(true, Ordering::Release);
|
||||
let task = mgr
|
||||
.create(new(vec![
|
||||
AgentConfigChoice { id: "model".into(), value: "big".into() },
|
||||
AgentConfigChoice { id: "effort".into(), value: "high".into() },
|
||||
]))
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert!(!agent.calls.lock().iter().any(|c| c == "session/set_config_option \"high\""));
|
||||
assert!(
|
||||
mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "effort"),
|
||||
"remembered session settings remain visible until the agent refreshes them"
|
||||
);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn reported_levels_refresh_even_without_a_model_option() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.extra_options.lock() = effort_options(&["low", "high"], "high");
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
for levels in [effort_options(&["minimal", "medium"], "medium"), vec![]] {
|
||||
agent.update("s1", json!({"sessionUpdate": "config_option_update", "configOptions": levels}));
|
||||
let expected = config::parse_options(&json!(levels));
|
||||
for _ in 0..100 {
|
||||
if mgr.shared.known.lock()["claude"].thought_levels["big"] == expected {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(mgr.shared.known.lock()["claude"].thought_levels["big"], expected);
|
||||
}
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -857,6 +1368,64 @@ async fn cursor_approval_switch_resolves_pending_and_survives_restart() {
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn bypass_approvals_keeps_both_question_dialects_pending_but_allows_permissions() {
|
||||
for prompt in ["ask", "qwen ask"] {
|
||||
for bypass_at_start in [false, true] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
// Cursor's client-side approval policy applies independently of the question dialect.
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text(prompt),
|
||||
provider: "cursor".into(),
|
||||
config: if bypass_at_start {
|
||||
vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }]
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let id = mgr
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|entry| match entry {
|
||||
AgentEntry::Permission { id, questions, chosen: None, .. } if questions.len() == 2 => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
mgr.set_config(&task.id, config::CURSOR_APPROVAL, "bypass".into()).await.unwrap();
|
||||
assert!(mgr.task(&task.id).unwrap().permissions.lock().contains_key(&id), "{prompt}, {bypass_at_start}");
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.status, AgentStatus::NeedsInput);
|
||||
let reply = if prompt == "ask" {
|
||||
json!({"Which layout?": ["Grid"], "Which checks?": ["Disk"]})
|
||||
} else {
|
||||
json!({"Which database?": ["Postgres"], "Which caches?": ["Memory"]})
|
||||
};
|
||||
mgr.respond(&task.id, id, Some(reply.to_string())).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
mgr.prompt(&task.id, text("Fix"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert!(
|
||||
entries.iter().any(|entry| matches!(entry,
|
||||
AgentEntry::Permission { questions, chosen: Some(name), .. }
|
||||
if questions.is_empty() && name == "Allow")),
|
||||
"{entries:?}"
|
||||
);
|
||||
assert!(entries.iter().any(|entry| matches!(entry, AgentEntry::Agent { text } if text == "chose yes")));
|
||||
mgr.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cursor_approval_choice_applies_before_first_prompt() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1110,6 +1679,114 @@ async fn idle_agents_stop_and_resume_their_session_on_the_next_message() {
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// A turn's background tasks outlive it: an idle agent stops only once its last one is
|
||||
/// done, and the usual delay runs from that report.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_idle_agent_waits_for_its_background_tasks_before_it_stops() {
|
||||
let live =
|
||||
|mgr: &AgentManager, id: &str| mgr.task(id).unwrap().live.lock().as_ref().is_some_and(|l| !l.peer.is_closed());
|
||||
let new = || NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("background"),
|
||||
provider: "claude".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
};
|
||||
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
mgr.set_idle_release(Duration::from_millis(200));
|
||||
let task = mgr.create(new()).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
// The task runs long past the idle delay: the agent stays up for it.
|
||||
tokio::time::sleep(Duration::from_millis(600)).await;
|
||||
assert!(live(&mgr, &task.id));
|
||||
// It is done: the delay starts over from this report, then the agent stops.
|
||||
agent.update("s1", json!({"sessionUpdate": BACKGROUND_TASKS_UPDATE, "tasks": []}));
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert!(live(&mgr, &task.id), "the delay runs from when the last task is done");
|
||||
tokio::time::sleep(Duration::from_millis(600)).await;
|
||||
assert!(!live(&mgr, &task.id));
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Ready, "not an error");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_task_shows_what_runs_in_the_background() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("background"),
|
||||
provider: "claude".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let shown = || mgr.task(&task.id).unwrap().state.lock().task.background.clone();
|
||||
let first = shown();
|
||||
assert_eq!(first.len(), 1);
|
||||
assert_eq!(
|
||||
(first[0].id.as_str(), first[0].kind.as_str(), first[0].description.as_str()),
|
||||
("bsh1", "local_bash", "sleep 900")
|
||||
);
|
||||
|
||||
agent.update(
|
||||
"s1",
|
||||
json!({"sessionUpdate": BACKGROUND_TASKS_UPDATE, "tasks": [
|
||||
{"task_id": "bsh1", "task_type": "local_bash", "description": "sleep 900"},
|
||||
{"task_id": "mon1", "task_type": "monitor", "description": "Watch the deploy"},
|
||||
]}),
|
||||
);
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while shown().len() < 2 {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(shown()[0].started_ms, first[0].started_ms, "a task keeps when it was first seen");
|
||||
|
||||
agent.update("s1", json!({"sessionUpdate": BACKGROUND_TASKS_UPDATE, "tasks": []}));
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while !shown().is_empty() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_background_task_is_stopped_on_its_own() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.stop_background(&task.id, "b1").await.unwrap();
|
||||
assert!(agent.calls.lock().contains(&"_openidea/stop_task \"b1\"".to_owned()));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// Deleting a task whose agent still runs in the worktree removes both and leaves no
|
||||
/// process behind, whether it is waiting for permission or idle without session/load.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
@@ -434,7 +434,13 @@ 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, title: "Run?".into(), options: vec![], chosen: None });
|
||||
t.push(AgentEntry::Permission {
|
||||
id: 1,
|
||||
title: "Run?".into(),
|
||||
options: vec![],
|
||||
questions: vec![],
|
||||
chosen: None,
|
||||
});
|
||||
assert_eq!(t.end_turn(None), vec![2, 3]);
|
||||
let again = Timeline::from_entries(t.entries.clone());
|
||||
assert_eq!(again.plan, Some(0));
|
||||
|
||||
@@ -153,7 +153,7 @@ fn detect_dir(dir: &Path, model: &BuildModel, root: &Path) -> Option<BuildSystem
|
||||
Some(BuildSystem::Gradle)
|
||||
} else if has(dir, &["Cargo.toml"]) {
|
||||
Some(BuildSystem::Cargo)
|
||||
} else if has(dir, &["go.mod"]) {
|
||||
} else if has(dir, &["go.mod", "go.work"]) {
|
||||
Some(BuildSystem::Go)
|
||||
} else if has(dir, &["tsconfig.json", "package.json"]) {
|
||||
Some(BuildSystem::TypeScript)
|
||||
@@ -227,14 +227,19 @@ pub fn plan(
|
||||
BuildSystem::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?,
|
||||
BuildSystem::Cargo => cargo_steps(&dir, kind),
|
||||
// Go builds the file's package (a module holds many).
|
||||
BuildSystem::Go => go_steps(file.and_then(Path::parent).unwrap_or(&dir), kind),
|
||||
BuildSystem::Go => go_steps(file.and_then(Path::parent).unwrap_or(&dir), kind)?,
|
||||
BuildSystem::TypeScript => ts_steps(&dir, kind),
|
||||
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
|
||||
};
|
||||
Ok(BuildPlan { system, title, steps })
|
||||
}
|
||||
|
||||
fn maven_steps(root: &Path, model: &BuildModel, kind: BuildKind, module: Option<&Path>) -> IdeResult<Vec<BuildStep>> {
|
||||
pub(super) fn maven_steps(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
kind: BuildKind,
|
||||
module: Option<&Path>,
|
||||
) -> IdeResult<Vec<BuildStep>> {
|
||||
let fallback;
|
||||
let m = match &model.maven {
|
||||
Some(m) => m,
|
||||
@@ -369,7 +374,31 @@ fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> V
|
||||
steps
|
||||
}
|
||||
|
||||
fn go_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
fn go_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
|
||||
if dir.join("go.work").is_file() {
|
||||
let work_file = dunce::canonicalize(dir.join("go.work"))?;
|
||||
let modules = ide_core::go::work_modules(&std::fs::read_to_string(dir.join("go.work"))?);
|
||||
if modules.is_empty() {
|
||||
return Err(IdeError::invalid("The Go workspace contains no modules"));
|
||||
}
|
||||
let mut steps = Vec::new();
|
||||
for module in modules {
|
||||
let module = dir.join(module);
|
||||
if !module.join("go.mod").is_file() {
|
||||
return Err(IdeError::not_found(format!("Go workspace module has no go.mod: {}", module.display())));
|
||||
}
|
||||
let mut module_steps = go_module_steps(&module, kind);
|
||||
for step in &mut module_steps {
|
||||
step.env.insert("GOWORK".into(), work_file.to_string_lossy().into_owned());
|
||||
}
|
||||
steps.extend(module_steps);
|
||||
}
|
||||
return Ok(steps);
|
||||
}
|
||||
Ok(go_module_steps(dir, kind))
|
||||
}
|
||||
|
||||
fn go_module_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
let module_root = dir.ancestors().find(|d| d.join("go.mod").is_file()).unwrap_or(dir);
|
||||
let target = if module_root == dir { "./...".to_owned() } else { format!("./{}/...", rel_str(module_root, dir)) };
|
||||
let mut args = vec!["build"];
|
||||
@@ -383,18 +412,7 @@ fn go_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
|
||||
/// `pnpm` / `yarn` / `bun` / `npm`, from the lock file next to `package.json` or above it.
|
||||
fn package_manager(dir: &Path) -> &'static str {
|
||||
for d in dir.ancestors() {
|
||||
if d.join("pnpm-lock.yaml").is_file() {
|
||||
return "pnpm";
|
||||
} else if d.join("yarn.lock").is_file() {
|
||||
return "yarn";
|
||||
} else if d.join("bun.lockb").is_file() || d.join("bun.lock").is_file() {
|
||||
return "bun";
|
||||
} else if d.join("package-lock.json").is_file() {
|
||||
return "npm";
|
||||
}
|
||||
}
|
||||
"npm"
|
||||
ide_core::project_roots::package_manager(dir)
|
||||
}
|
||||
|
||||
fn has_build_script(dir: &Path) -> bool {
|
||||
@@ -819,6 +837,68 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn go_workspace_build_commands_compile_members_with_local_dependencies() {
|
||||
let Some(go) = ide_core::process::find_executable("go", &ide_core::tool_path::search_path()) else {
|
||||
return;
|
||||
};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = &tmp.path().join("workspace");
|
||||
write(root, "go.work", "go 1.22\nuse (\n ./app\n ./lib\n ../external\n)\n");
|
||||
write(root, "lib/go.mod", "module example.com/lib\ngo 1.22\n");
|
||||
write(root, "lib/lib.go", "package lib\nfunc Value() int { return 1 }\n");
|
||||
write(root, "app/go.mod", "module example.com/app\ngo 1.22\nrequire example.com/lib v0.0.0\n");
|
||||
write(root, "app/main.go", "package main\nimport \"example.com/lib\"\nfunc main(){_ = lib.Value()}\n");
|
||||
write(root, "../external/go.mod", "module example.com/external\ngo 1.22\nrequire example.com/lib v0.0.0\n");
|
||||
write(root, "../external/main.go", "package main\nimport \"example.com/lib\"\nfunc main(){_ = lib.Value()}\n");
|
||||
let plan = plan(root, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
|
||||
for step in plan.steps {
|
||||
let result = std::process::Command::new(&go)
|
||||
.args(&step.args)
|
||||
.envs(&step.env)
|
||||
.env("GOPROXY", "off")
|
||||
.current_dir(&step.cwd)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_workspace_builds_every_use_module() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("workspace");
|
||||
write(&root, "go.work", "go 1.22\nuse (\n ./api\n \"./lib with spaces\"\n ../shared\n)\n");
|
||||
for module in ["api", "lib with spaces", "../shared"] {
|
||||
write(&root.join(module), "go.mod", "module example.com/p\ngo 1.22\n");
|
||||
}
|
||||
for kind in [BuildKind::Build, BuildKind::Rebuild, BuildKind::Artifacts] {
|
||||
let p = plan(&root, &BuildModel::default(), kind, None, None).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Go);
|
||||
assert_eq!(p.steps.len(), 3);
|
||||
for (step, module) in p.steps.iter().zip(["api", "lib with spaces", "../shared"]) {
|
||||
assert_eq!(step.cwd, root.join(module));
|
||||
let expected =
|
||||
if kind == BuildKind::Rebuild { vec!["build", "-a", "./..."] } else { vec!["build", "./..."] };
|
||||
assert_eq!(step.args, expected);
|
||||
}
|
||||
}
|
||||
let member =
|
||||
plan(&root, &BuildModel::default(), BuildKind::Build, Some(&root.join("api/pkg/a.go")), None).unwrap();
|
||||
assert_eq!(member.steps.len(), 1);
|
||||
assert_eq!(member.steps[0].cwd, root.join("api"));
|
||||
assert_eq!(member.steps[0].args, ["build", "./pkg/..."]);
|
||||
write(&root, "go.work", "use ./missing\n");
|
||||
assert!(
|
||||
plan(&root, &BuildModel::default(), BuildKind::Build, None, None)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("go.mod")
|
||||
);
|
||||
write(&root, "go.work", "go 1.22\n");
|
||||
assert!(plan(&root, &BuildModel::default(), BuildKind::Build, None, None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn independent_gradle_builds_keep_their_launchers_and_task_paths() {
|
||||
let wrapper = if cfg!(windows) { "gradlew.bat" } else { "gradlew" };
|
||||
|
||||
@@ -218,21 +218,14 @@ fn normalize(p: &Path) -> PathBuf {
|
||||
out
|
||||
}
|
||||
|
||||
/// The directory of the Gradle build under `root`: the root itself, or a direct
|
||||
/// subfolder, holding a settings or build script.
|
||||
/// The first automatically discovered build, for callers operating on one build.
|
||||
pub fn build_dir(root: &Path) -> Option<PathBuf> {
|
||||
let has = |d: &Path| SETTINGS_FILES.iter().chain(BUILD_FILES).any(|f| d.join(f).is_file());
|
||||
if has(root) {
|
||||
return Some(root.to_path_buf());
|
||||
}
|
||||
let mut dirs: Vec<PathBuf> = std::fs::read_dir(root)
|
||||
.ok()?
|
||||
.flatten()
|
||||
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && !e.file_name().to_string_lossy().starts_with('.'))
|
||||
.map(|e| e.path())
|
||||
.collect();
|
||||
dirs.sort();
|
||||
dirs.into_iter().find(|d| SETTINGS_FILES.iter().any(|f| d.join(f).is_file()))
|
||||
build_dirs(root).into_iter().next()
|
||||
}
|
||||
|
||||
fn build_dirs(root: &Path) -> Vec<PathBuf> {
|
||||
let markers: Vec<_> = SETTINGS_FILES.iter().chain(BUILD_FILES).copied().collect();
|
||||
ide_core::project_roots::discover(root, &markers)
|
||||
}
|
||||
|
||||
fn wrapper(dir: &Path) -> String {
|
||||
@@ -495,7 +488,7 @@ pub fn linked_project_key(root: &Path, dir: &str) -> String {
|
||||
/// Linked build identities without reading their scripts (also used by index hot paths).
|
||||
pub(crate) fn linked_dirs(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
|
||||
match &settings.linked_projects {
|
||||
None => build_dir(root).map(|dir| rel(root, &dir)).into_iter().collect(),
|
||||
None => build_dirs(root).iter().map(|dir| rel(root, dir)).collect(),
|
||||
Some(dirs) => {
|
||||
let mut out = Vec::new();
|
||||
for dir in dirs {
|
||||
@@ -686,6 +679,55 @@ pub(crate) fn has_war_plugin(script: &str) -> bool {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn default_linkage_discovers_all_shallow_builds() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
for file in [
|
||||
"Cargo.toml",
|
||||
"package.json",
|
||||
"fixtures/kotlin-gradle/settings.gradle.kts",
|
||||
"fixtures/kotlin-gradle/build.gradle.kts",
|
||||
"fixtures/kotlin-gradle/tools/settings.gradle",
|
||||
"services/backend/api/settings.gradle",
|
||||
"standalone/build.gradle",
|
||||
"ignored/src/settings.gradle",
|
||||
"ignored/out/build.gradle",
|
||||
"node_modules/example/settings.gradle",
|
||||
"target/example/build.gradle",
|
||||
"build/example/settings.gradle",
|
||||
"dist/example/build.gradle",
|
||||
"vendor/example/settings.gradle",
|
||||
".hidden/settings.gradle",
|
||||
"too/deep/to/find/settings.gradle",
|
||||
] {
|
||||
let path = root.join(file);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "").unwrap();
|
||||
}
|
||||
let models = super::load_linked(root, &Default::default());
|
||||
assert_eq!(
|
||||
models.iter().map(|m| m.dir.as_str()).collect::<Vec<_>>(),
|
||||
["fixtures/kotlin-gradle", "ignored/src", "services/backend/api", "standalone"]
|
||||
);
|
||||
std::fs::write(root.join("build.gradle.kts"), "").unwrap();
|
||||
let models = super::load_linked(root, &Default::default());
|
||||
assert_eq!(models.len(), 1);
|
||||
assert!(models[0].dir.is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn default_linkage_does_not_follow_symlinks() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
std::fs::create_dir(root.join("real")).unwrap();
|
||||
std::fs::write(root.join("real/build.gradle"), "").unwrap();
|
||||
std::os::unix::fs::symlink(root.join("real"), root.join("alias")).unwrap();
|
||||
let models = super::load_linked(root, &Default::default());
|
||||
assert_eq!(models.iter().map(|m| m.dir.as_str()).collect::<Vec<_>>(), ["real"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_from_the_ui_finds_the_saved_link() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
@@ -718,7 +760,10 @@ mod tests {
|
||||
std::fs::create_dir(root.join(dir)).unwrap();
|
||||
std::fs::write(root.join(dir).join("settings.gradle"), format!("rootProject.name = '{dir}'")).unwrap();
|
||||
}
|
||||
assert_eq!(super::load_linked(root, &Default::default())[0].dir, "a");
|
||||
assert_eq!(
|
||||
super::load_linked(root, &Default::default()).iter().map(|m| m.dir.as_str()).collect::<Vec<_>>(),
|
||||
["a", "b"]
|
||||
);
|
||||
let mut settings = ide_core::settings::GradleSettings {
|
||||
linked_projects: Some(vec!["b".into(), "./b".into(), "a".into()]),
|
||||
..Default::default()
|
||||
|
||||
@@ -53,8 +53,12 @@ pub struct Outcome {
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
/// Inspect sources, excluding generated/build/VCS trees and never following symlinks.
|
||||
pub fn has_kotlin(root: &Path) -> bool {
|
||||
/// Only linked Maven modules contribute sources to the bridge.
|
||||
pub fn has_kotlin(root: &Path, model: &BuildModel) -> bool {
|
||||
model.maven.iter().flat_map(|m| &m.projects).any(|p| has_kotlin_sources(&root.join(&p.dir)))
|
||||
}
|
||||
|
||||
fn has_kotlin_sources(root: &Path) -> bool {
|
||||
let Ok(entries) = std::fs::read_dir(root) else { return false };
|
||||
entries.flatten().any(|entry| {
|
||||
let Ok(kind) = entry.file_type() else { return false };
|
||||
@@ -66,11 +70,25 @@ pub fn has_kotlin(root: &Path) -> bool {
|
||||
entry.file_name().to_str(),
|
||||
Some("target" | "build" | "out" | "bin" | "node_modules" | ".git" | ".openidea")
|
||||
)
|
||||
&& has_kotlin(&entry.path())
|
||||
&& !["pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts"]
|
||||
.iter()
|
||||
.any(|marker| entry.path().join(marker).is_file())
|
||||
&& has_kotlin_sources(&entry.path())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn plan(root: &Path, model: &BuildModel) -> IdeResult<compile::BuildPlan> {
|
||||
if model.maven.as_ref().is_none_or(|m| m.projects.is_empty()) {
|
||||
return Err(IdeError::invalid("Kotlin bridge requires a Maven build root"));
|
||||
}
|
||||
Ok(compile::BuildPlan {
|
||||
system: compile::BuildSystem::Maven,
|
||||
title: root.file_name().unwrap_or_default().to_string_lossy().into_owned(),
|
||||
steps: compile::maven_steps(root, model, BuildKind::Build, None)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Run the project's configured wrapper/settings/JDK and lifecycle, with an output
|
||||
/// redirector loaded before Maven calculates its lifecycle execution plans.
|
||||
pub fn build(
|
||||
@@ -81,10 +99,7 @@ pub fn build(
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Outcome> {
|
||||
std::fs::create_dir_all(generation)?;
|
||||
let mut plan = compile::plan(root, model, BuildKind::Build, None, None)?;
|
||||
if plan.system != compile::BuildSystem::Maven {
|
||||
return Err(IdeError::invalid("Kotlin bridge requires a Maven build root"));
|
||||
}
|
||||
let mut plan = plan(root, model)?;
|
||||
let mut manifests = Vec::new();
|
||||
for (index, step) in plan.steps.iter_mut().enumerate() {
|
||||
step.args.push("--fail-at-end".into());
|
||||
@@ -447,14 +462,106 @@ mod tests {
|
||||
assert_eq!(error.message, "Kotlin bridge requires a Maven build root");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kotlin_sources_belong_to_linked_maven_modules() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
for file in [
|
||||
"java/pom.xml",
|
||||
"gradle/build.gradle.kts",
|
||||
"gradle/src/main/kotlin/App.kt",
|
||||
"java/unlinked/pom.xml",
|
||||
"java/unlinked/src/main/kotlin/App.kt",
|
||||
"java/gradle/settings.gradle.kts",
|
||||
"java/gradle/src/main/kotlin/App.kt",
|
||||
"java/target/generated/Old.kt",
|
||||
"java/node_modules/dependency/App.kt",
|
||||
"java/linked/pom.xml",
|
||||
"java/linked/src/test/kotlin/Test.kt",
|
||||
] {
|
||||
let path = root.join(file);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "").unwrap();
|
||||
}
|
||||
let mut model = BuildModel {
|
||||
maven: Some(crate::MavenModel {
|
||||
projects: vec![crate::MavenProject { dir: "java".into(), ..Default::default() }],
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!has_kotlin(root, &model));
|
||||
model.maven.as_mut().unwrap().projects.push(crate::MavenProject {
|
||||
dir: "java/linked".into(),
|
||||
aggregated: true,
|
||||
..Default::default()
|
||||
});
|
||||
assert!(has_kotlin(root, &model));
|
||||
model.maven.as_mut().unwrap().projects.clear();
|
||||
assert!(!has_kotlin(root, &model));
|
||||
assert!(!has_kotlin(root, &BuildModel::default()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_bridge_ignores_the_workspace_build_system() {
|
||||
for marker in ["Cargo.toml", "package.json", "build.gradle.kts", "go.mod", "CMakeLists.txt"] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::write(root.join(marker), "").unwrap();
|
||||
let mut model = BuildModel { maven: Some(crate::MavenModel::default()), ..Default::default() };
|
||||
for name in ["java", "kotlin"] {
|
||||
let module = root.join(name);
|
||||
std::fs::create_dir_all(&module).unwrap();
|
||||
model.maven.as_mut().unwrap().projects.push(crate::MavenProject {
|
||||
dir: name.into(),
|
||||
command: format!("{name}-mvnw"),
|
||||
options: vec!["-o".into(), "-Peditor".into()],
|
||||
env: BTreeMap::from([("JAVA_HOME".into(), "/jdk".into())]),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
std::fs::write(root.join("kotlin/App.kt"), "class App").unwrap();
|
||||
assert!(has_kotlin(root, &model), "{marker}");
|
||||
let plan = plan(root, &model).unwrap();
|
||||
assert_eq!(plan.system, compile::BuildSystem::Maven);
|
||||
assert_eq!(plan.steps.len(), 2);
|
||||
for (step, name) in plan.steps.iter().zip(["java", "kotlin"]) {
|
||||
assert_eq!(step.cwd, root.join(name));
|
||||
assert_eq!(step.program, format!("{name}-mvnw"));
|
||||
assert_eq!(step.args, ["-B", "-Dstyle.color=never", "-o", "-Peditor", "test-compile"]);
|
||||
assert_eq!(step.env.get("JAVA_HOME").map(String::as_str), Some("/jdk"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_linked_maven_sources_are_included() {
|
||||
let workspace = tempfile::tempdir().unwrap();
|
||||
let external = tempfile::tempdir().unwrap();
|
||||
std::fs::write(external.path().join("App.kt"), "class App").unwrap();
|
||||
let model = BuildModel {
|
||||
maven: Some(crate::MavenModel {
|
||||
projects: vec![crate::MavenProject {
|
||||
dir: external.path().to_string_lossy().into_owned(),
|
||||
command: "mvn".into(),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(has_kotlin(workspace.path(), &model));
|
||||
assert_eq!(plan(workspace.path(), &model).unwrap().steps[0].cwd, external.path());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_find_deleted_sources_in_build_outputs() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("target/generated")).unwrap();
|
||||
std::fs::write(dir.path().join("target/generated/Old.kt"), "").unwrap();
|
||||
assert!(!has_kotlin(dir.path()));
|
||||
assert!(!has_kotlin_sources(dir.path()));
|
||||
std::fs::write(dir.path().join("New.kt"), "").unwrap();
|
||||
assert!(has_kotlin(dir.path()));
|
||||
assert!(has_kotlin_sources(dir.path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+608
-42
@@ -8,6 +8,7 @@
|
||||
//! later replaces plugins and dependencies with the effective build.
|
||||
|
||||
use crate::xml::{self, Element};
|
||||
use ide_core::{Pos, Range};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
@@ -467,7 +468,7 @@ struct Resolver {
|
||||
}
|
||||
|
||||
/// `~/.m2/repository`, or `<localRepository>` from `~/.m2/settings.xml`.
|
||||
pub(crate) fn default_local_repo() -> Option<PathBuf> {
|
||||
pub fn default_local_repo() -> Option<PathBuf> {
|
||||
let m2 = dirs::home_dir()?.join(".m2");
|
||||
local_repository_of(&m2.join("settings.xml")).or(Some(m2.join("repository")))
|
||||
}
|
||||
@@ -1013,10 +1014,7 @@ pub(crate) fn plugin(
|
||||
|
||||
// ---------------------------------------------------------------- loading
|
||||
|
||||
/// Directories never searched for POMs.
|
||||
const SKIP_DIRS: &[&str] = &["node_modules", "target", "build", "out", "dist", "src", "vendor"];
|
||||
const MAX_PROJECTS: usize = 1000;
|
||||
const POM_SEARCH_DEPTH: usize = 3;
|
||||
|
||||
fn rel_path(root: &Path, p: &Path) -> String {
|
||||
p.strip_prefix(root).unwrap_or(p).to_string_lossy().replace('\\', "/")
|
||||
@@ -1027,44 +1025,7 @@ fn rel_path(root: &Path, p: &Path) -> String {
|
||||
/// aggregate POM directly inside `src/` counts too (issue #1001: `src/pom.xml`
|
||||
/// with its modules beside it, `src/app/pom.xml` and so on).
|
||||
fn top_level_poms(root: &Path) -> Vec<PathBuf> {
|
||||
let top = root.join("pom.xml");
|
||||
if top.is_file() {
|
||||
return vec![top];
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let src_pom = root.join("src").join("pom.xml");
|
||||
if src_pom.is_file() {
|
||||
out.push(src_pom);
|
||||
}
|
||||
let mut queue: Vec<(PathBuf, usize)> = vec![(root.to_path_buf(), 0)];
|
||||
while let Some((dir, depth)) = queue.pop() {
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
let mut dirs: Vec<PathBuf> = Vec::new();
|
||||
for e in entries.flatten() {
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
if e.file_type().is_ok_and(|t| t.is_dir()) && !name.starts_with('.') && !SKIP_DIRS.contains(&name.as_str())
|
||||
{
|
||||
dirs.push(e.path());
|
||||
}
|
||||
}
|
||||
dirs.sort();
|
||||
for d in dirs.into_iter().rev() {
|
||||
let pom = d.join("pom.xml");
|
||||
if pom.is_file() {
|
||||
out.push(pom);
|
||||
continue;
|
||||
}
|
||||
let src_pom = d.join("src").join("pom.xml");
|
||||
if src_pom.is_file() {
|
||||
out.push(src_pom);
|
||||
}
|
||||
if depth + 1 < POM_SEARCH_DEPTH {
|
||||
queue.push((d, depth + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
ide_core::project_roots::discover(root, &["pom.xml"]).into_iter().map(|dir| dir.join("pom.xml")).collect()
|
||||
}
|
||||
|
||||
/// Whether `root` holds a Maven build (cheap: the same search as [`load`] without parsing).
|
||||
@@ -1532,10 +1493,296 @@ pub fn parse_dependency_tree(output: &str) -> Vec<(String, Vec<MavenDependency>)
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- goto declaration
|
||||
|
||||
/// What a go-to-declaration in a POM found, and where.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PomGoto {
|
||||
/// Absolute path of the file with the declaration: the POM itself, or a parent
|
||||
/// POM of the local repository when the definition is inherited from one.
|
||||
pub path: PathBuf,
|
||||
pub range: Range,
|
||||
/// What was found.
|
||||
pub kind: PomGotoKind,
|
||||
/// The declaration as named for the user (`example.version`, `com.example:example-lib`).
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
/// The kind of declaration a POM go-to-declaration found.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PomGotoKind {
|
||||
/// A `<properties>` entry of the POM or one of its parents.
|
||||
Property,
|
||||
/// A `<dependencyManagement>` entry providing the dependency's version.
|
||||
ManagedDependency,
|
||||
/// A `<pluginManagement>` entry providing the plugin's version.
|
||||
ManagedPlugin,
|
||||
}
|
||||
|
||||
/// Byte offset of `pos` (0-based line / UTF-16 column), clamped to `text`.
|
||||
fn offset_at(text: &str, pos: Pos) -> usize {
|
||||
let (mut line_seen, mut at) = (0usize, 0usize);
|
||||
if pos.line > 0 {
|
||||
for (i, b) in text.bytes().enumerate() {
|
||||
if b == b'\n' {
|
||||
line_seen += 1;
|
||||
if line_seen == pos.line as usize {
|
||||
at = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if line_seen < pos.line as usize {
|
||||
return text.len();
|
||||
}
|
||||
}
|
||||
let line_end = text[at..].find('\n').map_or(text.len(), |i| at + i);
|
||||
let (mut col, mut byte) = (0u32, at);
|
||||
for c in text[at..line_end].chars() {
|
||||
let width = c.len_utf16() as u32;
|
||||
if col + width > pos.col {
|
||||
break;
|
||||
}
|
||||
col += width;
|
||||
byte += c.len_utf8();
|
||||
}
|
||||
byte
|
||||
}
|
||||
|
||||
/// 0-based line / UTF-16 column of byte offset `at`.
|
||||
fn pos_at(text: &str, at: usize) -> Pos {
|
||||
let before = &text[..at];
|
||||
let line_start = before.rfind('\n').map_or(0, |i| i + 1);
|
||||
Pos::new(before.matches('\n').count() as u32, before[line_start..].encode_utf16().count() as u32)
|
||||
}
|
||||
|
||||
/// The `${property}` reference covering byte offset `at`: its name and the span of
|
||||
/// the whole reference. `None` when `at` is outside one (a closing `${…}` before it
|
||||
/// ends the search: references do not nest).
|
||||
fn property_ref_at(text: &str, at: usize) -> Option<(&str, usize, usize)> {
|
||||
// `at` may sit on the `$` itself.
|
||||
let open = text[..at].rfind("${").or_else(|| text[at..].starts_with("${").then_some(at))?;
|
||||
let close = open + 2 + text[open + 2..].find('}')?;
|
||||
(close >= at).then(|| (text[open + 2..close].trim(), open, close + 1))
|
||||
}
|
||||
|
||||
/// The elements containing `at`, from the root down to the innermost one.
|
||||
fn element_path(root: &Element, at: usize) -> Vec<&Element> {
|
||||
let mut path = vec![root];
|
||||
loop {
|
||||
let Some(next) = path.last().unwrap().children.iter().find(|c| c.start <= at && at < c.end) else {
|
||||
return path;
|
||||
};
|
||||
path.push(next);
|
||||
}
|
||||
}
|
||||
|
||||
/// The `<groupId>` / `<artifactId>` of a dependency or plugin element, with the
|
||||
/// plugin default (`org.apache.maven.plugins`) applied.
|
||||
fn coordinates(e: &Element, props: &HashMap<String, String>) -> Option<(String, String)> {
|
||||
let group = if e.name == "plugin" && e.text_of("groupId").is_none() {
|
||||
"org.apache.maven.plugins".to_owned()
|
||||
} else {
|
||||
interpolate(&e.text_of("groupId")?, props)
|
||||
};
|
||||
Some((group, interpolate(&e.text_of("artifactId")?, props)))
|
||||
}
|
||||
|
||||
/// The go-to-declaration target at `pos` (0-based line / UTF-16 column) of the POM
|
||||
/// `text` stored at `path` (the current buffer text when the file is open): a
|
||||
/// `${property}` reference to the `<properties>` entry that defines it along the
|
||||
/// parent chain, or a dependency / plugin to the `<dependencyManagement>` /
|
||||
/// `<pluginManagement>` entry that provides its version (a parent POM, followed into
|
||||
/// the local repository when it is not in the project). `None` when there is no
|
||||
/// resolvable declaration here.
|
||||
pub fn goto_declaration(text: &str, path: &Path, pos: Pos, local_repo: Option<PathBuf>) -> Option<PomGoto> {
|
||||
let root = xml::parse(text).filter(|e| e.name == "project")?;
|
||||
let at = offset_at(text, pos);
|
||||
if let Some((name, _, _)) = property_ref_at(text, at)
|
||||
&& !name.is_empty()
|
||||
{
|
||||
return property_target(text, path, name, local_repo);
|
||||
}
|
||||
// A `<dependency>` / `<plugin>` in a declaration position: its version may come
|
||||
// from a management entry of this POM or an ancestor's.
|
||||
let elements = element_path(&root, at);
|
||||
let e = elements.iter().rev().find(|e| e.name == "dependency" || e.name == "plugin")?;
|
||||
if elements.iter().any(|a| a.name == "dependencyManagement" || a.name == "pluginManagement") {
|
||||
return None; // Management entries are declarations; there is nothing to go to.
|
||||
}
|
||||
let kind = match e.name.as_str() {
|
||||
"dependency" => PomGotoKind::ManagedDependency,
|
||||
_ => PomGotoKind::ManagedPlugin,
|
||||
};
|
||||
managed_target(text, path, e, kind, local_repo)
|
||||
}
|
||||
|
||||
/// The parent POMs of the POM in `text` at `path`, child-first (its `<parent>` refs,
|
||||
/// via `relativePath` in the project or the local repository), with their texts.
|
||||
fn parent_chain(path: &Path, text: &str, local_repo: Option<PathBuf>) -> Vec<(PathBuf, String)> {
|
||||
let mut resolver = Resolver::new(local_repo, &[]);
|
||||
let path = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
|
||||
let mut chain = vec![(path.clone(), text.to_owned())];
|
||||
let mut dir = path.parent().unwrap_or(Path::new("")).to_path_buf();
|
||||
let mut pom = parse_pom(text);
|
||||
for _ in 0..MAX_PARENT_DEPTH {
|
||||
let Some(parent) = pom.and_then(|p| p.parent) else { return chain };
|
||||
let Some(pp) = resolver.parent_path(&dir, &parent) else { return chain };
|
||||
let pp = dunce::canonicalize(&pp).unwrap_or(pp);
|
||||
let Ok(next) = std::fs::read_to_string(&pp) else { return chain };
|
||||
pom = resolver.pom(&pp);
|
||||
dir = pp.parent().unwrap_or(Path::new("")).to_path_buf();
|
||||
chain.push((pp, next));
|
||||
}
|
||||
chain
|
||||
}
|
||||
|
||||
/// The properties visible in the POM at `chain[i]`: inherited (its parents' and
|
||||
/// ancestors' own entries) plus its own, and the `project.*` built-ins.
|
||||
fn properties_at(resolver: &mut Resolver, chain: &[(PathBuf, String)], i: usize) -> HashMap<String, String> {
|
||||
let (p, text) = &chain[i];
|
||||
let Some(pom) = parse_pom(text) else { return HashMap::new() };
|
||||
let dir = p.parent().unwrap_or(Path::new("")).to_path_buf();
|
||||
let ctx = resolver.context(p, 0);
|
||||
resolver.properties_for(&pom, &ctx, &dir)
|
||||
}
|
||||
|
||||
/// Where the property `name` is declared: the `project.*` built-ins go to their
|
||||
/// coordinate elements, the rest to the first `<properties>` entry along the parent
|
||||
/// chain declaring it (a child's definition wins over a parent's; an active
|
||||
/// profile's counts as the POM's own). The winner's path, element range and name.
|
||||
fn property_target(text: &str, path: &Path, name: &str, local_repo: Option<PathBuf>) -> Option<PomGoto> {
|
||||
let name = name.strip_prefix("pom.").map(|n| format!("project.{n}")).unwrap_or_else(|| name.to_owned());
|
||||
let resolver = Resolver::new(local_repo.clone(), &[]);
|
||||
let chain = parent_chain(path, text, local_repo);
|
||||
// `project.parent.*` (and the legacy `parent.*` spellings) are declared by the
|
||||
// clicked POM's own `<parent>` section.
|
||||
let parent_key = match name.as_str() {
|
||||
"project.parent.groupId"
|
||||
| "project.parent.artifactId"
|
||||
| "project.parent.version"
|
||||
| "parent.groupId"
|
||||
| "parent.version" => {
|
||||
let key = name.rsplit('.').next().unwrap();
|
||||
Some(&name[name.len() - key.len()..])
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(key) = parent_key {
|
||||
if !matches!(key, "groupId" | "artifactId" | "version") {
|
||||
return None; // No other `project.parent.*` property has a declaration.
|
||||
}
|
||||
let root = xml::parse(&chain[0].1).filter(|e| e.name == "project")?;
|
||||
let e = root.child("parent")?.child(key)?;
|
||||
return Some(PomGoto {
|
||||
path: chain[0].0.clone(),
|
||||
range: range_of(&chain[0].1, e),
|
||||
kind: PomGotoKind::Property,
|
||||
label: name.clone(),
|
||||
});
|
||||
}
|
||||
// Built-in coordinates: the POM's own element, else the first ancestor declaring one.
|
||||
if let Some(key) = name.strip_prefix("project.") {
|
||||
if !matches!(key, "groupId" | "artifactId" | "version" | "packaging" | "name") {
|
||||
return None; // `project.basedir`, `project.build.directory`… have no element.
|
||||
}
|
||||
for (p, text) in &chain {
|
||||
let Some(root) = xml::parse(text).filter(|e| e.name == "project") else { continue };
|
||||
let Some(e) = root.child(key).filter(|e| !e.text.trim().is_empty()) else { continue };
|
||||
return Some(PomGoto {
|
||||
path: p.clone(),
|
||||
range: range_of(text, e),
|
||||
kind: PomGotoKind::Property,
|
||||
label: name.clone(),
|
||||
});
|
||||
}
|
||||
return None;
|
||||
}
|
||||
// A property of `<properties>`: the first POM of the chain (child-first) that
|
||||
// declares it, at project level or in an active profile.
|
||||
for (p, text) in &chain {
|
||||
let Some(root) = xml::parse(text).filter(|e| e.name == "project") else { continue };
|
||||
let active: Vec<String> = parse_pom(text)
|
||||
.map(|pom| resolver.active(&pom.profiles).map(|pr| pr.id.clone()).collect())
|
||||
.unwrap_or_default();
|
||||
// Project level first, then the first active profile declaring the property.
|
||||
let e = root.child("properties").and_then(|props| props.child(&name)).or_else(|| {
|
||||
root.list("profiles", "profile")
|
||||
.into_iter()
|
||||
.find(|profile| {
|
||||
active.contains(&profile.child("id").map(|id| id.text.trim().to_owned()).unwrap_or_default())
|
||||
&& profile.child("properties").and_then(|props| props.child(&name)).is_some()
|
||||
})?
|
||||
.child("properties")?
|
||||
.child(&name)
|
||||
});
|
||||
if let Some(e) = e {
|
||||
return Some(PomGoto {
|
||||
path: p.clone(),
|
||||
range: range_of(text, e),
|
||||
kind: PomGotoKind::Property,
|
||||
label: name.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The `<dependencyManagement>` / `<pluginManagement>` entry providing the version
|
||||
/// of the dependency / plugin element `e`: this POM's own management first, then the
|
||||
/// parent chain, child-first (the nearest declaration wins). Coordinates are matched
|
||||
/// after interpolation with each POM's effective properties.
|
||||
fn managed_target(
|
||||
text: &str,
|
||||
path: &Path,
|
||||
e: &Element,
|
||||
kind: PomGotoKind,
|
||||
local_repo: Option<PathBuf>,
|
||||
) -> Option<PomGoto> {
|
||||
let mut resolver = Resolver::new(local_repo.clone(), &[]);
|
||||
let chain = parent_chain(path, text, local_repo);
|
||||
let key = coordinates(e, &properties_at(&mut resolver, &chain, 0))?;
|
||||
let (section, item) = match kind {
|
||||
PomGotoKind::ManagedDependency => ("dependencyManagement/dependencies", "dependency"),
|
||||
_ => ("build/pluginManagement/plugins", "plugin"),
|
||||
};
|
||||
for (i, (p, text)) in chain.iter().enumerate() {
|
||||
let root = xml::parse(text).filter(|e| e.name == "project")?;
|
||||
let props = properties_at(&mut resolver, &chain, i);
|
||||
let Some(hit) = root.list(section, item).into_iter().find(|m| coordinates(m, &props).as_ref() == Some(&key))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let target = hit.child("artifactId").unwrap_or(hit);
|
||||
return Some(PomGoto {
|
||||
path: p.clone(),
|
||||
range: range_of(text, target),
|
||||
kind,
|
||||
label: format!("{}:{}", key.0, key.1),
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The range of element `e` in `text`.
|
||||
fn range_of(text: &str, e: &Element) -> Range {
|
||||
Range::new(pos_at(text, e.start), pos_at(text, e.end))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `parent_chain` returns paths normalized by `dunce::canonicalize`, so the
|
||||
/// expected values compared against them must go through the same call: the
|
||||
/// temp dirs sit behind symlinks on macOS (`/var` → `/private/var`) and under
|
||||
/// an 8.3 short name on Windows, and raw paths would not match on those runners.
|
||||
fn canon(path: &Path) -> PathBuf {
|
||||
dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
|
||||
}
|
||||
|
||||
/// A plugin jar in `repo` whose descriptor declares `goals`.
|
||||
fn write_plugin_jar(repo: &Path, group: &str, artifact: &str, version: &str, goals: &[&str]) {
|
||||
let dir = repo.join(group.replace('.', "/")).join(artifact).join(version);
|
||||
@@ -2215,6 +2462,325 @@ mod tests {
|
||||
assert_eq!((d.group_id.as_str(), d.version.as_deref()), ("g", Some("1")), "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------- goto declaration
|
||||
|
||||
/// The position of the first character of `needle` (a click on it).
|
||||
fn at(text: &str, needle: &str) -> Pos {
|
||||
pos_at(text, text.find(needle).unwrap())
|
||||
}
|
||||
|
||||
/// A parent POM and a child of it in `tmp`: the parent at `tmp/pom.xml`, the
|
||||
/// child at `tmp/app/pom.xml` (found through the default `../pom.xml`).
|
||||
fn write_parent_child(tmp: &Path, parent: &str, child: &str) {
|
||||
std::fs::create_dir_all(tmp.join("app")).unwrap();
|
||||
std::fs::write(tmp.join("pom.xml"), parent).unwrap();
|
||||
std::fs::write(tmp.join("app/pom.xml"), child).unwrap();
|
||||
}
|
||||
|
||||
const CHILD_HEADER: &str = r#"<project xmlns="http://maven.apache.org/POM/4.0.0">
|
||||
<parent>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>parent</artifactId>
|
||||
<version>1.0</version>
|
||||
</parent>
|
||||
<artifactId>app</artifactId>
|
||||
"#;
|
||||
|
||||
const PARENT_HEADER: &str = r#"<project xmlns="http://maven.apache.org/POM/4.0.0">
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>parent</artifactId>
|
||||
<version>1.0</version>
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn a_property_reference_finds_its_definition_in_the_same_pom() {
|
||||
let text = format!(
|
||||
r#"{CHILD_HEADER}<properties>
|
||||
<example.version>1.2.3</example.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<version>${{example.version}}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>"#
|
||||
);
|
||||
let path = Path::new("/tmp/pom.xml");
|
||||
let goto = goto_declaration(&text, path, at(&text, "${example.version}"), None).unwrap();
|
||||
assert_eq!(goto.kind, PomGotoKind::Property);
|
||||
assert_eq!(goto.label, "example.version");
|
||||
assert_eq!(goto.path, path);
|
||||
let from = text.find("<example.version>").unwrap();
|
||||
let to = text.find("</example.version>").unwrap() + "</example.version>".len();
|
||||
assert_eq!(goto.range, Range::new(pos_at(&text, from), pos_at(&text, to)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inherited_property_reference_finds_its_definition_in_the_parent_pom() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let parent = format!(
|
||||
r#"{PARENT_HEADER}<properties>
|
||||
<example.version>1.2.3</example.version>
|
||||
</properties>
|
||||
</project>"#
|
||||
);
|
||||
let child = format!(
|
||||
r#"{CHILD_HEADER}<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<version>${{example.version}}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>"#
|
||||
);
|
||||
write_parent_child(tmp.path(), &parent, &child);
|
||||
let path = tmp.path().join("app/pom.xml");
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let goto = goto_declaration(&text, &path, at(&text, "${example.version}"), None).unwrap();
|
||||
assert_eq!(goto.kind, PomGotoKind::Property);
|
||||
assert_eq!(goto.path, canon(&tmp.path().join("pom.xml")));
|
||||
let from = parent.find("<example.version>").unwrap();
|
||||
assert_eq!(goto.range.start, pos_at(&parent, from));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_property_wins_over_the_parent_s_definition() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let parent = format!(
|
||||
r#"{PARENT_HEADER}<properties>
|
||||
<example.version>1.0.0</example.version>
|
||||
</properties>
|
||||
</project>"#
|
||||
);
|
||||
let child = format!(
|
||||
r#"{CHILD_HEADER}<properties>
|
||||
<example.version>2.0.0</example.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<version>${{example.version}}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>"#
|
||||
);
|
||||
write_parent_child(tmp.path(), &parent, &child);
|
||||
let path = tmp.path().join("app/pom.xml");
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let goto = goto_declaration(&text, &path, at(&text, "${example.version}"), None).unwrap();
|
||||
assert_eq!(goto.path, canon(&path), "the child's own definition");
|
||||
let from = text.find("<example.version>").unwrap();
|
||||
let to = text.find("</example.version>").unwrap() + "</example.version>".len();
|
||||
assert_eq!(goto.range, Range::new(pos_at(&text, from), pos_at(&text, to)));
|
||||
assert!(text[from..to].contains("2.0.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_managed_dependency_reference_finds_the_managing_declaration_in_the_parent() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let parent = format!(
|
||||
r#"{PARENT_HEADER}<properties>
|
||||
<example.version>1.2.3</example.version>
|
||||
</properties>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>example-lib</artifactId>
|
||||
<version>${{example.version}}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
</project>"#
|
||||
);
|
||||
let child = format!(
|
||||
r#"{CHILD_HEADER}<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>example-lib</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>"#
|
||||
);
|
||||
write_parent_child(tmp.path(), &parent, &child);
|
||||
let path = tmp.path().join("app/pom.xml");
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let goto = goto_declaration(&text, &path, at(&text, "<artifactId>example-lib"), None).unwrap();
|
||||
assert_eq!(goto.kind, PomGotoKind::ManagedDependency);
|
||||
assert_eq!(goto.label, "com.example:example-lib");
|
||||
assert_eq!(goto.path, canon(&tmp.path().join("pom.xml")));
|
||||
let from = parent.find("<artifactId>example-lib</artifactId>").unwrap();
|
||||
let to = from + "<artifactId>example-lib</artifactId>".len();
|
||||
assert_eq!(goto.range, Range::new(pos_at(&parent, from), pos_at(&parent, to)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_managed_plugin_reference_finds_the_managing_declaration_in_the_parent() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let parent = format!(
|
||||
r#"{PARENT_HEADER}<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</project>"#
|
||||
);
|
||||
let child = format!(
|
||||
r#"{CHILD_HEADER}<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>"#
|
||||
);
|
||||
write_parent_child(tmp.path(), &parent, &child);
|
||||
let path = tmp.path().join("app/pom.xml");
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let goto = goto_declaration(&text, &path, at(&text, "<artifactId>maven-compiler-plugin"), None).unwrap();
|
||||
assert_eq!(goto.kind, PomGotoKind::ManagedPlugin);
|
||||
assert_eq!(goto.label, "org.apache.maven.plugins:maven-compiler-plugin");
|
||||
assert_eq!(goto.path, canon(&tmp.path().join("pom.xml")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inherited_property_is_found_in_a_parent_pom_of_the_local_repository() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repository");
|
||||
let parent_dir = repo.join("com/example/parent/1.0");
|
||||
std::fs::create_dir_all(&parent_dir).unwrap();
|
||||
let parent = format!(
|
||||
r#"{PARENT_HEADER}<properties>
|
||||
<example.version>1.2.3</example.version>
|
||||
</properties>
|
||||
</project>"#
|
||||
);
|
||||
std::fs::write(parent_dir.join("parent-1.0.pom"), &parent).unwrap();
|
||||
let child = format!(
|
||||
r#"{CHILD_HEADER}<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<version>${{example.version}}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>"#
|
||||
);
|
||||
let path = tmp.path().join("app/pom.xml");
|
||||
std::fs::create_dir_all(tmp.path().join("app")).unwrap();
|
||||
std::fs::write(&path, &child).unwrap();
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let goto = goto_declaration(&text, &path, at(&text, "${example.version}"), Some(repo)).unwrap();
|
||||
assert_eq!(goto.kind, PomGotoKind::Property);
|
||||
assert_eq!(goto.path, canon(&parent_dir.join("parent-1.0.pom")));
|
||||
assert_eq!(goto.range.start, pos_at(&parent, parent.find("<example.version>").unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_version_resolves_to_the_first_pom_declaring_its_own_version() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let parent = format!(r#"{PARENT_HEADER}<packaging>pom</packaging></project>"#);
|
||||
let child = format!(
|
||||
r#"{CHILD_HEADER}<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<version>${{project.version}}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>"#
|
||||
);
|
||||
write_parent_child(tmp.path(), &parent, &child);
|
||||
let path = tmp.path().join("app/pom.xml");
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let goto = goto_declaration(&text, &path, at(&text, "${project.version}"), None).unwrap();
|
||||
assert_eq!(goto.path, canon(&tmp.path().join("pom.xml")), "the child has no own <version>");
|
||||
assert_eq!(goto.range.start, pos_at(&parent, parent.find("<version>").unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicks_without_a_resolvable_declaration_find_nothing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let parent = format!(
|
||||
r#"{PARENT_HEADER}<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>managed-lib</artifactId>
|
||||
<version>1.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
</project>"#
|
||||
);
|
||||
let child = format!(
|
||||
r#"{CHILD_HEADER}<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>direct-lib</artifactId>
|
||||
<version>${{missing.key}}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>other-lib</artifactId>
|
||||
<version>2.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>"#
|
||||
);
|
||||
write_parent_child(tmp.path(), &parent, &child);
|
||||
let path = tmp.path().join("app/pom.xml");
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
// The property is declared nowhere along the chain.
|
||||
assert_eq!(goto_declaration(&text, &path, at(&text, "${missing.key}"), None), None);
|
||||
// The dependency names its own version: it is the declaration.
|
||||
assert_eq!(goto_declaration(&text, &path, at(&text, "<artifactId>other-lib"), None), None);
|
||||
// A management entry is a declaration itself, not a reference.
|
||||
let parent_path = tmp.path().join("pom.xml");
|
||||
let parent_text = std::fs::read_to_string(&parent_path).unwrap();
|
||||
assert_eq!(
|
||||
goto_declaration(&parent_text, &parent_path, at(&parent_text, "<artifactId>managed-lib"), None),
|
||||
None
|
||||
);
|
||||
// Offsets beyond the document, and non-POM documents, find nothing.
|
||||
assert_eq!(goto_declaration(&text, &path, Pos::new(999, 0), None), None);
|
||||
assert_eq!(goto_declaration("<project></project>", &path, Pos::new(0, 3), None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_property_reference_after_non_ascii_text_is_still_found() {
|
||||
let text = format!(
|
||||
r#"{CHILD_HEADER}<properties>
|
||||
<!-- Версия сборки: сборка 2026 -->
|
||||
<example.version>1.2.3</example.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<!-- Проверка: ссылка на свойство -->
|
||||
<version>${{example.version}}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>"#
|
||||
);
|
||||
let path = Path::new("/tmp/pom.xml");
|
||||
let goto = goto_declaration(&text, path, at(&text, "${example.version}"), None).unwrap();
|
||||
assert_eq!(goto.kind, PomGotoKind::Property);
|
||||
assert_eq!(goto.path, path);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -95,6 +95,24 @@ fn maven_sync_goals(effective: &Path, offline: bool) -> Vec<String> {
|
||||
"-Dverbose".into(),
|
||||
]
|
||||
}
|
||||
|
||||
/// The settings' Maven options for the sync runs: the thread count (`-T`, also
|
||||
/// `--threads`) is left out, because the sync pins its own `-T1` — its console
|
||||
/// output is parsed as one stream, which a parallel build interleaves.
|
||||
fn sync_maven_options(options: &[String]) -> Vec<String> {
|
||||
let mut out = Vec::with_capacity(options.len());
|
||||
let mut args = options.iter();
|
||||
while let Some(arg) = args.next() {
|
||||
if arg == "-T" || arg == "--threads" {
|
||||
args.next(); // the count itself
|
||||
} else if (arg.starts_with("-T") && arg.len() > 2) || arg.starts_with("--threads=") {
|
||||
// `--threads=4` / `-T4`: the count is part of the argument.
|
||||
} else {
|
||||
out.push(arg.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
const GRADLE_CACHE: &str = "gradle.json";
|
||||
const MAVEN_PROFILES: &str = "maven-profiles.json";
|
||||
|
||||
@@ -324,7 +342,7 @@ pub fn sync_maven(
|
||||
// `dependency:tree` output of concurrent modules, which the sync parses
|
||||
// as one stream. mvn is serial anyway, so this only pins the daemon.
|
||||
let mut args: Vec<String> = vec!["-B".into(), "-fae".into(), "-Dstyle.color=never".into(), "-T1".into()];
|
||||
args.extend(options.maven_options.iter().cloned());
|
||||
args.extend(sync_maven_options(&options.maven_options));
|
||||
if options.offline {
|
||||
args.push("-o".into());
|
||||
}
|
||||
@@ -831,6 +849,19 @@ mod tests {
|
||||
assert_eq!(error_summary("one\nlast line\n\n"), "last line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_sync_leaves_out_the_settings_thread_count() {
|
||||
// The sync pins its own `-T1`; the user's `-T` (Settings › Maven) would win
|
||||
// over it on the mvnd command line and interleave the parsed output.
|
||||
let options = ["-s".to_owned(), "settings.xml".to_owned(), "-T".to_owned(), "4".to_owned()];
|
||||
assert_eq!(sync_maven_options(&options), ["-s", "settings.xml"]);
|
||||
let options = ["--threads".to_owned(), "2C".to_owned(), "-Dmaven.repo.local=/m2".to_owned()];
|
||||
assert_eq!(sync_maven_options(&options), ["-Dmaven.repo.local=/m2"]);
|
||||
assert_eq!(sync_maven_options(&["-T4".to_owned()]), Vec::<String>::new());
|
||||
assert_eq!(sync_maven_options(&["--threads=4".to_owned()]), Vec::<String>::new());
|
||||
assert!(sync_maven_options(&[]).is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn maven_sync_runs_the_daemon_command_serially() {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! The file list on the OS clipboard: what Explorer copies when the user
|
||||
//! copies files, so the project view can paste them, and what the project view
|
||||
//! writes so Explorer can paste the files it copied (IDEA does both). The
|
||||
//! written list comes with the paths as text, so a paste into an editor
|
||||
//! inserts them instead of doing nothing.
|
||||
//! written list comes with the file names as text, so a paste into an editor
|
||||
//! inserts them instead of doing nothing (#1878).
|
||||
//!
|
||||
//! Windows keeps it as `CF_HDROP`: a `DROPFILES` header and a double-NUL
|
||||
//! terminated list of absolute paths, wide when `fWide` is set. The data is set
|
||||
@@ -44,6 +44,21 @@ pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
imp::set_files(paths)
|
||||
}
|
||||
|
||||
/// The text flavor written beside the file list: the files' names, one per
|
||||
/// line. An editor paste inserts names, not the absolute paths the file list
|
||||
/// keeps for Explorer (#1878; IDEA's text flavor is names too). A path with no
|
||||
/// file name (a root like `C:\`) keeps its whole path.
|
||||
#[cfg(any(windows, target_os = "macos", test))]
|
||||
fn names_text(paths: &[PathBuf], separator: &str) -> String {
|
||||
paths
|
||||
.iter()
|
||||
.map(|p| {
|
||||
p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| p.to_string_lossy().into_owned())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(separator)
|
||||
}
|
||||
|
||||
/// `DROPFILES` for `paths`, in the wide form so names outside the ANSI code
|
||||
/// page survive. Empty paths are skipped.
|
||||
pub fn encode(paths: &[PathBuf]) -> Vec<u8> {
|
||||
@@ -108,7 +123,7 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use super::{HEADER, decode, encode};
|
||||
use super::{HEADER, decode, encode, names_text};
|
||||
use std::ffi::c_void;
|
||||
use std::path::PathBuf;
|
||||
use std::ptr;
|
||||
@@ -220,9 +235,9 @@ mod imp {
|
||||
if bytes.len() <= HEADER {
|
||||
return false;
|
||||
}
|
||||
// The paths as text, newline-separated, so pasting into an editor
|
||||
// inserts them (IDEA writes the list and the text together).
|
||||
let text = paths.iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>().join("\r\n");
|
||||
// The file names as text: the file list keeps the absolute paths for
|
||||
// Explorer, while an editor paste inserts the names (#1878).
|
||||
let text = names_text(paths, "\r\n");
|
||||
// SAFETY: the blocks are allocated, filled, handed to the clipboard and
|
||||
// freed only on the paths where the clipboard did not take ownership.
|
||||
unsafe {
|
||||
@@ -242,7 +257,7 @@ mod imp {
|
||||
return false;
|
||||
}
|
||||
// Replacing the list also drops the text the user copied before;
|
||||
// the paths' own text is set back with it.
|
||||
// the file names are set back with it.
|
||||
if EmptyClipboard() == 0 {
|
||||
CloseClipboard();
|
||||
GlobalFree(memory);
|
||||
@@ -278,6 +293,8 @@ mod imp {
|
||||
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::names_text;
|
||||
|
||||
/// `NSURL` as the one class to read, limited to file URLs: a web link the
|
||||
/// user copied is not a file to paste.
|
||||
fn read_file_urls<R>(
|
||||
@@ -338,13 +355,11 @@ mod imp {
|
||||
urls.iter().map(|url| ProtocolObject::from_ref(&**url)).collect();
|
||||
let board = NSPasteboard::generalPasteboard();
|
||||
// Replacing the list also drops the text the user copied before;
|
||||
// the paths' own text is set back with it, so an editor paste
|
||||
// inserts them (IDEA writes the list and the text together).
|
||||
// the file names are set back as text, so an editor paste inserts
|
||||
// names, not paths (#1878).
|
||||
board.clearContents();
|
||||
let written = board.writeObjects(&NSArray::from_slice(&writers));
|
||||
let text = NSString::from_str(
|
||||
&paths.iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>().join("\n"),
|
||||
);
|
||||
let text = NSString::from_str(&names_text(paths, "\n"));
|
||||
board.setString_forType(&text, unsafe { NSPasteboardTypeString });
|
||||
written
|
||||
})
|
||||
@@ -415,6 +430,15 @@ mod tests {
|
||||
assert_eq!(decode(&far), Vec::<PathBuf>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_text_flavor_is_the_file_names() {
|
||||
assert_eq!(names_text(&paths(&["C:/work/project/a.txt", "C:/work/project/sub"]), "\r\n"), "a.txt\r\nsub");
|
||||
// A path with no file name (the filesystem root) keeps its whole path.
|
||||
let root = PathBuf::from("/");
|
||||
assert!(root.file_name().is_none());
|
||||
assert_eq!(names_text(std::slice::from_ref(&root), "\n"), root.to_string_lossy());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ansi_list_is_still_read_before_the_terminator() {
|
||||
let mut bytes = vec![0u8; HEADER];
|
||||
|
||||
@@ -15,6 +15,8 @@ use std::sync::Arc;
|
||||
pub enum IdeEvent {
|
||||
/// Project window membership or selection changed.
|
||||
WindowGroupsChanged,
|
||||
/// A window entered or left full screen, itself or as a member of a full-screen window group.
|
||||
WindowFullscreenChanged,
|
||||
ProjectTrustChanged {
|
||||
root: crate::IpcPath,
|
||||
trusted: bool,
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Go workspace module paths shared by project builds and run detection.
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Module directories from a go.work file. Quoted paths and comments follow Go's file syntax.
|
||||
pub fn work_modules(text: &str) -> Vec<PathBuf> {
|
||||
let mut tokens = Vec::new();
|
||||
let mut chars = text.chars().peekable();
|
||||
while let Some(ch) = chars.next() {
|
||||
match ch {
|
||||
'\n' | '(' | ')' => tokens.push(ch.to_string()),
|
||||
ch if ch.is_whitespace() => {}
|
||||
'/' if chars.peek() == Some(&'/') => {
|
||||
for c in chars.by_ref() {
|
||||
if c == '\n' {
|
||||
tokens.push("\n".into());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
'"' | '`' => {
|
||||
let Some(token) = quoted_work_path(&mut chars, ch) else { return Vec::new() };
|
||||
tokens.push(token);
|
||||
}
|
||||
_ => {
|
||||
let mut token = ch.to_string();
|
||||
while chars.peek().is_some_and(|c| !c.is_whitespace() && *c != '(' && *c != ')') {
|
||||
token.push(chars.next().unwrap());
|
||||
}
|
||||
tokens.push(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut start = true;
|
||||
let mut tokens = tokens.into_iter();
|
||||
while let Some(token) = tokens.next() {
|
||||
if token == "\n" {
|
||||
start = true;
|
||||
continue;
|
||||
}
|
||||
if start
|
||||
&& token == "use"
|
||||
&& let Some(path) = tokens.next()
|
||||
{
|
||||
if path == "(" {
|
||||
let mut paths = Vec::new();
|
||||
let mut closed = false;
|
||||
for path in tokens.by_ref() {
|
||||
if path == ")" {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
if path != "\n" && !path.is_empty() {
|
||||
paths.push(PathBuf::from(path));
|
||||
}
|
||||
}
|
||||
if closed {
|
||||
out.extend(paths);
|
||||
}
|
||||
} else if path != "\n" && !path.is_empty() {
|
||||
out.push(PathBuf::from(path));
|
||||
}
|
||||
}
|
||||
start = false;
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
out.retain(|path| seen.insert(path.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
fn quoted_work_path(chars: &mut std::iter::Peekable<std::str::Chars<'_>>, quote: char) -> Option<String> {
|
||||
let mut bytes = Vec::new();
|
||||
while let Some(ch) = chars.next() {
|
||||
if ch == quote {
|
||||
return String::from_utf8(bytes).ok();
|
||||
}
|
||||
if ch == '\\' && quote == '"' {
|
||||
let escaped = chars.next()?;
|
||||
let byte = match escaped {
|
||||
'a' => 7,
|
||||
'b' => 8,
|
||||
'f' => 12,
|
||||
'n' => 10,
|
||||
'r' => 13,
|
||||
't' => 9,
|
||||
'v' => 11,
|
||||
'\\' => b'\\',
|
||||
'"' => b'"',
|
||||
'x' => {
|
||||
let digits: String = chars.by_ref().take(2).collect();
|
||||
if digits.len() != 2 {
|
||||
return None;
|
||||
}
|
||||
u8::from_str_radix(&digits, 16).ok()?
|
||||
}
|
||||
'u' | 'U' => {
|
||||
let width = if escaped == 'u' { 4 } else { 8 };
|
||||
let digits: String = chars.by_ref().take(width).collect();
|
||||
if digits.len() != width {
|
||||
return None;
|
||||
}
|
||||
let ch = char::from_u32(u32::from_str_radix(&digits, 16).ok()?)?;
|
||||
bytes.extend_from_slice(ch.to_string().as_bytes());
|
||||
continue;
|
||||
}
|
||||
'0'..='7' => {
|
||||
let digits = format!("{escaped}{}", chars.by_ref().take(2).collect::<String>());
|
||||
if digits.len() != 3 {
|
||||
return None;
|
||||
}
|
||||
u8::from_str_radix(&digits, 8).ok()?
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
bytes.push(byte);
|
||||
} else {
|
||||
if ch == '\n' && quote == '"' {
|
||||
return None;
|
||||
}
|
||||
bytes.extend_from_slice(ch.to_string().as_bytes());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
pub mod editor_settings;
|
||||
pub mod error;
|
||||
pub mod event;
|
||||
pub mod go;
|
||||
pub mod ids;
|
||||
pub mod ignored;
|
||||
pub mod inspection_settings;
|
||||
@@ -16,6 +17,7 @@ pub mod jsonc;
|
||||
pub mod output_encoding;
|
||||
pub mod process;
|
||||
pub mod project_dir;
|
||||
pub mod project_roots;
|
||||
pub mod proxy_settings;
|
||||
pub mod remote_settings;
|
||||
pub mod settings;
|
||||
|
||||
@@ -299,9 +299,11 @@ fn appimage_fixes() -> Vec<(OsString, Option<OsString>)> {
|
||||
const APPIMAGE_LAUNCH_VARS: [&str; 4] = ["APPDIR", "APPIMAGE", "ARGV0", "OWD"];
|
||||
|
||||
/// What to change in `vars` (an environment) so a child sees the host's environment rather
|
||||
/// than the AppImage's: every `:`-separated entry inside `$APPDIR` is dropped (a saved
|
||||
/// `<NAME>_ORIG` wins when present), variables left empty are removed, and so are the
|
||||
/// runtime's own launch variables. Nothing changes when `APPDIR` is not set.
|
||||
/// than the AppImage's: every `:`-separated entry inside `$APPDIR` — or inside *any*
|
||||
/// AppImage mount, since an in-app update restart inherits the previous mount's entries
|
||||
/// alongside the new one — is dropped (a saved `<NAME>_ORIG` wins when present),
|
||||
/// variables left empty are removed, and so are the runtime's own launch variables.
|
||||
/// Nothing changes when `APPDIR` is not set.
|
||||
fn appimage_env_fixes(vars: &[(OsString, OsString)]) -> Vec<(OsString, Option<OsString>)> {
|
||||
let get = |name: &str| vars.iter().find(|(k, _)| k == name).map(|(_, v)| v);
|
||||
let Some(appdir) =
|
||||
@@ -309,7 +311,12 @@ fn appimage_env_fixes(vars: &[(OsString, OsString)]) -> Vec<(OsString, Option<Os
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let inside = |entry: &str| entry.strip_prefix(appdir).is_some_and(|rest| rest.is_empty() || rest.starts_with('/'));
|
||||
let inside = |entry: &str| {
|
||||
let own = entry.strip_prefix(appdir).is_some_and(|rest| rest.is_empty() || rest.starts_with('/'));
|
||||
// AppImages extract to `/tmp/.mount_<name>`; an entry under another mount is
|
||||
// another image's (e.g. the pre-update one a restart inherited), never the host's.
|
||||
own || entry.starts_with("/tmp/.mount_")
|
||||
};
|
||||
let mut fixes = Vec::new();
|
||||
for (key, value) in vars {
|
||||
let (Some(name), Some(value)) = (key.to_str(), value.to_str()) else { continue };
|
||||
@@ -715,7 +722,7 @@ mod tests {
|
||||
("PATH", "/tmp/.mount_OpenIDabc/usr/bin/:/tmp/.mount_OpenIDabc/usr/sbin/:/usr/local/bin:/usr/bin"),
|
||||
("XDG_DATA_DIRS", "/tmp/.mount_OpenIDabc/usr/share:/usr/share:/usr/local/share:/usr/share"),
|
||||
("HOME", "/home/me"),
|
||||
("JAVA_HOME", "/tmp/.mount_OpenIDabcdef/jdk"),
|
||||
("JAVA_HOME", "/opt/jdk"),
|
||||
]);
|
||||
assert_eq!(
|
||||
got,
|
||||
@@ -728,6 +735,27 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_of_a_previous_updates_mount_are_dropped() {
|
||||
// An in-app update restart inherits the old mount's entries: a child's curl
|
||||
// must not load the old image's libraries (they can still be mounted).
|
||||
let got = fixes(&[
|
||||
("APPDIR", "/tmp/.mount_OpenIDjIlFFA"),
|
||||
("LD_LIBRARY_PATH", "/tmp/.mount_OpenIDjIlFFA/usr/lib/:/tmp/.mount_OpenIDdaNGfM/usr/lib/:/usr/local/lib"),
|
||||
("PATH", "/tmp/.mount_OpenIDjIlFFA/usr/bin/:/tmp/.mount_OpenIDdaNGfM/usr/bin/:/usr/bin"),
|
||||
("GIO_MODULE_DIR", "/tmp/.mount_OpenIDdaNGfM/usr/lib/gio/modules"),
|
||||
]);
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
fix("APPDIR", None),
|
||||
fix("LD_LIBRARY_PATH", Some("/usr/local/lib")),
|
||||
fix("PATH", Some("/usr/bin")),
|
||||
fix("GIO_MODULE_DIR", None),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variables_left_empty_are_removed() {
|
||||
// AppRun prepends to an unset variable, leaving a trailing `:`; hooks set single paths.
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
//! Shared filesystem rules for discovering builds and resolving their owners.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const SEARCH_DEPTH: usize = 3;
|
||||
|
||||
pub fn children(dir: &Path) -> Vec<PathBuf> {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
|
||||
let mut dirs: Vec<_> = entries
|
||||
.flatten()
|
||||
.filter(|entry| {
|
||||
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
|
||||
return false;
|
||||
}
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
!name.starts_with('.')
|
||||
&& !matches!(
|
||||
name.as_ref(),
|
||||
"node_modules" | "target" | "build" | "dist" | "vendor" | "out" | "bin" | "obj" | "venv"
|
||||
)
|
||||
})
|
||||
.map(|entry| entry.path())
|
||||
.collect();
|
||||
dirs.sort();
|
||||
dirs
|
||||
}
|
||||
|
||||
pub fn discover(root: &Path, markers: &[&str]) -> Vec<PathBuf> {
|
||||
discover_matching(root, SEARCH_DEPTH, true, |dir| markers.iter().any(|marker| dir.join(marker).is_file()))
|
||||
}
|
||||
|
||||
pub fn discover_matching(
|
||||
root: &Path,
|
||||
max_depth: usize,
|
||||
stop_at_match: bool,
|
||||
marked: impl Fn(&Path) -> bool,
|
||||
) -> Vec<PathBuf> {
|
||||
discover_matching_cancellable(root, max_depth, stop_at_match, &crate::CancellationToken::new(), marked)
|
||||
}
|
||||
|
||||
pub fn discover_matching_cancellable(
|
||||
root: &Path,
|
||||
max_depth: usize,
|
||||
stop_at_match: bool,
|
||||
cancel: &crate::CancellationToken,
|
||||
marked: impl Fn(&Path) -> bool,
|
||||
) -> Vec<PathBuf> {
|
||||
let mut found = Vec::new();
|
||||
let mut pending = vec![(root.to_path_buf(), 0)];
|
||||
while let Some((dir, depth)) = pending.pop() {
|
||||
if cancel.is_cancelled() {
|
||||
break;
|
||||
}
|
||||
if marked(&dir) {
|
||||
found.push(dir.clone());
|
||||
if stop_at_match {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// A source folder may itself be a build root (e.g. src/pom.xml), but
|
||||
// source trees without their own build marker are never searched.
|
||||
let source = dir.join("src");
|
||||
if source.is_dir() && !source.is_symlink() && marked(&source) {
|
||||
found.push(source);
|
||||
}
|
||||
if depth < max_depth {
|
||||
pending.extend(
|
||||
children(&dir)
|
||||
.into_iter()
|
||||
.rev()
|
||||
.filter(|child| !child.ends_with("src"))
|
||||
.map(|child| (child, depth + 1)),
|
||||
);
|
||||
}
|
||||
}
|
||||
found.sort();
|
||||
found.dedup();
|
||||
found
|
||||
}
|
||||
|
||||
/// Expands workspace member patterns one level deep: `dir`, `dir/*`, `dir/**`.
|
||||
pub fn expand_members(root: &Path, patterns: &[String], marker: &str) -> Vec<PathBuf> {
|
||||
let mut dirs = Vec::new();
|
||||
for pattern in patterns {
|
||||
let pattern = pattern.trim().trim_start_matches("./").trim_end_matches('/');
|
||||
if pattern.is_empty() || pattern.starts_with('!') {
|
||||
continue;
|
||||
}
|
||||
let base = pattern.strip_suffix("/**").or_else(|| pattern.strip_suffix("/*"));
|
||||
match base {
|
||||
Some(base) if !base.contains('*') => {
|
||||
dirs.extend(children(&root.join(base)).into_iter().filter(|d| d.join(marker).is_file()))
|
||||
}
|
||||
None if !pattern.contains('*') => {
|
||||
let dir = root.join(pattern);
|
||||
if dir.join(marker).is_file() {
|
||||
dirs.push(dir);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
dirs.retain(|d| seen.insert(d.clone()));
|
||||
dirs
|
||||
}
|
||||
|
||||
pub fn node_workspace_members(root: &Path) -> Vec<PathBuf> {
|
||||
let package = std::fs::read(root.join("package.json"))
|
||||
.ok()
|
||||
.and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
|
||||
.unwrap_or_default();
|
||||
expand_members(root, &node_workspace_patterns(root, &package), "package.json")
|
||||
}
|
||||
|
||||
fn node_workspace_patterns(root: &Path, pkg: &serde_json::Value) -> Vec<String> {
|
||||
let mut patterns: Vec<String> = Vec::new();
|
||||
let ws = pkg.get("workspaces");
|
||||
let list = ws
|
||||
.and_then(serde_json::Value::as_array)
|
||||
.or_else(|| ws.and_then(|w| w.get("packages")).and_then(serde_json::Value::as_array));
|
||||
if let Some(list) = list {
|
||||
patterns.extend(list.iter().filter_map(serde_json::Value::as_str).map(str::to_owned));
|
||||
}
|
||||
if let Ok(yaml) = std::fs::read_to_string(root.join("pnpm-workspace.yaml")) {
|
||||
let mut in_packages = false;
|
||||
for line in yaml.lines() {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() || trimmed.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
if !line.starts_with([' ', '\t', '-']) {
|
||||
in_packages = trimmed.starts_with("packages:");
|
||||
continue;
|
||||
}
|
||||
if in_packages && let Some(item) = trimmed.strip_prefix('-') {
|
||||
let item = item.split(" #").next().unwrap_or_default().trim().trim_matches(['"', '\'']);
|
||||
patterns.push(item.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
patterns
|
||||
}
|
||||
|
||||
/// The closest package manager declaration or lockfile, shared by build and run.
|
||||
pub fn package_manager(root: &Path) -> &'static str {
|
||||
for dir in root.ancestors() {
|
||||
let package = std::fs::read(dir.join("package.json"))
|
||||
.ok()
|
||||
.and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok());
|
||||
if let Some(pm) = package.as_ref().and_then(|p| p.get("packageManager")).and_then(|p| p.as_str()) {
|
||||
match pm.split('@').next().unwrap_or_default() {
|
||||
"pnpm" => return "pnpm",
|
||||
"yarn" => return "yarn",
|
||||
"bun" => return "bun",
|
||||
"npm" => return "npm",
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for (marker, pm) in [
|
||||
("pnpm-lock.yaml", "pnpm"),
|
||||
("yarn.lock", "yarn"),
|
||||
("bun.lock", "bun"),
|
||||
("bun.lockb", "bun"),
|
||||
("package-lock.json", "npm"),
|
||||
] {
|
||||
if dir.join(marker).is_file() {
|
||||
return pm;
|
||||
}
|
||||
}
|
||||
}
|
||||
"npm"
|
||||
}
|
||||
|
||||
pub fn resolve(root: &Path, path: &Path) -> PathBuf {
|
||||
let mut out = PathBuf::new();
|
||||
for component in root.join(path).components() {
|
||||
match component {
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir if out.file_name().is_some() => {
|
||||
out.pop();
|
||||
}
|
||||
component => out.push(component),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn relative(root: &Path, path: &Path) -> PathBuf {
|
||||
let path = resolve(root, path);
|
||||
path.strip_prefix(resolve(root, Path::new(""))).unwrap_or(&path).to_path_buf()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn package_manager_declarations_are_shared_by_build_and_run() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
std::fs::write(temp.path().join("pnpm-lock.yaml"), "").unwrap();
|
||||
let child = temp.path().join("packages/web");
|
||||
std::fs::create_dir_all(&child).unwrap();
|
||||
assert_eq!(package_manager(&child), "pnpm");
|
||||
std::fs::write(child.join("package.json"), r#"{"packageManager":"[email protected]"}"#).unwrap();
|
||||
assert_eq!(package_manager(&child), "yarn");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovery_has_one_depth_boundary_and_exclusion_policy_for_all_families() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
let markers = [
|
||||
"package.json",
|
||||
"Cargo.toml",
|
||||
"go.mod",
|
||||
"pom.xml",
|
||||
"build.gradle.kts",
|
||||
"pyproject.toml",
|
||||
"composer.json",
|
||||
"Gemfile",
|
||||
"CMakeLists.txt",
|
||||
"project.godot",
|
||||
"deno.json",
|
||||
"Makefile",
|
||||
"justfile",
|
||||
];
|
||||
for marker in markers {
|
||||
for dir in [
|
||||
"apps/one",
|
||||
"services/backend/two",
|
||||
"src",
|
||||
"a/b/c/src",
|
||||
"too/deep/to/find",
|
||||
"node_modules/ignored",
|
||||
"target/ignored",
|
||||
"build/ignored",
|
||||
"vendor/ignored",
|
||||
".hidden",
|
||||
"src/ignored",
|
||||
] {
|
||||
let path = root.join(dir).join(marker);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "").unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
discover(root, &[marker]),
|
||||
["a/b/c/src", "apps/one", "services/backend/two", "src"].map(|dir| root.join(dir))
|
||||
);
|
||||
}
|
||||
std::fs::write(root.join("Cargo.toml"), "").unwrap();
|
||||
assert_eq!(discover(root, &["Cargo.toml"]), [root]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn discovery_never_follows_directory_symlinks() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(temp.path().join("real")).unwrap();
|
||||
std::fs::write(temp.path().join("real/go.mod"), "").unwrap();
|
||||
std::os::unix::fs::symlink(temp.path().join("real"), temp.path().join("alias")).unwrap();
|
||||
assert_eq!(discover(temp.path(), &["go.mod"]), [temp.path().join("real")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_keep_component_boundaries_and_external_roots() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path().join("workspace");
|
||||
assert_eq!(relative(&root, &root.join("apps/../api")), Path::new("api"));
|
||||
assert_eq!(relative(&root, &temp.path().join("workspace-other")), temp.path().join("workspace-other"));
|
||||
assert_eq!(resolve(&root, Path::new("./api/../web")), root.join("web"));
|
||||
}
|
||||
}
|
||||
@@ -268,6 +268,8 @@ pub struct GeneralSettings {
|
||||
pub power_save_mode: bool,
|
||||
/// File › Rename Project… (project layer): the name shown for the project; empty = its folder name.
|
||||
pub project_name: String,
|
||||
/// Where updates come from: `auto` (the CNB mirror for the Chinese UI, else GitHub) | `github` | `cnb`.
|
||||
pub update_source: String,
|
||||
}
|
||||
|
||||
impl Default for GeneralSettings {
|
||||
@@ -282,6 +284,7 @@ impl Default for GeneralSettings {
|
||||
date_format: DateFormatSettings::default(),
|
||||
power_save_mode: false,
|
||||
project_name: String::new(),
|
||||
update_source: "auto".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -364,6 +367,8 @@ pub struct AppearanceSettings {
|
||||
pub red_green_vision: bool,
|
||||
pub different_tool_window_background: bool,
|
||||
pub compact_mode: bool,
|
||||
/// IDEA "Use smaller indents in trees": tool window trees indent less per level.
|
||||
pub small_tree_indents: bool,
|
||||
pub full_path_in_title: bool,
|
||||
pub project_colors_in_toolbar: bool,
|
||||
pub dnd_with_alt_only: bool,
|
||||
@@ -434,6 +439,7 @@ impl Default for AppearanceSettings {
|
||||
red_green_vision: false,
|
||||
different_tool_window_background: false,
|
||||
compact_mode: false,
|
||||
small_tree_indents: false,
|
||||
full_path_in_title: false,
|
||||
project_colors_in_toolbar: true,
|
||||
dnd_with_alt_only: false,
|
||||
@@ -844,6 +850,8 @@ pub struct JavaSettings {
|
||||
/// Project JDK home; empty = per module, the installed JDK matching the
|
||||
/// Java version it targets.
|
||||
pub jdk: String,
|
||||
/// Project Java language level (`8`, `11`, `17`, `21`, `25`); empty = SDK default.
|
||||
pub language_level: String,
|
||||
/// JDK home the Java language server (jdtls) runs on, apart from the project
|
||||
/// JDK (IDEA's "JDK for importer"); empty = the project JDK when new enough,
|
||||
/// else the first installed one that is.
|
||||
@@ -897,6 +905,8 @@ pub enum GradleDistribution {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct MavenSettings {
|
||||
/// JDK home used to run Maven; empty = Project JDK, else the POM's Java version.
|
||||
pub runner_jre: String,
|
||||
/// Project-relative root POMs removed from the Maven project model.
|
||||
pub unlinked_projects: Vec<String>,
|
||||
/// Project-relative POMs outside the root reactor added as independent top-level projects.
|
||||
@@ -913,6 +923,24 @@ pub struct MavenSettings {
|
||||
/// Maven Daemon home (or its `mvnd` executable); empty = `$MVND_HOME`, else
|
||||
/// `mvnd` on `PATH` / common install dirs. Only used when `daemon` is on.
|
||||
pub mvnd_home: String,
|
||||
/// Thread count of Maven builds (`-T`): a number of threads (`4`) or a core
|
||||
/// multiplier (`2C`, `2.5C`); empty = Maven's default (one thread per module).
|
||||
pub threads: String,
|
||||
}
|
||||
|
||||
impl MavenSettings {
|
||||
/// The `-T` value when it is one Maven accepts: a thread count (`4`) or a
|
||||
/// core multiplier with an optional decimal fraction (`1C`, `2.5C`).
|
||||
/// Anything else is dropped: a bad `-T` would make every Maven run fail.
|
||||
pub fn thread_count(&self) -> Option<&str> {
|
||||
let value = self.threads.trim();
|
||||
let number = value.strip_suffix('C').unwrap_or(value);
|
||||
let mut decimal = number.split('.');
|
||||
let well_formed = number.parse::<f64>().is_ok_and(|n| n > 0.0)
|
||||
&& decimal.clone().count() <= 2
|
||||
&& decimal.all(|part| !part.is_empty() && part.chars().all(|c| c.is_ascii_digit()));
|
||||
well_formed.then_some(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -929,6 +957,98 @@ impl Default for TypeScriptSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// Dependency scope for a module dependency or project library (IDEA's Modules › Dependencies).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DependencyScope {
|
||||
#[default]
|
||||
Compile,
|
||||
Test,
|
||||
Runtime,
|
||||
Provided,
|
||||
}
|
||||
|
||||
/// A project-level library (Project Structure › Libraries).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ProjectLibrary {
|
||||
pub name: String,
|
||||
/// Class archives (`.jar`) or class directories.
|
||||
pub classes: Vec<String>,
|
||||
/// Source archives (`-sources.jar`, `.zip`) or source directories.
|
||||
pub sources: Vec<String>,
|
||||
/// Documentation archives (`-javadoc.jar`) or directories.
|
||||
pub javadocs: Vec<String>,
|
||||
pub scope: DependencyScope,
|
||||
}
|
||||
|
||||
/// Dependency entry of a module (Project Structure › Modules › Dependencies).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ModuleDependency {
|
||||
/// `"library"` (references a `ProjectLibrary` by name or path) or `"module"` (references another module).
|
||||
pub kind: String,
|
||||
pub target: String,
|
||||
pub scope: DependencyScope,
|
||||
pub exported: bool,
|
||||
}
|
||||
|
||||
/// Per-module Project Structure overrides (SDK, language level, output paths, dependencies).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ModuleStructureSettings {
|
||||
/// Module SDK home override; empty = inherit Project SDK.
|
||||
pub jdk: String,
|
||||
/// Module language level override; empty = inherit Project language level.
|
||||
pub language_level: String,
|
||||
/// Module compiler output directory override; empty = inherit Project compiler output.
|
||||
pub compiler_output: String,
|
||||
/// Module test compiler output directory override; empty = default.
|
||||
pub test_compiler_output: String,
|
||||
/// Additional module dependencies.
|
||||
pub dependencies: Vec<ModuleDependency>,
|
||||
}
|
||||
|
||||
/// Framework facet attached to a module (Project Structure › Facets).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct FacetConfig {
|
||||
/// `"web"` | `"spring"` | `"jpa"`.
|
||||
pub kind: String,
|
||||
/// Module relative path (`"."` for root module).
|
||||
pub module: String,
|
||||
/// Deployment descriptor path (e.g. `src/main/webapp/WEB-INF/web.xml`, `src/main/resources/META-INF/persistence.xml`).
|
||||
pub descriptor: String,
|
||||
/// Web resource root directory for Web facets (e.g. `src/main/webapp`).
|
||||
pub web_root: String,
|
||||
}
|
||||
|
||||
/// Packaging type of a Project Structure artifact.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ArtifactKind {
|
||||
#[default]
|
||||
Jar,
|
||||
War,
|
||||
WarExploded,
|
||||
}
|
||||
|
||||
/// Packaging artifact definition (Project Structure › Artifacts).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ArtifactConfig {
|
||||
pub name: String,
|
||||
pub kind: ArtifactKind,
|
||||
/// Module relative path (`"."` for root module).
|
||||
pub module: String,
|
||||
/// Output directory (relative to project root or absolute).
|
||||
pub output_directory: String,
|
||||
/// Main class for executable JAR artifacts.
|
||||
pub main_class: String,
|
||||
/// Project library names included in the packaged artifact (`WEB-INF/lib` or JAR manifest).
|
||||
pub include_libraries: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ProjectStructureSettings {
|
||||
@@ -945,9 +1065,28 @@ pub struct ProjectStructureSettings {
|
||||
pub content_roots: Vec<String>,
|
||||
/// "Exclude files": `;`-separated name patterns (`*.log;tmp*`) excluded at any depth.
|
||||
pub exclude_files: String,
|
||||
/// Project compiler output directory (relative to project root or absolute; empty = default).
|
||||
pub compiler_output: String,
|
||||
/// Per-module SDK, language level, output paths and dependency overrides, keyed by module relative path (`"."` for root).
|
||||
pub modules: BTreeMap<String, ModuleStructureSettings>,
|
||||
/// Project-level libraries (`JAR`s / class folders / source archives).
|
||||
pub libraries: Vec<ProjectLibrary>,
|
||||
/// Module framework facets (`web`, `spring`, `jpa`).
|
||||
pub facets: Vec<FacetConfig>,
|
||||
/// Packaging artifacts (`jar`, `war`, `warExploded`).
|
||||
pub artifacts: Vec<ArtifactConfig>,
|
||||
}
|
||||
|
||||
impl ProjectStructureSettings {
|
||||
/// Overrides belong to the module's full path, never just its directory name.
|
||||
pub fn module_settings(
|
||||
&self,
|
||||
root: &std::path::Path,
|
||||
module: &std::path::Path,
|
||||
) -> Option<&ModuleStructureSettings> {
|
||||
self.modules.iter().find_map(|(key, settings)| (root.join(key) == module).then_some(settings))
|
||||
}
|
||||
|
||||
/// The "Exclude files" name patterns.
|
||||
pub fn exclude_file_patterns(&self) -> Vec<String> {
|
||||
self.exclude_files.split(';').map(str::trim).filter(|p| !p.is_empty()).map(str::to_owned).collect()
|
||||
@@ -1128,12 +1267,81 @@ mod tests {
|
||||
assert_eq!(s.file_excludes(), vec!["*.log", "tmp*"]);
|
||||
assert!(Settings::default().files.file_types.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_structure_modules_libraries_facets_and_artifacts_round_trip() {
|
||||
let old: Settings = serde_json::from_str(r#"{"projectStructure":{"sourceRoots":["src"]}}"#).unwrap();
|
||||
assert!(old.project_structure.compiler_output.is_empty());
|
||||
assert!(old.project_structure.modules.is_empty());
|
||||
assert!(old.project_structure.libraries.is_empty());
|
||||
assert!(old.project_structure.facets.is_empty());
|
||||
assert!(old.project_structure.artifacts.is_empty());
|
||||
assert!(old.languages.java.language_level.is_empty());
|
||||
|
||||
let mut settings = Settings::default();
|
||||
settings.languages.java.language_level = "21".into();
|
||||
settings.project_structure.compiler_output = "out/production".into();
|
||||
settings.project_structure.modules.insert(
|
||||
"backend".into(),
|
||||
ModuleStructureSettings {
|
||||
jdk: "/opt/jdk-21".into(),
|
||||
language_level: "21".into(),
|
||||
compiler_output: "backend/target/classes".into(),
|
||||
test_compiler_output: "backend/target/test-classes".into(),
|
||||
dependencies: vec![ModuleDependency {
|
||||
kind: "library".into(),
|
||||
target: "custom-lib".into(),
|
||||
scope: DependencyScope::Compile,
|
||||
exported: true,
|
||||
}],
|
||||
},
|
||||
);
|
||||
settings.project_structure.libraries.push(ProjectLibrary {
|
||||
name: "custom-lib".into(),
|
||||
classes: vec!["lib/custom.jar".into()],
|
||||
sources: vec!["lib/custom-sources.jar".into()],
|
||||
javadocs: Vec::new(),
|
||||
scope: DependencyScope::Compile,
|
||||
});
|
||||
settings.project_structure.facets.push(FacetConfig {
|
||||
kind: "web".into(),
|
||||
module: "backend".into(),
|
||||
descriptor: "src/main/webapp/WEB-INF/web.xml".into(),
|
||||
web_root: "src/main/webapp".into(),
|
||||
});
|
||||
settings.project_structure.artifacts.push(ArtifactConfig {
|
||||
name: "backend:war exploded".into(),
|
||||
kind: ArtifactKind::WarExploded,
|
||||
module: "backend".into(),
|
||||
output_directory: "out/artifacts/backend_war_exploded".into(),
|
||||
main_class: String::new(),
|
||||
include_libraries: vec!["custom-lib".into()],
|
||||
});
|
||||
|
||||
let value = serde_json::to_value(&settings).unwrap();
|
||||
assert_eq!(value["languages"]["java"]["languageLevel"], "21");
|
||||
assert_eq!(value["projectStructure"]["compilerOutput"], "out/production");
|
||||
assert_eq!(value["projectStructure"]["artifacts"][0]["kind"], "warExploded");
|
||||
let restored: Settings = serde_json::from_value(value).unwrap();
|
||||
assert_eq!(restored, settings);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod maven_linkage_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn maven_runner_jre_defaults_and_round_trips() {
|
||||
let old: MavenSettings = serde_json::from_str(r#"{"home":"/opt/maven"}"#).unwrap();
|
||||
assert!(old.runner_jre.is_empty());
|
||||
assert!(MavenSettings::default().runner_jre.is_empty());
|
||||
let settings = MavenSettings { runner_jre: "/opt/jdk-21".into(), ..old };
|
||||
let encoded = serde_json::to_string(&settings).unwrap();
|
||||
assert!(encoded.contains(r#""runnerJre":"/opt/jdk-21""#));
|
||||
assert_eq!(serde_json::from_str::<MavenSettings>(&encoded).unwrap(), settings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_linkage_defaults_and_round_trips() {
|
||||
let old: MavenSettings = serde_json::from_str(r#"{"home":"/opt/maven"}"#).unwrap();
|
||||
@@ -1155,6 +1363,41 @@ mod maven_linkage_tests {
|
||||
assert!(encoded.contains("\"daemon\":true") && encoded.contains("mvndHome"));
|
||||
assert_eq!(serde_json::from_str::<MavenSettings>(&encoded).unwrap(), settings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_count_takes_counts_and_core_multipliers_only() {
|
||||
let threads = |t: &str| {
|
||||
let m = MavenSettings { threads: t.into(), ..Default::default() };
|
||||
m.thread_count().map(str::to_owned)
|
||||
};
|
||||
// Empty = Maven's default (one thread per module).
|
||||
assert_eq!(threads("").as_deref(), None);
|
||||
assert_eq!(threads(" ").as_deref(), None);
|
||||
// A thread count, and a core multiplier whose fraction may be decimal.
|
||||
assert_eq!(threads("4").as_deref(), Some("4"));
|
||||
assert_eq!(threads(" 2 ").as_deref(), Some("2"));
|
||||
assert_eq!(threads("1C").as_deref(), Some("1C"));
|
||||
assert_eq!(threads("2.0C").as_deref(), Some("2.0C"));
|
||||
assert_eq!(threads("0.5C").as_deref(), Some("0.5C"));
|
||||
// Everything else a `-T` would make every Maven run reject is dropped.
|
||||
assert_eq!(threads("abc").as_deref(), None);
|
||||
assert_eq!(threads("4x").as_deref(), None);
|
||||
assert_eq!(threads("0").as_deref(), None);
|
||||
assert_eq!(threads("-4").as_deref(), None);
|
||||
assert_eq!(threads("1e3").as_deref(), None);
|
||||
assert_eq!(threads("2..5C").as_deref(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_count_round_trips_and_defaults_to_empty() {
|
||||
// Old settings files predate the thread count; `serde(default)` keeps them loadable.
|
||||
let old: MavenSettings = serde_json::from_str(r#"{"home":"/opt/maven"}"#).unwrap();
|
||||
assert!(old.threads.is_empty() && old.thread_count().is_none());
|
||||
let settings = MavenSettings { threads: "2C".into(), ..old };
|
||||
let encoded = serde_json::to_string(&settings).unwrap();
|
||||
assert!(encoded.contains("\"threads\":\"2C\""));
|
||||
assert_eq!(serde_json::from_str::<MavenSettings>(&encoded).unwrap(), settings);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -113,6 +113,8 @@ pub struct CommitSettings {
|
||||
pub body_limit: u32,
|
||||
pub show_right_margin: bool,
|
||||
pub wrap_at_margin: bool,
|
||||
/// Plugin before-commit checks turned off (`<plugin id>/<check id>`); the rest run.
|
||||
pub disabled_plugin_checks: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for CommitSettings {
|
||||
@@ -132,6 +134,7 @@ impl Default for CommitSettings {
|
||||
body_limit: 72,
|
||||
show_right_margin: true,
|
||||
wrap_at_margin: false,
|
||||
disabled_plugin_checks: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
futures.workspace = true
|
||||
tempfile.workspace = true
|
||||
ide-core.workspace = true
|
||||
ide-language.workspace = true
|
||||
@@ -19,6 +20,9 @@ memchr = "2"
|
||||
portable-pty.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
tracing-subscriber.workspace = true
|
||||
tokio = { workspace = true, features = ["net", "rt-multi-thread", "macros"] }
|
||||
@@ -196,10 +196,18 @@ fn managed_dirs(root: &Path) -> Vec<PathBuf> {
|
||||
dirs
|
||||
}
|
||||
|
||||
/// The `PATH` an adapter runs with, unless its launch sets one: the search path language servers
|
||||
/// get, so what it starts in turn (js-debug's wrapper runs `node`, Delve runs `go build`) is
|
||||
/// found like Run finds it, even when the login shell's `PATH` didn't reach the app.
|
||||
fn adapter_path(env: &[(String, String)]) -> Option<std::ffi::OsString> {
|
||||
let own = env.iter().any(|(k, _)| if cfg!(windows) { k.eq_ignore_ascii_case("PATH") } else { k == "PATH" });
|
||||
(!own).then(ide_core::tool_path::search_path)
|
||||
}
|
||||
|
||||
/// Directories searched for adapter binaries: managed tools first, then `PATH` and the usual install spots.
|
||||
fn search_dirs() -> Vec<PathBuf> {
|
||||
let mut dirs: Vec<PathBuf> = tools_root().map(|r| managed_dirs(&r)).unwrap_or_default();
|
||||
dirs.extend(std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect::<Vec<_>>()).unwrap_or_default());
|
||||
dirs.extend(std::env::split_paths(&ide_core::tool_path::search_path()));
|
||||
if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
|
||||
for rel in [".cargo/bin", ".local/bin", "go/bin", ".dotnet/tools", ".bun/bin", ".npm-global/bin", ".volta/bin"]
|
||||
{
|
||||
@@ -464,6 +472,9 @@ impl AdapterLauncher for ProcessLauncher {
|
||||
None => args,
|
||||
};
|
||||
let mut cmd = Command::new(&binary);
|
||||
if let Some(path) = adapter_path(&spec.env) {
|
||||
cmd.env("PATH", path);
|
||||
}
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
cmd.args(&args)
|
||||
.envs(spec.env.iter().map(|(k, v)| (k, v)))
|
||||
@@ -592,6 +603,21 @@ async fn connect_with_retries(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn adapters_run_on_the_tool_search_path() {
|
||||
let search = ide_core::tool_path::search_path();
|
||||
assert_eq!(adapter_path(&[]), Some(search.clone()));
|
||||
assert_eq!(adapter_path(&[("GOFLAGS".into(), "-mod=mod".into())]), Some(search));
|
||||
// A launch that sets its own (a selected Go SDK's bin first) keeps it.
|
||||
assert_eq!(adapter_path(&[("PATH".into(), "/sdk/go/bin:/usr/bin".into())]), None);
|
||||
// The search path reaches the usual install spots even when this process's `PATH` doesn't.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let dirs: Vec<PathBuf> = std::env::split_paths(&ide_core::tool_path::search_path()).collect();
|
||||
assert!(dirs.contains(&PathBuf::from("/usr/local/bin")), "{dirs:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn program_output_is_forwarded_without_the_adapter_banner() {
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
|
||||
+166
-27
@@ -19,6 +19,7 @@ mod session;
|
||||
|
||||
use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
use connection::{Connection, DapError};
|
||||
use futures::future::join_all;
|
||||
use ide_core::{DebugSessionId, IdeError, IdeResult, SharedSink};
|
||||
use ide_language::LanguageRegistry;
|
||||
use parking_lot::Mutex;
|
||||
@@ -300,6 +301,8 @@ pub struct DebugManager {
|
||||
exception_choices: Mutex<BTreeMap<String, bool>>,
|
||||
function_breakpoints: Mutex<Vec<FunctionBreakpoint>>,
|
||||
data_breakpoints: Mutex<Vec<DataBreakpoint>>,
|
||||
/// In-flight stops, by session: a second Stop sets `stop_force`, the waiting one kills.
|
||||
stopping: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
|
||||
}
|
||||
|
||||
/// Whether the debugged project depends on the Flutter SDK, so it must go
|
||||
@@ -510,6 +513,18 @@ pub(crate) fn capabilities_from(caps: &Value) -> DebugCapabilities {
|
||||
}
|
||||
}
|
||||
|
||||
/// States of a file's line breakpoints that no session has been sent.
|
||||
fn unsent(breakpoints: &[Breakpoint]) -> Vec<BreakpointState> {
|
||||
breakpoints
|
||||
.iter()
|
||||
.map(|b| BreakpointState {
|
||||
line: b.line,
|
||||
verified: false,
|
||||
message: (!b.enabled).then(|| "Disabled".to_owned()),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// States for breakpoints no session has verified yet.
|
||||
fn unverified(enabled: impl Iterator<Item = bool>) -> Vec<BreakpointState> {
|
||||
enabled
|
||||
@@ -517,6 +532,34 @@ fn unverified(enabled: impl Iterator<Item = bool>) -> Vec<BreakpointState> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Delve compiles the debuggee to `__debug_bin` in the session's cwd (on Windows
|
||||
/// `__debug_bin.exe` plus `__debug_bin.exe<digits>` in DAP mode) and removes it on a
|
||||
/// graceful exit — a shutdown it doesn't always reach, so the files pile up. Sweep
|
||||
/// the leftovers once the session is down. Runs after `session_closed`, so Delve
|
||||
/// has already exited or been killed and holds no file locks; a leftover of a
|
||||
/// still-building run is removed on that run's own shutdown.
|
||||
fn remove_delve_binaries(cwd: &Path) {
|
||||
let Ok(entries) = std::fs::read_dir(cwd) else { return };
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name();
|
||||
let Some(name) = name.to_str() else { continue };
|
||||
// Windows writes `__debug_bin.exe` (and `.exe<digits>` in DAP mode); other
|
||||
// platforms keep the bare name. Suffixes like `.go` are user files.
|
||||
let suffix = name.strip_prefix("__debug_bin");
|
||||
let leftover = suffix.is_some_and(|s| {
|
||||
s.is_empty()
|
||||
|| s == ".exe"
|
||||
|| (s.starts_with(".exe") && s[".exe".len()..].chars().all(|c| c.is_ascii_digit()))
|
||||
});
|
||||
if leftover
|
||||
&& entry.file_type().is_ok_and(|t| t.is_file())
|
||||
&& let Err(e) = std::fs::remove_file(entry.path())
|
||||
{
|
||||
tracing::debug!("could not remove Delve leftover {}: {e}", entry.path().display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn variable_from(v: &Value) -> Variable {
|
||||
let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_owned);
|
||||
Variable {
|
||||
@@ -546,6 +589,7 @@ impl DebugManager {
|
||||
exception_choices: Mutex::default(),
|
||||
function_breakpoints: Mutex::default(),
|
||||
data_breakpoints: Mutex::default(),
|
||||
stopping: Mutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -877,12 +921,20 @@ impl DebugManager {
|
||||
let _ = tokio::time::timeout(INIT_TIMEOUT, initialized.wait_for(|v| *v)).await;
|
||||
}
|
||||
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> =
|
||||
self.breakpoints.lock().iter().map(|(p, b)| (p.clone(), b.clone())).collect();
|
||||
// A fresh adapter has no breakpoints, so a file with none enabled needs no request; the
|
||||
// others go out together, as VS Code sends them, instead of one round trip per file.
|
||||
let (files, idle): (Vec<_>, Vec<_>) = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|(p, b)| (p.clone(), b.clone()))
|
||||
.partition(|(_, b)| b.iter().any(|b| b.enabled));
|
||||
let sent = join_all(files.iter().map(|(path, bps)| s.send_breakpoints(path, bps, None))).await;
|
||||
// Breakpoint states follow the owner's first session.
|
||||
let first = self.live_sessions().into_iter().find(|f| f.owner.key == s.owner.key).map(|f| f.id) == Some(s.id);
|
||||
for (path, bps) in files {
|
||||
match s.send_breakpoints(&path, &bps, None).await {
|
||||
let idle = idle.into_iter().map(|(path, bps)| (path, Ok(unsent(&bps))));
|
||||
for (path, result) in files.into_iter().map(|(path, _)| path).zip(sent).chain(idle) {
|
||||
match result {
|
||||
Ok(states) => {
|
||||
if first {
|
||||
self.states.lock().insert(path.clone(), states);
|
||||
@@ -945,21 +997,72 @@ impl DebugManager {
|
||||
|
||||
/// Ends a session: `terminate` (when asked and supported) → `disconnect` → kill.
|
||||
pub(crate) async fn shutdown(&self, s: &Arc<Session>, terminate: bool) {
|
||||
// java-debug runs the program itself and pipes its stdout over DAP. A `disconnect`
|
||||
// ends that DAP session, so every line the program writes while shutting down is lost.
|
||||
// Ask the program to exit ourselves and keep the adapter attached until it has drained
|
||||
// the console (`terminated`), as IDEA does with the process it owns.
|
||||
let pid = s.debuggee_pid.load(Ordering::Acquire);
|
||||
let own_terminate = terminate && s.request == "launch" && pid > 0;
|
||||
let graceful = terminate && s.request == "launch" && s.supports("supportsTerminateRequest");
|
||||
if !s.conn.is_closed() {
|
||||
if terminate && s.request == "launch" && s.supports("supportsTerminateRequest") {
|
||||
if graceful {
|
||||
let _ = s.conn.request_timeout("terminate", json!({ "restart": false }), SHUTDOWN_TIMEOUT).await;
|
||||
}
|
||||
if !graceful && !own_terminate {
|
||||
let _ = s
|
||||
.conn
|
||||
.request_timeout(
|
||||
"disconnect",
|
||||
json!({ "restart": false, "terminateDebuggee": s.request == "launch" }),
|
||||
SHUTDOWN_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
if own_terminate && !graceful {
|
||||
// Signal before anything else: waiting on a request the adapter may not answer
|
||||
// would delay the shutdown the console is supposed to show.
|
||||
crate::session::signal_debuggee(s, false);
|
||||
}
|
||||
if graceful {
|
||||
// java-debug sends `terminated` only after it has drained the program's console
|
||||
// (it waits up to 5 s for the output pump). Close on the process id alone and the
|
||||
// last shutdown lines are dropped, so wait for that event here.
|
||||
let deadline = std::time::Instant::now() + crate::session::DEBUGGEE_EXIT_WAIT;
|
||||
while !s.terminated.load(Ordering::Acquire) && std::time::Instant::now() < deadline {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
// An adapter answers `disconnect` before the program it launched has exited, and that
|
||||
// program keeps its port until it is gone. Reporting the session as terminated then
|
||||
// lets Run start again into an occupied port, so wait for the program first — with the
|
||||
// connection still open, so a second Stop can find the session and kill it.
|
||||
crate::session::wait_for_debuggee(s, terminate).await;
|
||||
if terminate && s.request == "launch" {
|
||||
// The adapter reports `terminated` only after it has drained the program's console
|
||||
// (java-debug waits up to 5 s for the pump): closing before that drops the last
|
||||
// shutdown lines from the console.
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(6);
|
||||
while !s.terminated.load(Ordering::Acquire) && !s.conn.is_closed() && std::time::Instant::now() < deadline {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
if graceful && !s.conn.is_closed() {
|
||||
let _ = s
|
||||
.conn
|
||||
.request_timeout(
|
||||
"disconnect",
|
||||
json!({ "restart": false, "terminateDebuggee": s.request == "launch" }),
|
||||
json!({ "restart": false, "terminateDebuggee": false }),
|
||||
SHUTDOWN_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
s.conn.close();
|
||||
self.session_closed(s);
|
||||
if s.adapter == "delve" && s.spec.server_host.is_none() {
|
||||
let cwd = s.spec.cwd.clone();
|
||||
tokio::task::spawn_blocking(move || remove_delve_binaries(&cwd));
|
||||
}
|
||||
}
|
||||
|
||||
/// Breakpoints are kept per file even without a session and sent on start.
|
||||
@@ -990,16 +1093,7 @@ impl DebugManager {
|
||||
Err(e) => tracing::debug!("setBreakpoints on session {} failed: {e}", s.id.0),
|
||||
}
|
||||
}
|
||||
let states = result.unwrap_or_else(|| {
|
||||
breakpoints
|
||||
.iter()
|
||||
.map(|b| BreakpointState {
|
||||
line: b.line,
|
||||
verified: false,
|
||||
message: (!b.enabled).then(|| "Disabled".to_owned()),
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
let states = result.unwrap_or_else(|| unsent(&breakpoints));
|
||||
self.states.lock().insert(path, states.clone());
|
||||
Ok(states)
|
||||
}
|
||||
@@ -1327,13 +1421,26 @@ impl DebugManager {
|
||||
/// Sends empty breakpoint lists (line, function, data) to `session` until its next
|
||||
/// stop, when the stored ones are restored. `except` is left to the caller.
|
||||
async fn suspend_breakpoints(&self, session: &Arc<Session>, except: Option<&Path>) -> IdeResult<()> {
|
||||
let files: Vec<PathBuf> = self.breakpoints.lock().keys().cloned().collect();
|
||||
for path in files {
|
||||
if Some(path.as_path()) == except {
|
||||
continue;
|
||||
// While paused the adapter holds the stored lists: only files with something enabled change.
|
||||
let files: Vec<PathBuf> = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
let sent = join_all(files.iter().map(|path| session.send_breakpoints(path, &[], None))).await;
|
||||
let mut failed = None;
|
||||
for (path, result) in files.into_iter().zip(sent) {
|
||||
match result {
|
||||
Ok(_) => {
|
||||
session.pending_restore.lock().files.insert(path);
|
||||
}
|
||||
Err(e) => failed = failed.or(Some(e)),
|
||||
}
|
||||
session.send_breakpoints(&path, &[], None).await?;
|
||||
session.pending_restore.lock().files.insert(path);
|
||||
}
|
||||
if let Some(e) = failed {
|
||||
return Err(e.into());
|
||||
}
|
||||
if !self.function_breakpoints.lock().is_empty() && session.supports("supportsFunctionBreakpoints") {
|
||||
session.send_function_breakpoints(&[]).await?;
|
||||
@@ -1349,9 +1456,11 @@ impl DebugManager {
|
||||
/// Re-sends what [`suspend_breakpoints`](Self::suspend_breakpoints) / run to cursor replaced.
|
||||
pub(crate) async fn restore_breakpoints(&self, session: &Arc<Session>) {
|
||||
let pending = std::mem::take(&mut *session.pending_restore.lock());
|
||||
for path in pending.files {
|
||||
let bps = self.stored_breakpoints(&path);
|
||||
if let Err(e) = session.send_breakpoints(&path, &bps, None).await {
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> =
|
||||
pending.files.into_iter().map(|path| (path.clone(), self.stored_breakpoints(&path))).collect();
|
||||
let sent = join_all(files.iter().map(|(path, bps)| session.send_breakpoints(path, bps, None))).await;
|
||||
for ((path, _), result) in files.iter().zip(sent) {
|
||||
if let Err(e) = result {
|
||||
tracing::debug!("restoring breakpoints of {} failed: {e}", path.display());
|
||||
}
|
||||
}
|
||||
@@ -1518,10 +1627,40 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops a session and its child sessions.
|
||||
/// Stops every debug session started from `root` or below — closing a project stops the
|
||||
/// programs it launched even when the session's owner key does not name the window doing
|
||||
/// the closing (window groups, auxiliary windows).
|
||||
pub async fn stop_under(&self, root: &Path) {
|
||||
let ids: Vec<DebugSessionId> =
|
||||
self.live_sessions().into_iter().filter(|s| s.spec.cwd.starts_with(root)).map(|s| s.id).collect();
|
||||
tracing::info!(root = %root.display(), sessions = ids.len(), "closing project: stopping debug sessions");
|
||||
for id in ids {
|
||||
if let Err(e) = self.stop(id).await {
|
||||
tracing::debug!("debug session {id:?} did not stop: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops a session and its child sessions. A second Stop while the first one waits kills
|
||||
/// the program instead of waiting for it — even after the adapter dropped the session.
|
||||
pub async fn stop(&self, s: DebugSessionId) -> IdeResult<()> {
|
||||
{
|
||||
let in_flight = self.stopping.lock();
|
||||
if let Some(session) = in_flight.get(&s) {
|
||||
session.stop_force.store(true, Ordering::Release);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let session = self.session(s)?;
|
||||
let children: Vec<Arc<Session>> = self.live_sessions().into_iter().filter(|c| c.parent == Some(s)).collect();
|
||||
self.stopping.lock().insert(s, session.clone());
|
||||
let result = self.stop_tree(session).await;
|
||||
self.stopping.lock().remove(&s);
|
||||
result
|
||||
}
|
||||
|
||||
async fn stop_tree(&self, session: Arc<Session>) -> IdeResult<()> {
|
||||
let children: Vec<Arc<Session>> =
|
||||
self.live_sessions().into_iter().filter(|c| c.parent == Some(session.id)).collect();
|
||||
for child in children {
|
||||
self.shutdown(&child, true).await;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncRead, AsyncReadExt};
|
||||
use tokio::process::Child;
|
||||
@@ -49,6 +49,14 @@ pub(crate) struct Session {
|
||||
pub configured: AtomicBool,
|
||||
pub initialized: watch::Sender<bool>,
|
||||
pub terminated: AtomicBool,
|
||||
/// Set by a second Stop: the one waiting for the program kills it instead.
|
||||
pub stop_force: AtomicBool,
|
||||
/// `systemProcessId` from the adapter's `process` event: the program being debugged.
|
||||
pub debuggee_pid: AtomicI64,
|
||||
/// Pids signalled for the current stop: the reported pid and everything it started (an
|
||||
/// adapter may report the launcher shell, whose child is the program).
|
||||
#[cfg_attr(not(unix), allow(dead_code))]
|
||||
pub stop_pids: parking_lot::Mutex<Vec<i32>>,
|
||||
/// Breakpoints replaced for run to cursor / force stepping, restored on the next stop.
|
||||
pub pending_restore: Mutex<PendingRestore>,
|
||||
/// Adapter breakpoint id → (file, index in the stored list).
|
||||
@@ -96,6 +104,9 @@ impl Session {
|
||||
configured: AtomicBool::new(false),
|
||||
initialized: watch::channel(false).0,
|
||||
terminated: AtomicBool::new(false),
|
||||
stop_force: AtomicBool::new(false),
|
||||
debuggee_pid: AtomicI64::new(0),
|
||||
stop_pids: parking_lot::Mutex::new(Vec::new()),
|
||||
pending_restore: Mutex::default(),
|
||||
breakpoint_ids: Mutex::new(HashMap::new()),
|
||||
resolved_paths: Mutex::new(HashMap::new()),
|
||||
@@ -275,6 +286,108 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// How long Stop waits for a launched program to exit before reporting the session ended.
|
||||
pub(crate) const DEBUGGEE_EXIT_WAIT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// The program and everything it started: an adapter may report the launcher shell, whose
|
||||
/// child is the debugged program, so stopping only the reported pid leaves the program alive.
|
||||
#[cfg(unix)]
|
||||
fn process_tree(pid: i32) -> Vec<i32> {
|
||||
use std::collections::HashMap;
|
||||
let Ok(out) = std::process::Command::new("ps").args(["-A", "-o", "pid=,ppid="]).output() else {
|
||||
return vec![pid];
|
||||
};
|
||||
let mut children: HashMap<i32, Vec<i32>> = HashMap::new();
|
||||
for line in String::from_utf8_lossy(&out.stdout).lines() {
|
||||
let mut it = line.split_whitespace();
|
||||
let (Some(p), Some(parent)) = (it.next(), it.next()) else { continue };
|
||||
let (Ok(p), Ok(parent)) = (p.parse::<i32>(), parent.parse::<i32>()) else { continue };
|
||||
children.entry(parent).or_default().push(p);
|
||||
}
|
||||
let mut tree = vec![pid];
|
||||
let mut at = 0;
|
||||
while at < tree.len() {
|
||||
if let Some(kids) = children.get(&tree[at]) {
|
||||
tree.extend(kids.iter().copied());
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
tree
|
||||
}
|
||||
|
||||
/// Asks the program itself to exit (`force` = SIGKILL) without ending the adapter session:
|
||||
/// its output keeps flowing over DAP while it shuts down. The first call remembers the pid
|
||||
/// tree, because the reported pid may die before its program does.
|
||||
pub(crate) fn signal_debuggee(s: &Arc<Session>, force: bool) {
|
||||
let pid = s.debuggee_pid.load(Ordering::Acquire);
|
||||
if pid <= 0 {
|
||||
return;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let mut known = s.stop_pids.lock();
|
||||
if known.is_empty() {
|
||||
*known = process_tree(pid as i32);
|
||||
}
|
||||
let signal = if force { libc::SIGKILL } else { libc::SIGTERM };
|
||||
// Children first: the shell that started the program would otherwise reparent it.
|
||||
for p in known.iter().rev() {
|
||||
// SAFETY: plain syscall on the processes this session started.
|
||||
unsafe {
|
||||
libc::kill(*p, signal);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let mut cmd = std::process::Command::new("taskkill");
|
||||
cmd.args(["/PID", &pid.to_string(), "/T"]);
|
||||
if force {
|
||||
cmd.arg("/F");
|
||||
}
|
||||
let _ = cmd.status();
|
||||
}
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
let _ = (pid, force);
|
||||
}
|
||||
|
||||
/// Waits until the program a `launch` session started is gone; a second Stop kills it.
|
||||
pub(crate) async fn wait_for_debuggee(s: &Arc<Session>, terminate: bool) {
|
||||
if !terminate || s.request != "launch" {
|
||||
return;
|
||||
}
|
||||
let pid = s.debuggee_pid.load(Ordering::Acquire);
|
||||
if pid <= 0 {
|
||||
return;
|
||||
}
|
||||
tracing::info!(session = s.id.0, pid, "stop: waiting for the debugged program to exit");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::time::Instant;
|
||||
let targets = {
|
||||
let known = s.stop_pids.lock();
|
||||
if known.is_empty() { process_tree(pid as i32) } else { known.clone() }
|
||||
};
|
||||
let alive = || targets.iter().any(|p| unsafe { libc::kill(*p, 0) } == 0);
|
||||
let deadline = Instant::now() + DEBUGGEE_EXIT_WAIT;
|
||||
while alive() {
|
||||
if s.stop_force.swap(false, Ordering::AcqRel) {
|
||||
signal_debuggee(s, true);
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
// The program ignored the terminate: do not leave it running.
|
||||
signal_debuggee(s, true);
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = pid;
|
||||
}
|
||||
}
|
||||
|
||||
// java-debug and Windows netcoredbg need native separators for source lookup.
|
||||
// Keep DAP path mode, but normalize Windows drive and UNC paths.
|
||||
fn is_windows_source_path(path: &str) -> bool {
|
||||
@@ -370,8 +483,18 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
|
||||
return;
|
||||
}
|
||||
let output = str_("output").unwrap_or_default();
|
||||
if tracing::enabled!(tracing::Level::DEBUG) && mgr.stopping.lock().contains_key(&s.id) {
|
||||
tracing::debug!(session = ?s.id, bytes = output.len(), "output during stop");
|
||||
}
|
||||
s.emit(DebugEvent::Output { category, output });
|
||||
}
|
||||
// The program the adapter started: Stop must wait for it, not for the adapter's reply.
|
||||
// `process` is the DAP event; java-debug announces the same thing as `processid`.
|
||||
"process" | "processid" => {
|
||||
if let Some(pid) = int("systemProcessId").or_else(|| int("processId")).filter(|p| *p > 0) {
|
||||
s.debuggee_pid.store(pid, Ordering::Release);
|
||||
}
|
||||
}
|
||||
"thread" => s.emit(DebugEvent::Thread {
|
||||
thread_id: int("threadId").unwrap_or(0),
|
||||
started: body.get("reason").and_then(Value::as_str) != Some("exited"),
|
||||
@@ -390,12 +513,18 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
|
||||
}
|
||||
"exited" => {}
|
||||
"terminated" => {
|
||||
if !s.terminated.swap(true, Ordering::AcqRel) {
|
||||
s.emit(DebugEvent::Terminated);
|
||||
}
|
||||
let first = !s.terminated.swap(true, Ordering::AcqRel);
|
||||
let mgr = mgr.clone();
|
||||
let s = s.clone();
|
||||
tokio::spawn(async move { mgr.shutdown(&s, false).await });
|
||||
// Waiting here would stop reading the adapter: it keeps sending the program's last
|
||||
// output while the program exits. Wait off the reader task, then report the end.
|
||||
tokio::spawn(async move {
|
||||
if first {
|
||||
wait_for_debuggee(&s, true).await;
|
||||
s.emit(DebugEvent::Terminated);
|
||||
}
|
||||
mgr.shutdown(&s, false).await;
|
||||
});
|
||||
}
|
||||
"capabilities" => {
|
||||
if let Some(new) = body.get("capabilities").and_then(Value::as_object) {
|
||||
|
||||
+299
-10
@@ -5,11 +5,16 @@ use crate::adapter::{AdapterIo, LaunchFuture};
|
||||
use ide_core::IdeEvent;
|
||||
use ide_core::event::DebugEvent;
|
||||
use ide_jsonrpc::framing;
|
||||
#[cfg(unix)]
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
#[cfg(unix)]
|
||||
use std::time::Instant;
|
||||
use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
|
||||
|
||||
type Log = Arc<Mutex<Vec<Value>>>;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
#[derive(Clone)]
|
||||
struct Script {
|
||||
/// Send a `runInTerminal` reverse request when `launch` arrives.
|
||||
run_in_terminal: Option<Vec<String>>,
|
||||
@@ -17,6 +22,33 @@ struct Script {
|
||||
start_debugging: bool,
|
||||
ignore_configuration_done: bool,
|
||||
source_path: Option<String>,
|
||||
/// Report this process id in the adapter's `process` event (the program being debugged).
|
||||
debuggee_pid: Option<u32>,
|
||||
/// java-debug's spelling of the same event.
|
||||
java_process_id: bool,
|
||||
/// Send one more output event right after the `terminated` event (a program still logging
|
||||
/// while it shuts down).
|
||||
output_after_terminate: bool,
|
||||
/// Advertise `supportsTerminateRequest` (java-debug does not, so Stop signals the program).
|
||||
supports_terminate: bool,
|
||||
/// Answer `setBreakpoints` only once this many are waiting (a client that waits for each never gets one).
|
||||
hold_set_breakpoints: usize,
|
||||
}
|
||||
|
||||
impl Default for Script {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
run_in_terminal: None,
|
||||
start_debugging: false,
|
||||
ignore_configuration_done: false,
|
||||
source_path: None,
|
||||
debuggee_pid: None,
|
||||
java_process_id: false,
|
||||
output_after_terminate: false,
|
||||
supports_terminate: true,
|
||||
hold_set_breakpoints: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct FakeLauncher {
|
||||
@@ -49,6 +81,7 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
let mut r = BufReader::new(r);
|
||||
let mut seq = 1000;
|
||||
let mut pending_launch: Option<i64> = None;
|
||||
let mut held: Vec<Value> = Vec::new();
|
||||
macro_rules! send {
|
||||
($v:expr) => {{
|
||||
let mut v: Value = $v;
|
||||
@@ -74,7 +107,7 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
json!({
|
||||
"supportsConfigurationDoneRequest": true,
|
||||
"supportsCompletionsRequest": true,
|
||||
"supportsTerminateRequest": true,
|
||||
"supportsTerminateRequest": script.supports_terminate,
|
||||
"supportsSetVariable": true,
|
||||
"supportsFunctionBreakpoints": true,
|
||||
"supportsDataBreakpoints": true,
|
||||
@@ -101,14 +134,20 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
send!(json!({"type": "event", "event": "initialized"}));
|
||||
}
|
||||
"setBreakpoints" => {
|
||||
let bps: Vec<Value> = msg["arguments"]["breakpoints"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, b)| json!({"id": i + 1, "verified": true, "line": b["line"]}))
|
||||
.collect();
|
||||
ok!(msg, json!({"breakpoints": bps}));
|
||||
held.push(msg);
|
||||
if held.len() < script.hold_set_breakpoints {
|
||||
continue;
|
||||
}
|
||||
for msg in std::mem::take(&mut held) {
|
||||
let bps: Vec<Value> = msg["arguments"]["breakpoints"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, b)| json!({"id": i + 1, "verified": true, "line": b["line"]}))
|
||||
.collect();
|
||||
ok!(msg, json!({"breakpoints": bps}));
|
||||
}
|
||||
}
|
||||
"setExceptionBreakpoints" => ok!(msg, json!({})),
|
||||
"setFunctionBreakpoints" | "setDataBreakpoints" => {
|
||||
@@ -146,6 +185,14 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
if let Some(l) = pending_launch.take() {
|
||||
send!(json!({"type": "response", "request_seq": l, "command": "launch", "success": true}));
|
||||
}
|
||||
if let Some(pid) = script.debuggee_pid {
|
||||
let event = if script.java_process_id {
|
||||
json!({"type": "event", "event": "processid", "body": {"processId": pid, "shellProcessId": pid}})
|
||||
} else {
|
||||
json!({"type": "event", "event": "process", "body": {"name": "prog", "systemProcessId": pid}})
|
||||
};
|
||||
send!(event);
|
||||
}
|
||||
send!(json!({"type": "event", "event": "output", "body": {"category": "stdout", "output": "hello\n"}}));
|
||||
send!(
|
||||
json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1, "allThreadsStopped": true}})
|
||||
@@ -199,6 +246,11 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
"terminate" => {
|
||||
ok!(msg, Value::Null);
|
||||
send!(json!({"type": "event", "event": "terminated"}));
|
||||
if script.output_after_terminate {
|
||||
send!(
|
||||
json!({"type": "event", "event": "output", "body": {"category": "stdout", "output": "late\n"}})
|
||||
);
|
||||
}
|
||||
}
|
||||
"disconnect" => {
|
||||
ok!(msg, Value::Null);
|
||||
@@ -921,6 +973,7 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
|
||||
let b = PathBuf::from("/p/b.py");
|
||||
h.manager.set_breakpoints(a.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(b.clone(), vec![bp(3)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
h.manager.set_function_breakpoints(vec![function_bp("run", true)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
@@ -949,6 +1002,24 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
|
||||
h.manager.run_to(id, 1, a.clone(), 9, true).await.unwrap();
|
||||
assert_eq!(sent_for("/p/a.py").last().unwrap(), &json!([{"line": 10}]));
|
||||
assert_eq!(sent_for("/p/b.py").last().unwrap(), &json!([]));
|
||||
assert!(sent_for("/p/off.py").is_empty(), "nothing enabled there, nothing to suspend or restore");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled() {
|
||||
let h = harness(Script { hold_set_breakpoints: 2, ..Script::default() });
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
|
||||
let off = PathBuf::from("/p/off.py");
|
||||
h.manager.set_breakpoints(off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
// Waiting for each answer before the next request would stall until the request timeout.
|
||||
tokio::time::timeout(Duration::from_secs(5), h.start(config())).await.expect("requests pipelined").unwrap();
|
||||
let paths: Vec<Value> = requests(&h, "setBreakpoints").into_iter().map(|r| r["source"]["path"].clone()).collect();
|
||||
assert_eq!(paths, [json!("/p/a.py"), json!("/p/b.py")]);
|
||||
assert_eq!(
|
||||
h.manager.breakpoint_states(&off),
|
||||
[BreakpointState { line: 5, verified: false, message: Some("Disabled".into()) }]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1319,3 +1390,221 @@ fn flutter_projects_are_found_from_the_program_or_the_working_directory() {
|
||||
assert!(!is_flutter_project(&root, None));
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn stop_waits_for_the_launched_program_to_exit() {
|
||||
// The adapter answers `disconnect` at once; the program it started is still alive and
|
||||
// holds its port for a while. Stop must not report the session as over before it exits.
|
||||
// Reaped by a waiting thread: a zombie still "exists" for `kill(pid, 0)`, unlike the
|
||||
// program an adapter starts and reaps.
|
||||
// Ignores SIGTERM: Stop must wait for the program, not assume the signal ended it.
|
||||
let mut child = std::process::Command::new("python3")
|
||||
.args(["-c", "import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(1)"])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let pid = child.id();
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
});
|
||||
let h = harness(Script { debuggee_pid: Some(pid), ..Default::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Initialized)).await;
|
||||
for _ in 0..100 {
|
||||
if h.manager.session(id).map(|s| s.debuggee_pid.load(Ordering::Acquire)).ok() == Some(i64::from(pid)) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await; // let the program install its trap
|
||||
let started = Instant::now();
|
||||
h.manager.stop(id).await.unwrap();
|
||||
let elapsed = started.elapsed();
|
||||
assert!(elapsed >= Duration::from_millis(800), "stop returned after {elapsed:?}, before the program exited");
|
||||
assert!(elapsed < Duration::from_secs(5), "stop waited {elapsed:?} for a program that ended after a second");
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Terminated)).await;
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_second_stop_kills_the_program_instead_of_waiting() {
|
||||
let mut child = std::process::Command::new("python3")
|
||||
.args(["-c", "import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(30)"])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let pid = child.id();
|
||||
let exited = Arc::new(AtomicBool::new(false));
|
||||
{
|
||||
let exited = exited.clone();
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
exited.store(true, Ordering::Release);
|
||||
});
|
||||
}
|
||||
let h = harness(Script { debuggee_pid: Some(pid), ..Default::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Initialized)).await;
|
||||
for _ in 0..100 {
|
||||
if h.manager.session(id).map(|s| s.debuggee_pid.load(Ordering::Acquire)).ok() == Some(i64::from(pid)) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(400)).await;
|
||||
let first = tokio::spawn({
|
||||
let manager = h.manager.clone();
|
||||
async move { manager.stop(id).await }
|
||||
});
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
assert!(!exited.load(Ordering::Acquire), "the program is still alive while the first Stop waits");
|
||||
let started = Instant::now();
|
||||
h.manager.stop(id).await.unwrap();
|
||||
let first_result = tokio::time::timeout(Duration::from_secs(5), first).await.expect("the first Stop returns");
|
||||
first_result.unwrap().unwrap();
|
||||
assert!(started.elapsed() < Duration::from_secs(2), "a second Stop does not wait out the program");
|
||||
for _ in 0..100 {
|
||||
if exited.load(Ordering::Acquire) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert!(exited.load(Ordering::Acquire), "the second Stop killed the program");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn stop_waits_for_the_program_when_the_adapter_uses_javas_processid_event() {
|
||||
// Ignores SIGTERM: Stop must wait for the program, not assume the signal ended it.
|
||||
let mut child = std::process::Command::new("python3")
|
||||
.args(["-c", "import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(1)"])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let pid = child.id();
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
});
|
||||
let h = harness(Script { debuggee_pid: Some(pid), java_process_id: true, ..Default::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Initialized)).await;
|
||||
for _ in 0..100 {
|
||||
if h.manager.session(id).map(|s| s.debuggee_pid.load(Ordering::Acquire)).ok() == Some(i64::from(pid)) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let started = Instant::now();
|
||||
h.manager.stop(id).await.unwrap();
|
||||
assert!(
|
||||
started.elapsed() >= Duration::from_millis(800),
|
||||
"stop returned after {:?}, before the program exited",
|
||||
started.elapsed()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn output_keeps_arriving_while_a_stopped_program_is_exiting() {
|
||||
// Ignores SIGTERM: Stop must wait for the program, not assume the signal ended it.
|
||||
let mut child = std::process::Command::new("python3")
|
||||
.args(["-c", "import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(1)"])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let pid = child.id();
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
});
|
||||
let h = harness(Script { debuggee_pid: Some(pid), output_after_terminate: true, ..Default::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Initialized)).await;
|
||||
for _ in 0..100 {
|
||||
if h.manager.session(id).map(|s| s.debuggee_pid.load(Ordering::Acquire)).ok() == Some(i64::from(pid)) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
let started = Instant::now();
|
||||
let stop = tokio::spawn({
|
||||
let manager = h.manager.clone();
|
||||
async move { manager.stop(id).await }
|
||||
});
|
||||
// The last line must reach the console while Stop still waits for the program.
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Output { output, .. } if output == "late\n")).await;
|
||||
assert!(started.elapsed() < Duration::from_millis(800), "output arrived only after the program was gone");
|
||||
stop.await.unwrap().unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closing_a_project_stops_the_debug_sessions_it_started() {
|
||||
let h = harness(Script::default());
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Initialized)).await;
|
||||
// The session's cwd is /p, whatever key it was started under.
|
||||
h.manager.stop_under(Path::new("/p")).await;
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Terminated)).await;
|
||||
assert!(h.manager.sessions(None).is_empty(), "session {id:?} is gone");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn stop_kills_the_program_started_by_the_reported_launcher() {
|
||||
use std::io::BufRead;
|
||||
// java-debug reports the launcher shell; the JVM is its child. Stopping only the reported
|
||||
// pid orphans the program, which keeps running (and keeps its ports).
|
||||
let mut launcher = std::process::Command::new("sh")
|
||||
.args(["-c", "python3 -c 'import time; time.sleep(30)' & echo $!; wait"])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let launcher_pid = launcher.id();
|
||||
let mut line = String::new();
|
||||
std::io::BufReader::new(launcher.stdout.take().unwrap()).read_line(&mut line).unwrap();
|
||||
let program: i32 = line.trim().parse().expect("child pid");
|
||||
// Reap the launcher: a zombie still "exists" for `kill(pid, 0)`, unlike the shell jdtls reaps.
|
||||
std::thread::spawn(move || {
|
||||
let _ = launcher.wait();
|
||||
});
|
||||
|
||||
let h = harness(Script {
|
||||
debuggee_pid: Some(launcher_pid),
|
||||
supports_terminate: false, // java-debug does not advertise it
|
||||
..Default::default()
|
||||
});
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Initialized)).await;
|
||||
for _ in 0..100 {
|
||||
if h.manager.session(id).map(|s| s.debuggee_pid.load(Ordering::Acquire)).ok() == Some(i64::from(launcher_pid)) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
h.manager.stop(id).await.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while unsafe { libc::kill(program, 0) } == 0 {
|
||||
assert!(Instant::now() < deadline, "the program the launcher started survived stop");
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delve_leftovers_are_removed_without_touching_other_files() {
|
||||
let dir = std::env::temp_dir().join(format!("openidea-delve-bin-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for name in ["__debug_bin", "__debug_bin.exe", "__debug_bin.exe3323301925"] {
|
||||
std::fs::write(dir.join(name), b"bin").unwrap();
|
||||
}
|
||||
// Lookalikes that are not Delve's own binaries stay: sources, a future
|
||||
// in-progress build, and a directory that happens to share the name.
|
||||
for name in ["__debug_bin.go", "__debug_bin.go.exe", "main.go"] {
|
||||
std::fs::write(dir.join(name), b"keep").unwrap();
|
||||
}
|
||||
std::fs::create_dir(dir.join("__debug_bin.dir")).unwrap();
|
||||
remove_delve_binaries(&dir);
|
||||
for name in ["__debug_bin", "__debug_bin.exe", "__debug_bin.exe3323301925"] {
|
||||
assert!(!dir.join(name).exists(), "{name} should be gone");
|
||||
}
|
||||
for name in ["__debug_bin.go", "__debug_bin.go.exe", "main.go", "__debug_bin.dir"] {
|
||||
assert!(dir.join(name).exists(), "{name} should stay");
|
||||
}
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
+355
-84
@@ -12,14 +12,17 @@ use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use sqlx::{
|
||||
Column, ColumnIndex, Connection, Decode, Executor, MySql, Postgres, Row, SqlSafeStr, Sqlite, TypeInfo, ValueRef,
|
||||
mysql::{MySqlConnectOptions, MySqlPool, MySqlPoolOptions, MySqlSslMode},
|
||||
Column, ColumnIndex, Connection, Decode, Executor, Row, SqlSafeStr, Sqlite, TypeInfo, ValueRef,
|
||||
mysql::{MySqlConnectOptions, MySqlConnection, MySqlSslMode},
|
||||
pool::PoolConnection,
|
||||
postgres::{PgConnectOptions, PgPool, PgPoolOptions, PgSslMode},
|
||||
postgres::{PgConnectOptions, PgConnection, PgSslMode},
|
||||
sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions},
|
||||
};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -47,12 +50,135 @@ pub struct QueryResult {
|
||||
pub execution_ms: f64,
|
||||
}
|
||||
|
||||
/// Session context belongs to the physical connection, including across pool checkouts.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Context {
|
||||
default: Option<String>,
|
||||
current: Option<String>,
|
||||
known: bool,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
pub(crate) fn new(default: Option<String>) -> Self {
|
||||
Self { current: default.clone(), default, known: true }
|
||||
}
|
||||
|
||||
pub(crate) fn set_current(&mut self, current: Option<String>) {
|
||||
self.current = current;
|
||||
}
|
||||
|
||||
fn wanted(&self, driver: DbDriver, schema: Option<&str>) -> Option<String> {
|
||||
schema
|
||||
.filter(|s| !s.is_empty())
|
||||
.and_then(|s| crate::sql::use_schema(driver, s))
|
||||
.or_else(|| self.default.clone())
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! sqlx_pool {
|
||||
($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr) => {
|
||||
pub struct $manager {
|
||||
options: $options,
|
||||
init: Arc<Vec<String>>,
|
||||
timeout: Duration,
|
||||
}
|
||||
|
||||
pub struct $handle {
|
||||
conn: Option<$connection>,
|
||||
context: Context,
|
||||
options: $options,
|
||||
init: Arc<Vec<String>>,
|
||||
timeout: Duration,
|
||||
in_transaction: bool,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for $handle {
|
||||
type Target = $connection;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.conn.as_ref().expect("live connection")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::DerefMut for $handle {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
self.conn.as_mut().expect("live connection")
|
||||
}
|
||||
}
|
||||
|
||||
impl ManageConnection for $manager {
|
||||
type Connection = $handle;
|
||||
type Error = sqlx::Error;
|
||||
|
||||
async fn connect(&self) -> Result<Self::Connection, Self::Error> {
|
||||
tokio::time::timeout(self.timeout, async {
|
||||
let mut conn = <$connection>::connect_with(&self.options).await?;
|
||||
let context_sql = |value: Option<String>| {
|
||||
value.map(|v| {
|
||||
if $driver == DbDriver::Postgres {
|
||||
format!("SET search_path TO {v}")
|
||||
} else {
|
||||
crate::sql::use_schema($driver, &v).expect("switchable driver")
|
||||
}
|
||||
})
|
||||
};
|
||||
for sql in self.init.iter() {
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut conn).await?;
|
||||
}
|
||||
let row = sqlx::raw_sql(sqlx::AssertSqlSafe($query.to_owned())).fetch_one(&mut conn).await?;
|
||||
let context = Context::new(context_sql(row.try_get(0)?));
|
||||
Ok($handle {
|
||||
conn: Some(conn),
|
||||
context,
|
||||
options: self.options.clone(),
|
||||
init: self.init.clone(),
|
||||
timeout: self.timeout,
|
||||
in_transaction: false,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|_| sqlx::Error::PoolTimedOut)?
|
||||
}
|
||||
|
||||
async fn is_valid(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> {
|
||||
conn.ping().await
|
||||
}
|
||||
|
||||
fn has_broken(&self, conn: &mut Self::Connection) -> bool {
|
||||
conn.conn.is_none()
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
sqlx_pool!(PgManager, PgHandle, PgConnectOptions, PgConnection, DbDriver::Postgres, "SHOW search_path");
|
||||
sqlx_pool!(MysqlManager, MysqlHandle, MySqlConnectOptions, MySqlConnection, DbDriver::Mysql, "SELECT DATABASE()");
|
||||
|
||||
pub struct ServerPool<M: ManageConnection> {
|
||||
inner: Bb8Pool<M>,
|
||||
closed: AtomicBool,
|
||||
}
|
||||
|
||||
impl<M: ManageConnection> ServerPool<M> {
|
||||
async fn get(&self) -> IdeResult<bb8::PooledConnection<'static, M>>
|
||||
where
|
||||
M::Error: std::fmt::Display,
|
||||
{
|
||||
if self.closed.load(Ordering::Relaxed) {
|
||||
return Err(IdeError::new(ErrorKind::Io, "database connection is closed"));
|
||||
}
|
||||
self.inner.get_owned().await.map_err(|e| match e {
|
||||
bb8::RunError::User(e) => IdeError::new(ErrorKind::Io, e.to_string()),
|
||||
bb8::RunError::TimedOut => IdeError::new(ErrorKind::Io, "timed out connecting to the database"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Keep an empty slot when a connection is discarded after cancellation or rollback failure.
|
||||
pub struct MssqlConnectionManager(tiberius::Config);
|
||||
|
||||
type MssqlClient = tiberius::Client<tokio_util::compat::Compat<tokio::net::TcpStream>>;
|
||||
|
||||
pub struct MssqlConnection(Option<MssqlClient>);
|
||||
pub struct MssqlConnection(Option<MssqlClient>, Context);
|
||||
|
||||
impl std::ops::Deref for MssqlConnection {
|
||||
type Target = MssqlClient;
|
||||
@@ -76,7 +202,7 @@ impl ManageConnection for MssqlConnectionManager {
|
||||
|
||||
let tcp = tokio::net::TcpStream::connect(self.0.get_addr()).await?;
|
||||
tcp.set_nodelay(true)?;
|
||||
let client = match MssqlClient::connect(self.0.clone(), tcp.compat_write()).await {
|
||||
let mut client = match MssqlClient::connect(self.0.clone(), tcp.compat_write()).await {
|
||||
// Preserve the single redirect supported by the previous pool adapter.
|
||||
Err(tiberius::error::Error::Routing { host, port }) => {
|
||||
let mut config = self.0.clone();
|
||||
@@ -88,7 +214,11 @@ impl ManageConnection for MssqlConnectionManager {
|
||||
}
|
||||
result => result?,
|
||||
};
|
||||
Ok(MssqlConnection(Some(client)))
|
||||
let row = client.simple_query("SELECT DB_NAME()").await?.into_row().await?;
|
||||
let default = row
|
||||
.and_then(|r| r.get::<&str, _>(0).map(str::to_owned))
|
||||
.and_then(|db| crate::sql::use_schema(DbDriver::SqlServer, &db));
|
||||
Ok(MssqlConnection(Some(client), Context::new(default)))
|
||||
}
|
||||
|
||||
async fn is_valid(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> {
|
||||
@@ -103,25 +233,13 @@ impl ManageConnection for MssqlConnectionManager {
|
||||
|
||||
pub enum Pool {
|
||||
Sqlite(SqlitePool),
|
||||
Postgres(PgPool),
|
||||
Mysql(MySqlPool),
|
||||
Postgres(ServerPool<PgManager>),
|
||||
Mysql(ServerPool<MysqlManager>),
|
||||
SqlServer(Bb8Pool<MssqlConnectionManager>),
|
||||
Clickhouse(crate::clickhouse::ClickhousePool),
|
||||
Oracle(crate::oracle::OraclePool),
|
||||
}
|
||||
|
||||
/// Runs `$body` with `$p` bound to the concrete pool of each driver.
|
||||
macro_rules! with_pool {
|
||||
($pool:expr, $p:ident => $body:expr) => {
|
||||
match $pool {
|
||||
Pool::Sqlite($p) => $body,
|
||||
Pool::Postgres($p) => $body,
|
||||
Pool::Mysql($p) => $body,
|
||||
Pool::SqlServer(_) | Pool::Clickhouse(_) | Pool::Oracle(_) => unreachable!(),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) fn db_err(e: sqlx::Error) -> IdeError {
|
||||
match &e {
|
||||
sqlx::Error::Database(d) => {
|
||||
@@ -438,6 +556,19 @@ macro_rules! backend_id {
|
||||
}};
|
||||
}
|
||||
|
||||
// Session control, scripts and PostgreSQL set_config can invalidate the tracked context.
|
||||
fn context_may_change(sql: &str) -> bool {
|
||||
let text = sql.trim().trim_end_matches(';');
|
||||
text.contains(';')
|
||||
|| text.to_ascii_lowercase().contains("set_config")
|
||||
|| !text.split_whitespace().next().is_some_and(|s| {
|
||||
matches!(
|
||||
s.to_ascii_uppercase().as_str(),
|
||||
"SELECT" | "INSERT" | "UPDATE" | "DELETE" | "CREATE" | "DROP" | "TRUNCATE" | "SHOW" | "EXPLAIN"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn looks_like_query(sql: &str) -> bool {
|
||||
let first = sql
|
||||
.lines()
|
||||
@@ -535,7 +666,13 @@ impl Setup {
|
||||
return Err(IdeError::invalid("ClickHouse HTTP does not support statement caching"));
|
||||
}
|
||||
(_, "statement_cache_capacity") => s.statement_cache = Some(number(&name)? as usize),
|
||||
(_, "connect_timeout") => s.connect_timeout = Some(Duration::from_secs(number(&name)?)),
|
||||
(_, "connect_timeout") => {
|
||||
let seconds = number(&name)?;
|
||||
if seconds == 0 {
|
||||
return Err(IdeError::invalid("connect_timeout must be greater than zero"));
|
||||
}
|
||||
s.connect_timeout = Some(Duration::from_secs(seconds));
|
||||
}
|
||||
(DbDriver::Postgres, "application_name") => s.application_name = Some(value.to_owned()),
|
||||
(DbDriver::Mysql, "charset") => s.charset = Some(value.to_owned()),
|
||||
(DbDriver::Mysql, "collation") => s.collation = Some(value.to_owned()),
|
||||
@@ -662,14 +799,12 @@ impl Pool {
|
||||
if let Some(n) = setup.statement_cache {
|
||||
opts = opts.statement_cache_capacity(n);
|
||||
}
|
||||
let pool = PgPoolOptions::new()
|
||||
.max_connections(MAX)
|
||||
.acquire_timeout(timeout)
|
||||
.after_connect(after_connect!())
|
||||
.connect_with(opts)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
Ok(Pool::Postgres(pool))
|
||||
let manager = PgManager { options: opts, init: init.clone(), timeout };
|
||||
// Open once directly so authentication failures retain their database error.
|
||||
let first = manager.connect().await.map_err(db_err)?;
|
||||
let pool = Bb8Pool::builder().max_size(MAX).connection_timeout(timeout).build_unchecked(manager);
|
||||
let _ = pool.add(first);
|
||||
Ok(Pool::Postgres(ServerPool { inner: pool, closed: AtomicBool::new(false) }))
|
||||
}
|
||||
DbDriver::Mysql => {
|
||||
let mut opts = MySqlConnectOptions::new()
|
||||
@@ -711,14 +846,12 @@ impl Pool {
|
||||
if !tz.is_empty() {
|
||||
opts = opts.timezone(Some(tz.to_owned()));
|
||||
}
|
||||
let pool = MySqlPoolOptions::new()
|
||||
.max_connections(MAX)
|
||||
.acquire_timeout(timeout)
|
||||
.after_connect(after_connect!())
|
||||
.connect_with(opts)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
Ok(Pool::Mysql(pool))
|
||||
let manager = MysqlManager { options: opts, init: init.clone(), timeout };
|
||||
// Open once directly so authentication failures retain their database error.
|
||||
let first = manager.connect().await.map_err(db_err)?;
|
||||
let pool = Bb8Pool::builder().max_size(MAX).connection_timeout(timeout).build_unchecked(manager);
|
||||
let _ = pool.add(first);
|
||||
Ok(Pool::Mysql(ServerPool { inner: pool, closed: AtomicBool::new(false) }))
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
use tiberius::Config;
|
||||
@@ -757,7 +890,9 @@ impl Pool {
|
||||
match self {
|
||||
Pool::SqlServer(_) | Pool::Oracle(_) => {}
|
||||
Pool::Clickhouse(p) => p.close(),
|
||||
_ => with_pool!(self, p => p.close().await),
|
||||
Pool::Sqlite(p) => p.close().await,
|
||||
Pool::Postgres(p) => p.closed.store(true, Ordering::Relaxed),
|
||||
Pool::Mysql(p) => p.closed.store(true, Ordering::Relaxed),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -766,7 +901,9 @@ impl Pool {
|
||||
Pool::SqlServer(_) => false,
|
||||
Pool::Oracle(p) => p.is_closed(),
|
||||
Pool::Clickhouse(p) => p.is_closed(),
|
||||
_ => with_pool!(self, p => p.is_closed()),
|
||||
Pool::Sqlite(p) => p.is_closed(),
|
||||
Pool::Postgres(p) => p.closed.load(Ordering::Relaxed),
|
||||
Pool::Mysql(p) => p.closed.load(Ordering::Relaxed),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -775,18 +912,9 @@ impl Pool {
|
||||
if let Pool::Clickhouse(p) = self {
|
||||
return Ok(p.execute(sql, max, &CancellationToken::new()).await?.rows);
|
||||
}
|
||||
if let Pool::Oracle(p) = self {
|
||||
let mut conn = p.get().await?;
|
||||
let fetched = crate::oracle::run(&mut conn, sql, 0, max, Cells::Text, &CancellationToken::new()).await?;
|
||||
return Ok(fetched.1);
|
||||
}
|
||||
let fetched: IdeResult<Fetched> = match self {
|
||||
Pool::SqlServer(p) => {
|
||||
let mut conn = p.get_owned().await.map_err(mssql_pool_err)?;
|
||||
mssql_fetch(&mut conn, sql, 0, max).await
|
||||
}
|
||||
_ => with_pool!(self, p => fetch!(p, sql, max, Cells::Text)),
|
||||
};
|
||||
let mut conn = Held::acquire(self).await?;
|
||||
conn.apply_context(None).await?;
|
||||
let fetched = conn.fetch_rows(sql, max).await;
|
||||
Ok(fetched?.1)
|
||||
}
|
||||
|
||||
@@ -809,7 +937,10 @@ impl Pool {
|
||||
return p.execute_from(sql, skip, max_rows, cancel).await;
|
||||
}
|
||||
let mut conn = Held::acquire(self).await?;
|
||||
let r = conn.execute_from(self, sql, skip, max_rows, cancel).await;
|
||||
let r = match conn.apply_context(None).await {
|
||||
Ok(()) => conn.execute_from(self, sql, skip, max_rows, cancel).await,
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
conn.discard().await;
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -822,8 +953,10 @@ impl Pool {
|
||||
pub async fn transaction(&self, statements: &[(String, bool)]) -> IdeResult<u64> {
|
||||
match self {
|
||||
Pool::Clickhouse(_) => Err(crate::clickhouse::transaction_error()),
|
||||
Pool::SqlServer(p) => {
|
||||
let mut conn = p.get_owned().await.map_err(mssql_pool_err)?;
|
||||
Pool::SqlServer(_) => {
|
||||
let mut held = Held::acquire(self).await?;
|
||||
held.apply_context(None).await?;
|
||||
let Held::SqlServer(mut conn) = held else { unreachable!() };
|
||||
let result = async {
|
||||
mssql_command(&mut conn, "BEGIN TRAN").await?;
|
||||
let mut total = 0;
|
||||
@@ -846,8 +979,10 @@ impl Pool {
|
||||
}
|
||||
result
|
||||
}
|
||||
Pool::Oracle(p) => {
|
||||
let mut conn = p.get().await?;
|
||||
Pool::Oracle(_) => {
|
||||
let mut held = Held::acquire(self).await?;
|
||||
held.apply_context(None).await?;
|
||||
let Held::Oracle(mut conn) = held else { unreachable!() };
|
||||
let result = crate::oracle::transaction(&mut conn, statements).await;
|
||||
if result.is_err() {
|
||||
// An open transaction must never return to the pool with the connection.
|
||||
@@ -855,21 +990,37 @@ impl Pool {
|
||||
}
|
||||
result
|
||||
}
|
||||
_ => with_pool!(self, p => {
|
||||
let mut tx = p.begin().await.map_err(db_err)?;
|
||||
let mut total = 0;
|
||||
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();
|
||||
// MySQL reports 0 for an UPDATE that leaves the row unchanged.
|
||||
if *expect_one && (n > 1 || (n == 0 && !matches!(self, Pool::Mysql(_)))) {
|
||||
return Err(IdeError::invalid(format!("{sql}: expected to change 1 row, changed {n}; nothing was saved")));
|
||||
}
|
||||
total += n;
|
||||
_ => {
|
||||
let mut conn = Held::acquire(self).await?;
|
||||
conn.apply_context(None).await?;
|
||||
macro_rules! transaction {
|
||||
($c:expr) => {{
|
||||
let mut tx = (&mut **$c).begin().await.map_err(db_err)?;
|
||||
let mut total = 0;
|
||||
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!(
|
||||
"{sql}: expected to change 1 row, changed {n}; nothing was saved"
|
||||
)));
|
||||
}
|
||||
total += n;
|
||||
}
|
||||
tx.commit().await.map_err(db_err)?;
|
||||
Ok(total)
|
||||
}};
|
||||
}
|
||||
tx.commit().await.map_err(db_err)?;
|
||||
Ok(total)
|
||||
}),
|
||||
match &mut conn {
|
||||
Held::Sqlite(c) => transaction!(c),
|
||||
Held::Postgres(c) => transaction!(&mut ***c),
|
||||
Held::Mysql(c) => transaction!(&mut ***c),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -878,8 +1029,8 @@ impl Pool {
|
||||
/// manual-commit console across statements with its transaction open.
|
||||
pub enum Held {
|
||||
Sqlite(PoolConnection<Sqlite>),
|
||||
Postgres(PoolConnection<Postgres>),
|
||||
Mysql(PoolConnection<MySql>),
|
||||
Postgres(Box<bb8::PooledConnection<'static, PgManager>>),
|
||||
Mysql(Box<bb8::PooledConnection<'static, MysqlManager>>),
|
||||
SqlServer(Box<bb8::PooledConnection<'static, MssqlConnectionManager>>),
|
||||
Clickhouse(crate::clickhouse::ClickhousePool),
|
||||
Oracle(crate::oracle::OracleConnection),
|
||||
@@ -889,8 +1040,8 @@ impl Held {
|
||||
pub async fn acquire(pool: &Pool) -> IdeResult<Self> {
|
||||
Ok(match pool {
|
||||
Pool::Sqlite(p) => Held::Sqlite(p.acquire().await.map_err(db_err)?),
|
||||
Pool::Postgres(p) => Held::Postgres(p.acquire().await.map_err(db_err)?),
|
||||
Pool::Mysql(p) => Held::Mysql(p.acquire().await.map_err(db_err)?),
|
||||
Pool::Postgres(p) => Held::Postgres(Box::new(p.get().await?)),
|
||||
Pool::Mysql(p) => Held::Mysql(Box::new(p.get().await?)),
|
||||
Pool::SqlServer(p) => Held::SqlServer(Box::new(p.get_owned().await.map_err(mssql_pool_err)?)),
|
||||
Pool::Clickhouse(p) => {
|
||||
if p.is_closed() {
|
||||
@@ -902,8 +1053,121 @@ impl Held {
|
||||
})
|
||||
}
|
||||
|
||||
fn context(&mut self) -> Option<&mut Context> {
|
||||
match self {
|
||||
Held::Postgres(c) => Some(&mut c.context),
|
||||
Held::Mysql(c) => Some(&mut c.context),
|
||||
Held::SqlServer(c) => Some(&mut c.1),
|
||||
Held::Oracle(c) => Some(c.context()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn invalidate_context(&mut self) {
|
||||
if let Some(context) = self.context() {
|
||||
context.known = false;
|
||||
}
|
||||
}
|
||||
|
||||
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") {
|
||||
c.in_transaction = true;
|
||||
return;
|
||||
}
|
||||
if matches!(control.as_str(), "COMMIT" | "ROLLBACK") {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if context_may_change(sql) {
|
||||
self.invalidate_context();
|
||||
}
|
||||
}
|
||||
|
||||
fn after_statement(&mut self, sql: &str) {
|
||||
if let Held::Mysql(c) = self
|
||||
&& matches!(sql.trim().trim_end_matches(';').trim().to_ascii_uppercase().as_str(), "COMMIT" | "ROLLBACK")
|
||||
{
|
||||
c.in_transaction = false;
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn apply_context(&mut self, schema: Option<&str>) -> IdeResult<()> {
|
||||
let driver = match self {
|
||||
Held::Postgres(_) => DbDriver::Postgres,
|
||||
Held::Mysql(_) => DbDriver::Mysql,
|
||||
Held::SqlServer(_) => DbDriver::SqlServer,
|
||||
Held::Oracle(_) => DbDriver::Oracle,
|
||||
_ => return Ok(()),
|
||||
};
|
||||
let context = self.context().expect("switchable connection");
|
||||
let wanted = context.wanted(driver, schema);
|
||||
if context.known && context.current == wanted {
|
||||
return Ok(());
|
||||
}
|
||||
context.known = false;
|
||||
if let Some(sql) = &wanted {
|
||||
self.raw_command(sql).await?;
|
||||
} else {
|
||||
// MySQL cannot USE an absent database. Re-open with the original options.
|
||||
macro_rules! reopen {
|
||||
($c:expr, $manager:ident) => {{
|
||||
let manager = $manager { options: $c.options.clone(), init: $c.init.clone(), timeout: $c.timeout };
|
||||
if $c.in_transaction {
|
||||
return Err(IdeError::invalid("commit or roll back before clearing the selected database"));
|
||||
}
|
||||
let fresh = manager.connect().await.map_err(db_err)?;
|
||||
if let Some(raw) = $c.conn.take() {
|
||||
let _ = raw.close().await;
|
||||
}
|
||||
***$c = fresh;
|
||||
}};
|
||||
}
|
||||
match self {
|
||||
Held::Mysql(c) => reopen!(c, MysqlManager),
|
||||
Held::Postgres(c) => reopen!(c, PgManager),
|
||||
_ => unreachable!("server context has a default"),
|
||||
}
|
||||
}
|
||||
let context = self.context().expect("switchable connection");
|
||||
context.current = wanted;
|
||||
context.known = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Restore before a manual session returns its physical connection to the pool.
|
||||
pub async fn restore_default(&mut self) -> IdeResult<()> {
|
||||
self.apply_context(None).await
|
||||
}
|
||||
|
||||
async fn fetch_rows(&mut self, sql: &str, max: usize) -> IdeResult<Fetched> {
|
||||
self.before_statement(sql);
|
||||
let result = match self {
|
||||
Held::Sqlite(c) => fetch!(&mut **c, sql, max, Cells::Text),
|
||||
Held::Postgres(c) => fetch!(&mut ****c, sql, max, Cells::Text),
|
||||
Held::Mysql(c) => fetch!(&mut ****c, sql, max, Cells::Text),
|
||||
Held::SqlServer(c) => mssql_fetch(c, sql, 0, max).await,
|
||||
Held::Oracle(c) => crate::oracle::run(c, sql, 0, max, Cells::Text, &CancellationToken::new()).await,
|
||||
Held::Clickhouse(_) => unreachable!(),
|
||||
};
|
||||
if result.is_ok() {
|
||||
self.after_statement(sql);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Runs a statement without results (`BEGIN`, `COMMIT`, `ROLLBACK`).
|
||||
pub async fn command(&mut self, sql: &str) -> IdeResult<()> {
|
||||
self.before_statement(sql);
|
||||
let result = self.raw_command(sql).await;
|
||||
if result.is_ok() {
|
||||
self.after_statement(sql);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn raw_command(&mut self, sql: &str) -> IdeResult<()> {
|
||||
match self {
|
||||
Held::SqlServer(c) => mssql_command(c, sql).await,
|
||||
Held::Clickhouse(_) => Err(crate::clickhouse::transaction_error()),
|
||||
@@ -918,8 +1182,8 @@ impl Held {
|
||||
let sql = sqlx::AssertSqlSafe(sql.to_owned());
|
||||
match other {
|
||||
Held::Sqlite(c) => sqlx::raw_sql(sql).execute(&mut **c).await.map(drop),
|
||||
Held::Postgres(c) => sqlx::raw_sql(sql).execute(&mut **c).await.map(drop),
|
||||
Held::Mysql(c) => sqlx::raw_sql(sql).execute(&mut **c).await.map(drop),
|
||||
Held::Postgres(c) => sqlx::raw_sql(sql).execute(&mut ****c).await.map(drop),
|
||||
Held::Mysql(c) => sqlx::raw_sql(sql).execute(&mut ****c).await.map(drop),
|
||||
Held::SqlServer(_) | Held::Clickhouse(_) | Held::Oracle(_) => unreachable!(),
|
||||
}
|
||||
.map_err(db_err)
|
||||
@@ -932,11 +1196,15 @@ impl Held {
|
||||
pub async fn discard(self) {
|
||||
match self {
|
||||
Held::Sqlite(c) => drop(c.detach()),
|
||||
Held::Postgres(c) => {
|
||||
let _ = c.detach().close().await;
|
||||
Held::Postgres(mut c) => {
|
||||
if let Some(raw) = c.conn.take() {
|
||||
let _ = raw.close().await;
|
||||
}
|
||||
}
|
||||
Held::Mysql(c) => {
|
||||
let _ = c.detach().close().await;
|
||||
Held::Mysql(mut c) => {
|
||||
if let Some(raw) = c.conn.take() {
|
||||
let _ = raw.close().await;
|
||||
}
|
||||
}
|
||||
Held::SqlServer(mut c) => {
|
||||
c.0.take();
|
||||
@@ -971,6 +1239,7 @@ impl Held {
|
||||
if let Held::Clickhouse(c) = self {
|
||||
return c.execute_from(sql, skip, max_rows, cancel).await;
|
||||
}
|
||||
self.before_statement(sql);
|
||||
let started = Instant::now();
|
||||
// `$id`: the query naming the server process, `$kill`: how another connection stops it.
|
||||
macro_rules! run {
|
||||
@@ -1003,9 +1272,9 @@ impl Held {
|
||||
let fetched: Fetched = match self {
|
||||
Held::Sqlite(c) => run!(c, None::<&str>, |_: String| String::new()),
|
||||
Held::Postgres(c) => {
|
||||
run!(c, Some("SELECT pg_backend_pid()"), |b: String| format!("SELECT pg_cancel_backend({b})"))
|
||||
run!(&mut ***c, Some("SELECT pg_backend_pid()"), |b: String| format!("SELECT pg_cancel_backend({b})"))
|
||||
}
|
||||
Held::Mysql(c) => run!(c, Some("SELECT CONNECTION_ID()"), |b: String| format!("KILL QUERY {b}")),
|
||||
Held::Mysql(c) => run!(&mut ***c, Some("SELECT CONNECTION_ID()"), |b: String| format!("KILL QUERY {b}")),
|
||||
Held::SqlServer(c) => {
|
||||
// Tiberius has no attention/cancel API; stop reading and discard the connection.
|
||||
tokio::select! {
|
||||
@@ -1016,6 +1285,7 @@ impl Held {
|
||||
Held::Oracle(c) => crate::oracle::run(c, sql, skip, max_rows, Cells::Display, cancel).await?,
|
||||
Held::Clickhouse(_) => unreachable!(),
|
||||
};
|
||||
self.after_statement(sql);
|
||||
let (columns, rows, affected, has_more, first) = fetched;
|
||||
let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
Ok(QueryResult {
|
||||
@@ -1055,7 +1325,7 @@ mod tests {
|
||||
#[test]
|
||||
fn discarded_sqlserver_connections_are_broken() {
|
||||
let manager = MssqlConnectionManager(tiberius::Config::new());
|
||||
assert!(manager.has_broken(&mut MssqlConnection(None)));
|
||||
assert!(manager.has_broken(&mut MssqlConnection(None, Context::new(None))));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1191,6 +1461,7 @@ mod tests {
|
||||
assert_eq!(setup.charset.as_deref(), Some("utf8mb4"));
|
||||
assert_eq!(setup.connect_timeout, Some(Duration::from_secs(5)));
|
||||
assert!(Setup::of(&DataSource { properties: vec![prop("a; drop", "1")], ..s.clone() }).is_err());
|
||||
assert!(Setup::of(&DataSource { properties: vec![prop("connect_timeout", "0")], ..s.clone() }).is_err());
|
||||
assert!(Setup::of(&DataSource { properties: vec![prop("connect_timeout", "soon")], ..s }).is_err());
|
||||
}
|
||||
|
||||
|
||||
+51
-11
@@ -315,7 +315,7 @@ fn keep_alive(pool: &Arc<Pool>, every: Duration) {
|
||||
async fn end_session(session: &Session) {
|
||||
let held = session.lock().await.take();
|
||||
if let Some(mut conn) = held
|
||||
&& conn.command("ROLLBACK").await.is_err()
|
||||
&& (conn.command("ROLLBACK").await.is_err() || conn.restore_default().await.is_err())
|
||||
{
|
||||
conn.discard().await;
|
||||
}
|
||||
@@ -704,8 +704,15 @@ impl DbManager {
|
||||
let introspection = self.source(id)?.introspection;
|
||||
let system = introspection.show_system;
|
||||
let pool = self.pool(id).await?;
|
||||
if pool.driver() == DbDriver::SqlServer {
|
||||
let first =
|
||||
|rows: Vec<Vec<Option<String>>>| rows.into_iter().filter_map(|r| r.into_iter().next().flatten());
|
||||
let current = first(pool.rows("SELECT DB_NAME()", 1).await?).next().unwrap_or_default();
|
||||
let names = first(pool.rows(sql::sqlserver_databases(), MAX_META_ROWS).await?).collect();
|
||||
return Ok(Databases { current, names });
|
||||
}
|
||||
if pool.driver() != DbDriver::Postgres {
|
||||
return Err(IdeError::invalid("only PostgreSQL data sources list databases"));
|
||||
return Err(IdeError::invalid("this data source does not list databases"));
|
||||
}
|
||||
let first = |rows: Vec<Vec<Option<String>>>| rows.into_iter().filter_map(|r| r.into_iter().next().flatten());
|
||||
let current = first(pool.rows("SELECT current_database()", 1).await?).next().unwrap_or_default();
|
||||
@@ -1038,11 +1045,13 @@ impl DbManager {
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
self.execute_from(id, statement, 0, max_rows, cancel).await
|
||||
self.execute_from(id, statement, 0, max_rows, cancel, None).await
|
||||
}
|
||||
|
||||
/// [`execute`](Self::execute), reading past the first `skip` rows without keeping
|
||||
/// them: a later page of a result, where only that page is decoded and returned.
|
||||
/// `schema` is a query console's active context: the connection that runs the
|
||||
/// statement is put in it first, so unqualified names resolve there.
|
||||
pub async fn execute_from(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -1050,8 +1059,9 @@ impl DbManager {
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let r = self.run(id, statement, skip, max_rows, cancel).await;
|
||||
let r = self.run(id, statement, skip, max_rows, cancel, schema).await;
|
||||
let ran = match &r {
|
||||
Ok(_) => true,
|
||||
Err(e) => !matches!(e.kind, ErrorKind::Cancelled | ErrorKind::PermissionDenied),
|
||||
@@ -1083,8 +1093,15 @@ impl DbManager {
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// The execution plan of `statement` (explained, not run).
|
||||
pub async fn explain(&self, id: &str, statement: &str, cancel: &CancellationToken) -> IdeResult<Vec<PlanNode>> {
|
||||
/// The execution plan of `statement` (explained, not run), in the console's
|
||||
/// active `schema` when it has one.
|
||||
pub async fn explain(
|
||||
&self,
|
||||
id: &str,
|
||||
statement: &str,
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<Vec<PlanNode>> {
|
||||
let driver = self.pool(id).await?.driver();
|
||||
if driver == DbDriver::Oracle {
|
||||
// EXPLAIN PLAN writes PLAN_TABLE; the plan is read (and cleaned up) separately.
|
||||
@@ -1102,14 +1119,16 @@ impl DbManager {
|
||||
0,
|
||||
MAX_META_ROWS,
|
||||
cancel,
|
||||
schema,
|
||||
)
|
||||
.await?;
|
||||
let result = self.run(id, &plan::oracle_plan_query(&plan_id), 0, MAX_META_ROWS, cancel).await?;
|
||||
let result = self.run(id, &plan::oracle_plan_query(&plan_id), 0, MAX_META_ROWS, cancel, None).await?;
|
||||
let nodes = plan::parse(driver, &result);
|
||||
let _ = self.run(id, &plan::oracle_plan_cleanup(&plan_id), 0, 0, cancel).await;
|
||||
let _ = self.run(id, &plan::oracle_plan_cleanup(&plan_id), 0, 0, cancel, None).await;
|
||||
return nodes;
|
||||
}
|
||||
let result = self.run(id, &plan::explain_statement(driver, statement), 0, MAX_META_ROWS, cancel).await?;
|
||||
let result =
|
||||
self.run(id, &plan::explain_statement(driver, statement), 0, MAX_META_ROWS, cancel, schema).await?;
|
||||
plan::parse(driver, &result)
|
||||
}
|
||||
|
||||
@@ -1120,11 +1139,25 @@ impl DbManager {
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let pool = self.pool(id).await?;
|
||||
let session = self.sessions.lock().get(id).cloned();
|
||||
let Some(session) = session else {
|
||||
return pool.execute_from(statement, skip, max_rows, cancel).await;
|
||||
if schema.is_none() {
|
||||
return pool.execute_from(statement, skip, max_rows, cancel).await;
|
||||
}
|
||||
// Like `Pool::execute_from`, with the schema applied to the connection first.
|
||||
let mut conn = Held::acquire(&pool).await?;
|
||||
let r = match conn.apply_context(schema).await {
|
||||
Ok(()) => conn.execute_from(&pool, statement, skip, max_rows, cancel).await,
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
conn.discard().await;
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
return r;
|
||||
};
|
||||
if pool.driver() == DbDriver::Clickhouse {
|
||||
return Err(IdeError::invalid("ClickHouse manual transactions are unsupported"));
|
||||
@@ -1132,10 +1165,12 @@ impl DbManager {
|
||||
let mut held = session.lock().await;
|
||||
if held.is_none() {
|
||||
let mut conn = Held::acquire(&pool).await?;
|
||||
conn.apply_context(schema).await?;
|
||||
conn.command(conn::begin_statement(pool.driver())).await?;
|
||||
*held = Some(conn);
|
||||
}
|
||||
let conn = held.as_mut().expect("opened above");
|
||||
conn.apply_context(schema).await?;
|
||||
let r = conn.execute_from(&pool, statement, skip, max_rows, cancel).await;
|
||||
if cancel.is_cancelled() {
|
||||
// The server rolls the transaction back with the connection.
|
||||
@@ -1171,7 +1206,12 @@ impl DbManager {
|
||||
let Some(session) = session else { return Ok(()) };
|
||||
let mut held = session.lock().await;
|
||||
let Some(mut conn) = held.take() else { return Ok(()) };
|
||||
match conn.command(if commit { "COMMIT" } else { "ROLLBACK" }).await {
|
||||
let result = async {
|
||||
conn.command(if commit { "COMMIT" } else { "ROLLBACK" }).await?;
|
||||
conn.restore_default().await
|
||||
}
|
||||
.await;
|
||||
match result {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
conn.discard().await;
|
||||
|
||||
@@ -181,7 +181,7 @@ impl OraclePool {
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(format!("Oracle connect task: {e}")))?
|
||||
.map_err(oracle_err)?;
|
||||
let _ = pool.add(OracleHandle { conn: Some(opened) });
|
||||
let _ = pool.add(opened);
|
||||
Ok(Self { state, pool: Arc::new(pool) })
|
||||
}
|
||||
|
||||
@@ -208,6 +208,7 @@ fn pool_err(e: bb8::RunError<OracleError>) -> OracleError {
|
||||
/// discarded (a cancelled statement leaves it in the blocking task).
|
||||
pub struct OracleHandle {
|
||||
conn: Option<oracle::Connection>,
|
||||
context: crate::conn::Context,
|
||||
}
|
||||
|
||||
pub struct OracleConnectionManager(Arc<State>);
|
||||
@@ -222,7 +223,7 @@ impl ManageConnection for OracleConnectionManager {
|
||||
.await
|
||||
.map_err(|e| OracleError::message(format!("Oracle connect task: {e}")))?;
|
||||
let conn = opened.map_err(OracleError::new)?;
|
||||
Ok(OracleHandle { conn: Some(conn) })
|
||||
Ok(conn)
|
||||
}
|
||||
|
||||
async fn is_valid(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> {
|
||||
@@ -271,6 +272,10 @@ pub struct OracleConnection {
|
||||
}
|
||||
|
||||
impl OracleConnection {
|
||||
pub(crate) fn context(&mut self) -> &mut crate::conn::Context {
|
||||
&mut self.pooled.context
|
||||
}
|
||||
|
||||
pub fn is_closed(&self) -> bool {
|
||||
self.pooled.conn.is_none()
|
||||
}
|
||||
@@ -282,7 +287,7 @@ impl OracleConnection {
|
||||
}
|
||||
}
|
||||
|
||||
fn open(state: &State) -> oracle::Result<oracle::Connection> {
|
||||
fn open(state: &State) -> oracle::Result<OracleHandle> {
|
||||
let mut connector = oracle::Connector::new(state.user.clone(), state.password.clone(), state.connect.clone());
|
||||
connector.driver_name("OpenIDEA");
|
||||
if let Some(n) = state.statement_cache {
|
||||
@@ -293,7 +298,12 @@ fn open(state: &State) -> oracle::Result<oracle::Connection> {
|
||||
for sql in &state.init {
|
||||
statement(&mut conn, sql, 0, 0, Cells::Text).map_err(|e| message_error(&e.message))?;
|
||||
}
|
||||
Ok(conn)
|
||||
let user: String = conn.query_row_as("SELECT SYS_CONTEXT('USERENV', 'SESSION_USER') FROM DUAL", &[])?;
|
||||
let default = crate::sql::use_schema(DbDriver::Oracle, &user);
|
||||
let current: String = conn.query_row_as("SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') FROM DUAL", &[])?;
|
||||
let mut context = crate::conn::Context::new(default);
|
||||
context.set_current(crate::sql::use_schema(DbDriver::Oracle, ¤t));
|
||||
Ok(OracleHandle { conn: Some(conn), context })
|
||||
}
|
||||
|
||||
/// Runs `f` with the connection on the blocking pool. Cancelling drops the
|
||||
@@ -558,7 +568,7 @@ mod tests {
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let mut broken = OracleHandle { conn: None };
|
||||
let mut broken = OracleHandle { conn: None, context: crate::conn::Context::new(None) };
|
||||
assert!(manager.has_broken(&mut broken));
|
||||
// A connection that cannot be opened reports the failure without panicking
|
||||
// (a client-load error, or ORA-12541 when a client is available).
|
||||
|
||||
@@ -63,6 +63,11 @@ pub const ORACLE_SYSTEM_SCHEMAS: &[&str] = &[
|
||||
"XS$NULL",
|
||||
];
|
||||
|
||||
/// Databases available to this login; offline/restoring databases cannot be selected.
|
||||
pub fn sqlserver_databases() -> &'static str {
|
||||
"SELECT name FROM sys.databases WHERE state = 0 AND HAS_DBACCESS(name) = 1 ORDER BY name"
|
||||
}
|
||||
|
||||
pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
|
||||
match driver {
|
||||
DbDriver::Sqlite => "SELECT name FROM pragma_database_list WHERE name <> 'temp' ORDER BY seq",
|
||||
@@ -396,6 +401,18 @@ pub fn current_schema(driver: DbDriver) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The statement that makes unqualified names resolve in `schema` on the
|
||||
/// connection that runs it (a query console's active schema; `None`: the driver
|
||||
/// has no schema to switch — SQLite's `main`, ClickHouse's `USE` differs).
|
||||
pub fn use_schema(driver: DbDriver, schema: &str) -> Option<String> {
|
||||
match driver {
|
||||
DbDriver::Sqlite | DbDriver::Clickhouse => None,
|
||||
DbDriver::Postgres => Some(format!("SET search_path TO {}", quote_ident(driver, schema))),
|
||||
DbDriver::Mysql | DbDriver::SqlServer => Some(format!("USE {}", quote_ident(driver, schema))),
|
||||
DbDriver::Oracle => Some(format!("ALTER SESSION SET CURRENT_SCHEMA = {}", quote_ident(driver, schema))),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbSortKey")]
|
||||
@@ -994,6 +1011,20 @@ mod tests {
|
||||
assert!(object_ddl(DbDriver::Postgres, "s", K::Sequence, "q").unwrap().0.contains("sequencename = 'q'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schema_switch_statement_per_dialect() {
|
||||
assert_eq!(use_schema(DbDriver::Postgres, "app data"), Some("SET search_path TO \"app data\"".into()));
|
||||
assert_eq!(use_schema(DbDriver::Mysql, "a`b"), Some("USE `a``b`".into()));
|
||||
assert_eq!(use_schema(DbDriver::SqlServer, "app] data"), Some("USE [app]] data]".into()));
|
||||
assert_eq!(use_schema(DbDriver::Postgres, "a\"b"), Some("SET search_path TO \"a\"\"b\"".into()));
|
||||
assert_eq!(use_schema(DbDriver::Oracle, "a\"b"), Some("ALTER SESSION SET CURRENT_SCHEMA = \"a\"\"b\"".into()));
|
||||
assert!(sqlserver_databases().contains("state = 0 AND HAS_DBACCESS(name) = 1"));
|
||||
assert_eq!(use_schema(DbDriver::Oracle, "hr"), Some("ALTER SESSION SET CURRENT_SCHEMA = \"hr\"".into()));
|
||||
// Single-schema (SQLite) and not-yet-supported drivers: no dropdown, no switch.
|
||||
assert_eq!(use_schema(DbDriver::Sqlite, "main"), None);
|
||||
assert_eq!(use_schema(DbDriver::Clickhouse, "default"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_ddl() {
|
||||
let cols = [
|
||||
|
||||
@@ -103,7 +103,7 @@ async fn clickhouse_cloud_manager_catalogs_and_session_table() -> IdeResult<()>
|
||||
"completion columns differ from catalog",
|
||||
)?;
|
||||
}
|
||||
let plan = db.explain("clickhouse", &format!("SELECT id FROM {table}"), &cancel).await?;
|
||||
let plan = db.explain("clickhouse", &format!("SELECT id FROM {table}"), &cancel, None).await?;
|
||||
check(!plan.is_empty(), "query plan missing")?;
|
||||
let value = r"path\O'Brien";
|
||||
let result = db
|
||||
|
||||
@@ -85,3 +85,101 @@ async fn metadata_names_are_text_whatever_the_column_collation() -> IdeResult<()
|
||||
let raw = manager(&tmp, "SET character_set_results = binary").await.unwrap();
|
||||
assert_metadata_is_text(&raw).await
|
||||
}
|
||||
|
||||
// A console's active schema: the connection that runs each autocommit statement
|
||||
// is put in it first, so unqualified names resolve there (and not elsewhere).
|
||||
// Its own schema names: tests of this file share one server but run in parallel.
|
||||
#[tokio::test]
|
||||
async fn active_schema_context_drives_the_executing_connection() -> IdeResult<()> {
|
||||
const A: &str = "oi_ctx_meta";
|
||||
const B: &str = "oi_ctx_data";
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
for s in [A, B] {
|
||||
for stmt in [
|
||||
format!("DROP DATABASE IF EXISTS `{s}`"),
|
||||
format!("CREATE DATABASE `{s}` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"),
|
||||
format!("CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20))"),
|
||||
format!("INSERT INTO `{s}`.`用户` VALUES (1, '{s}')"),
|
||||
] {
|
||||
db.execute("m", &stmt, 10, &c).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
// The source connects with no default database; the console's pick decides.
|
||||
let r = db.execute_from("m", "SELECT DATABASE()", 0, 1, &c, Some(A)).await?;
|
||||
assert_eq!(r.rows, vec![vec![Some(A.into())]]);
|
||||
// Both schemas hold `用户`; the context resolves the unqualified name in its own,
|
||||
// on every pooled connection the autocommit statements may land on.
|
||||
for _ in 0..6 {
|
||||
for (schema, name) in [(A, A), (B, B)] {
|
||||
let r = db.execute_from("m", "SELECT name FROM 用户", 0, 1, &c, Some(schema)).await?;
|
||||
assert_eq!(r.rows, vec![vec![Some(name.into())]], "of {schema}");
|
||||
let r = db.execute_from("m", "SELECT DATABASE()", 0, 1, &c, Some("")).await?;
|
||||
assert_eq!(r.rows, vec![vec![None]]);
|
||||
assert_eq!(db.completion("m").await?.default_schema, "");
|
||||
}
|
||||
}
|
||||
// A statement without a selection returns to the source's absent default.
|
||||
let r = db.execute_from("m", "SELECT DATABASE()", 0, 1, &c, None).await?;
|
||||
assert_eq!(r.rows, vec![vec![None]]);
|
||||
|
||||
// A manual-commit console switches schemas on its session connection.
|
||||
db.set_manual_commit("m", true).await?;
|
||||
// Starting a no-database manual session must keep its transaction open.
|
||||
db.execute("m", &format!("INSERT INTO `{A}`.`用户` VALUES (2, 'rollback')"), 1, &c).await?;
|
||||
db.finish_transaction("m", false).await?;
|
||||
assert!(db.execute("m", &format!("SELECT name FROM `{A}`.`用户` WHERE id = 2"), 1, &c).await?.rows.is_empty());
|
||||
let r = db.execute_from("m", "SELECT name FROM 用户", 0, 1, &c, Some(A)).await?;
|
||||
assert_eq!(r.rows, vec![vec![Some(A.into())]]);
|
||||
let r = db.execute_from("m", "SELECT DATABASE()", 0, 1, &c, Some(B)).await?;
|
||||
assert_eq!(r.rows, vec![vec![Some(B.into())]]);
|
||||
assert!(db.execute("m", "SELECT DATABASE()", 1, &c).await.is_err());
|
||||
// The rejected clear keeps the transaction and selection intact.
|
||||
assert_eq!(db.execute_from("m", "SELECT DATABASE()", 0, 1, &c, Some(B)).await?.rows, vec![vec![Some(B.into())]]);
|
||||
db.finish_transaction("m", true).await?;
|
||||
for commit in [false, true] {
|
||||
db.execute_from("m", "SELECT 1", 0, 1, &c, Some(A)).await?;
|
||||
db.finish_transaction("m", commit).await?;
|
||||
let r = db.execute("m", "SELECT DATABASE()", 1, &c).await?;
|
||||
assert_eq!(r.rows, vec![vec![None]]);
|
||||
}
|
||||
db.execute_from("m", "SELECT 1", 0, 1, &c, Some(A)).await?;
|
||||
db.set_manual_commit("m", false).await?;
|
||||
db.execute("m", &format!("USE `{B}`"), 1, &c).await?;
|
||||
let r = db.execute("m", "SELECT DATABASE()", 1, &c).await?;
|
||||
assert_eq!(r.rows, vec![vec![None]]);
|
||||
|
||||
// An unknown schema fails the statement instead of running it somewhere else.
|
||||
let error = db.execute_from("m", "SELECT 1", 0, 1, &c, Some("oi_missing")).await.unwrap_err();
|
||||
assert!(error.message.contains("oi_missing"), "{}", error.message);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_reused_physical_connection_restores_the_configured_database() -> IdeResult<()> {
|
||||
use ide_db::{Held, Pool};
|
||||
let Some((host, port, user, password)) = server() else { return Ok(()) };
|
||||
let source = DataSource {
|
||||
driver: DbDriver::Mysql,
|
||||
host,
|
||||
port: Some(port),
|
||||
user,
|
||||
database: "mysql".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let pool = Pool::connect(&source, Some(&password), None).await?;
|
||||
let c = CancellationToken::new();
|
||||
let _other = [Held::acquire(&pool).await?, Held::acquire(&pool).await?, Held::acquire(&pool).await?];
|
||||
let mut conn = Held::acquire(&pool).await?;
|
||||
let backend = conn.execute(&pool, "SELECT CONNECTION_ID()", 1, &c).await?.rows;
|
||||
for schema in ["information_schema", "mysql", "information_schema"] {
|
||||
conn.apply_context(Some(schema)).await?;
|
||||
assert_eq!(conn.execute(&pool, "SELECT DATABASE()", 1, &c).await?.rows, vec![vec![Some(schema.into())]]);
|
||||
}
|
||||
drop(conn);
|
||||
assert_eq!(pool.rows("SELECT DATABASE()", 1).await?, vec![vec![Some("mysql".into())]]);
|
||||
assert_eq!(pool.execute("SELECT CONNECTION_ID()", 1, &c).await?.rows, backend);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
//! The active schema context against a real PostgreSQL server, skipped unless
|
||||
//! `OPENIDEA_TEST_POSTGRES=host:port:user:password` names a throwaway server.
|
||||
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{DataSource, DbDriver, DbManager};
|
||||
|
||||
fn server() -> Option<(String, u16, String, String)> {
|
||||
let v = std::env::var("OPENIDEA_TEST_POSTGRES").ok()?;
|
||||
let mut it = v.splitn(4, ':');
|
||||
Some((it.next()?.into(), it.next()?.parse().ok()?, it.next()?.into(), it.next().unwrap_or("").into()))
|
||||
}
|
||||
|
||||
async fn manager(tmp: &tempfile::TempDir) -> 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")));
|
||||
let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
db.save_sources(vec![DataSource {
|
||||
id: "p".into(),
|
||||
name: "postgres".into(),
|
||||
driver: DbDriver::Postgres,
|
||||
host,
|
||||
port: Some(port),
|
||||
user,
|
||||
..Default::default()
|
||||
}])
|
||||
.await
|
||||
.unwrap();
|
||||
db.set_password("p", Some(password), false).await.unwrap();
|
||||
Some(db)
|
||||
}
|
||||
|
||||
async fn create_schemas(db: &DbManager) {
|
||||
let c = CancellationToken::new();
|
||||
for (schema, tag) in [("oi_a", "from a"), ("oi_b", "from b")] {
|
||||
for stmt in [
|
||||
format!("DROP SCHEMA IF EXISTS \"{schema}\" CASCADE"),
|
||||
format!("CREATE SCHEMA \"{schema}\""),
|
||||
format!("CREATE TABLE \"{schema}\".items (id INT PRIMARY KEY, tag TEXT)"),
|
||||
format!("INSERT INTO \"{schema}\".items VALUES (1, '{tag}')"),
|
||||
] {
|
||||
db.execute("p", &stmt, 10, &c).await.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn active_schema_context_drives_the_executing_connection() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
create_schemas(&db).await;
|
||||
let c = CancellationToken::new();
|
||||
|
||||
// The connection default stays untouched before any console picks a schema.
|
||||
let r = db.execute("p", "SHOW search_path", 1, &c).await?;
|
||||
assert!(r.rows[0][0].as_deref().unwrap_or("").contains("public"), "{:?}", r.rows);
|
||||
|
||||
// Both schemas hold `items`; the context resolves the unqualified name in its own,
|
||||
// on every pooled connection the autocommit statements may land on.
|
||||
for _ in 0..6 {
|
||||
for (schema, tag) in [("oi_a", "from a"), ("oi_b", "from b")] {
|
||||
let r = db.execute_from("p", "SELECT tag FROM items", 0, 1, &c, Some(schema)).await?;
|
||||
assert_eq!(r.rows, vec![vec![Some(tag.into())]], "of {schema}");
|
||||
let r = db.execute_from("p", "SHOW search_path", 0, 1, &c, Some("")).await?;
|
||||
assert_eq!(r.rows, vec![vec![Some("\"$user\", public".into())]]);
|
||||
assert_eq!(db.completion("p").await?.default_schema, "public");
|
||||
}
|
||||
}
|
||||
|
||||
// A manual-commit console switches schemas on its session connection.
|
||||
db.set_manual_commit("p", true).await?;
|
||||
let r = db.execute_from("p", "SELECT tag FROM items", 0, 1, &c, Some("oi_a")).await?;
|
||||
assert_eq!(r.rows, vec![vec![Some("from a".into())]]);
|
||||
let r = db.execute_from("p", "SELECT tag FROM items", 0, 1, &c, Some("oi_b")).await?;
|
||||
assert_eq!(r.rows, vec![vec![Some("from b".into())]]);
|
||||
db.finish_transaction("p", true).await?;
|
||||
for commit in [false, true] {
|
||||
db.execute_from("p", "SELECT 1", 0, 1, &c, Some("oi_a")).await?;
|
||||
db.finish_transaction("p", commit).await?;
|
||||
let r = db.execute("p", "SHOW search_path", 1, &c).await?;
|
||||
assert_eq!(r.rows, vec![vec![Some("\"$user\", public".into())]]);
|
||||
}
|
||||
db.set_manual_commit("p", false).await?;
|
||||
db.execute("p", "SET search_path TO oi_b", 1, &c).await?;
|
||||
let r = db.execute("p", "SHOW search_path", 1, &c).await?;
|
||||
assert_eq!(r.rows, vec![vec![Some("\"$user\", public".into())]]);
|
||||
|
||||
// An unknown schema never resolves the statement's tables (`SET search_path`
|
||||
// itself does not validate names; resolution against it does).
|
||||
let error = db.execute_from("p", "SELECT tag FROM items", 0, 1, &c, Some("oi_missing")).await.unwrap_err();
|
||||
assert!(error.message.to_lowercase().contains("does not exist"), "{}", error.message);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_reused_physical_connection_restores_the_full_default_path() -> IdeResult<()> {
|
||||
use ide_db::{DbOptions, Held, Pool};
|
||||
let Some((host, port, user, password)) = server() else { return Ok(()) };
|
||||
let source = DataSource {
|
||||
driver: DbDriver::Postgres,
|
||||
host,
|
||||
port: Some(port),
|
||||
user,
|
||||
options: DbOptions { default_schema: "public, pg_catalog".into(), ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
let pool = Pool::connect(&source, Some(&password), None).await?;
|
||||
let c = CancellationToken::new();
|
||||
// Occupy the other three slots: every operation below must reuse the fourth.
|
||||
let _other = [Held::acquire(&pool).await?, Held::acquire(&pool).await?, Held::acquire(&pool).await?];
|
||||
let mut conn = Held::acquire(&pool).await?;
|
||||
let backend = conn.execute(&pool, "SELECT pg_backend_pid()", 1, &c).await?.rows;
|
||||
for schema in ["pg_catalog", "public", "pg_catalog"] {
|
||||
conn.apply_context(Some(schema)).await?;
|
||||
let r = conn.execute(&pool, "SELECT current_schema()", 1, &c).await?;
|
||||
assert_eq!(r.rows, vec![vec![Some(schema.into())]]);
|
||||
}
|
||||
conn.apply_context(Some("public")).await?;
|
||||
conn.execute(&pool, "SELECT set_config('search_path', 'pg_catalog', false)", 1, &c).await?;
|
||||
conn.apply_context(Some("public")).await?;
|
||||
assert_eq!(conn.execute(&pool, "SELECT current_schema()", 1, &c).await?.rows, vec![vec![Some("public".into())]]);
|
||||
drop(conn);
|
||||
assert_eq!(pool.rows("SHOW search_path", 1).await?, vec![vec![Some("public, pg_catalog".into())]]);
|
||||
assert_eq!(pool.execute("SELECT pg_backend_pid()", 1, &c).await?.rows, backend);
|
||||
let mut conn = Held::acquire(&pool).await?;
|
||||
conn.command("BEGIN").await?;
|
||||
conn.apply_context(Some("pg_catalog")).await?;
|
||||
conn.command("ROLLBACK").await?;
|
||||
conn.restore_default().await?;
|
||||
assert_eq!(
|
||||
conn.execute(&pool, "SHOW search_path", 1, &c).await?.rows,
|
||||
vec![vec![Some("public, pg_catalog".into())]]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -132,16 +132,16 @@ async fn a_later_page_returns_only_its_rows() -> IdeResult<()> {
|
||||
let sql = "SELECT id FROM users ORDER BY id";
|
||||
let ids = |r: &QueryResult| r.rows.iter().map(|row| row[0].clone().unwrap()).collect::<Vec<_>>();
|
||||
|
||||
let second = db.execute_from("s1", sql, 1, 1, &c).await?;
|
||||
let second = db.execute_from("s1", sql, 1, 1, &c, None).await?;
|
||||
assert_eq!(ids(&second), vec!["2"]);
|
||||
assert!(second.has_more);
|
||||
assert_eq!(second.columns.len(), 1);
|
||||
|
||||
let last = db.execute_from("s1", sql, 2, 5, &c).await?;
|
||||
let last = db.execute_from("s1", sql, 2, 5, &c, None).await?;
|
||||
assert_eq!(ids(&last), vec!["3"]);
|
||||
assert!(!last.has_more);
|
||||
|
||||
let past = db.execute_from("s1", sql, 9, 5, &c).await?;
|
||||
let past = db.execute_from("s1", sql, 9, 5, &c, None).await?;
|
||||
assert!(past.rows.is_empty() && !past.has_more);
|
||||
assert_eq!(past.columns.len(), 1, "columns of a page past the end come from the prepared statement");
|
||||
Ok(())
|
||||
@@ -276,11 +276,11 @@ async fn ddl_of_tables_and_views() -> IdeResult<()> {
|
||||
async fn explains_queries_without_running_them() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
let c = CancellationToken::new();
|
||||
let plan = db.explain("s1", "SELECT * FROM users WHERE id > 1 ORDER BY note;", &c).await?;
|
||||
let plan = db.explain("s1", "SELECT * FROM users WHERE id > 1 ORDER BY note;", &c, None).await?;
|
||||
let ops: Vec<_> = plan.iter().map(|n| n.operation.as_str()).collect();
|
||||
assert_eq!(ops, vec!["Index Scan", "Order By"]);
|
||||
assert!(plan[0].params.starts_with("table: users;"), "{}", plan[0].params);
|
||||
db.explain("s1", "DELETE FROM users", &c).await?;
|
||||
db.explain("s1", "DELETE FROM users", &c, None).await?;
|
||||
assert_eq!(count(&db).await, "3");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -443,7 +443,7 @@ pub fn compose_op(
|
||||
|
||||
/// Whether `ep` is a daemon on this machine, where a bind mount of the project
|
||||
/// is this machine's folder. The CLI's default daemon and a context are looked
|
||||
/// up (`DOCKER_HOST`, else the context's endpoint).
|
||||
/// up (`DOCKER_CONTEXT`, then `DOCKER_HOST`, else the current context).
|
||||
pub fn endpoint_is_local(ep: &DockerEndpoint) -> IdeResult<bool> {
|
||||
let url = match ep {
|
||||
DockerEndpoint::Socket { path } => path.trim().to_owned(),
|
||||
@@ -451,17 +451,31 @@ pub fn endpoint_is_local(ep: &DockerEndpoint) -> IdeResult<bool> {
|
||||
let host = host.trim();
|
||||
if host.contains("://") { host.to_owned() } else { format!("tcp://{host}") }
|
||||
}
|
||||
DockerEndpoint::Default => {
|
||||
match ide_core::process::host_var_os("DOCKER_HOST").map(|v| v.to_string_lossy().trim().to_owned()) {
|
||||
Some(url) if !url.is_empty() => url,
|
||||
_ => context_host(ep, None)?,
|
||||
}
|
||||
}
|
||||
DockerEndpoint::Default => 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),
|
||||
)?,
|
||||
DockerEndpoint::Context { name } => context_host(&DockerEndpoint::Default, Some(name.trim()))?,
|
||||
};
|
||||
Ok(daemon_url_is_local(&url))
|
||||
}
|
||||
|
||||
fn default_daemon_url(
|
||||
context: Option<&str>,
|
||||
host: Option<&str>,
|
||||
lookup: impl FnOnce(Option<&str>) -> IdeResult<String>,
|
||||
) -> IdeResult<String> {
|
||||
let context = context.filter(|v| !v.is_empty());
|
||||
if context.is_some() {
|
||||
return lookup(context);
|
||||
}
|
||||
match host.filter(|v| !v.is_empty()) {
|
||||
Some(host) => Ok(host.to_owned()),
|
||||
None => lookup(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The daemon URL of context `name` (the current one with `None`).
|
||||
fn context_host(ep: &DockerEndpoint, name: Option<&str>) -> IdeResult<String> {
|
||||
let mut args = vec!["context", "inspect", "--format", "{{.Endpoints.docker.Host}}"];
|
||||
@@ -506,6 +520,34 @@ pub fn compose_config(ep: &DockerEndpoint, dir: &Path, files: &[String]) -> IdeR
|
||||
mod local_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_selected_context_overrides_docker_host() {
|
||||
let local = "unix:///var/run/docker.sock";
|
||||
let remote = "ssh://me@build";
|
||||
for host in [None, Some(""), Some(local)] {
|
||||
let url = default_daemon_url(Some("build"), host, |name| {
|
||||
assert_eq!(name, Some("build"));
|
||||
Ok(remote.into())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(!daemon_url_is_local(&url));
|
||||
}
|
||||
for context in [None, Some("")] {
|
||||
assert_eq!(
|
||||
default_daemon_url(context, Some(local), |_| panic!("host overrides current context")).unwrap(),
|
||||
local
|
||||
);
|
||||
assert_eq!(
|
||||
default_daemon_url(context, None, |name| {
|
||||
assert_eq!(name, None);
|
||||
Ok(remote.into())
|
||||
})
|
||||
.unwrap(),
|
||||
remote
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_daemon_urls() {
|
||||
for url in [
|
||||
|
||||
@@ -18,6 +18,8 @@ pub enum Capability {
|
||||
EditorRead,
|
||||
/// Edit the focused editor (versioned edits).
|
||||
EditorWrite,
|
||||
/// Create and replace files inside the project root.
|
||||
ProjectWrite,
|
||||
VcsRead,
|
||||
VcsWrite,
|
||||
/// The plugin's own key-value store and data directory.
|
||||
@@ -36,6 +38,8 @@ pub enum Capability {
|
||||
Process(String),
|
||||
/// Read files outside the project under one path.
|
||||
FsRead(String),
|
||||
/// Write files outside the project under one path.
|
||||
FsWrite(String),
|
||||
}
|
||||
|
||||
/// How a grant is presented (plan 4.2).
|
||||
@@ -54,10 +58,14 @@ impl Capability {
|
||||
pub fn risk(&self) -> Risk {
|
||||
match self {
|
||||
Self::ProjectRead | Self::EditorRead | Self::Storage | Self::Events | Self::VcsRead => Risk::Low,
|
||||
Self::EditorWrite | Self::VcsWrite | Self::Net(_) | Self::Secrets | Self::InputEvents | Self::Clipboard => {
|
||||
Risk::Medium
|
||||
}
|
||||
Self::Process(_) | Self::FsRead(_) => Risk::High,
|
||||
Self::EditorWrite
|
||||
| Self::ProjectWrite
|
||||
| Self::VcsWrite
|
||||
| Self::Net(_)
|
||||
| Self::Secrets
|
||||
| Self::InputEvents
|
||||
| Self::Clipboard => Risk::Medium,
|
||||
Self::Process(_) | Self::FsRead(_) | Self::FsWrite(_) => Risk::High,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,6 +81,7 @@ impl Capability {
|
||||
Self::ProjectRead => "Read files in the open project".into(),
|
||||
Self::EditorRead => "Read the focused editor's file and selection".into(),
|
||||
Self::EditorWrite => "Change text in the editor".into(),
|
||||
Self::ProjectWrite => "Create and change files in the open project".into(),
|
||||
Self::VcsRead => "Read version control state".into(),
|
||||
Self::VcsWrite => "Change version control state (commit, fetch, checkout)".into(),
|
||||
Self::Storage => "Store its own data".into(),
|
||||
@@ -85,6 +94,7 @@ impl Capability {
|
||||
Self::Net(host) => format!("Connect to {host} (from the machine the project is on)"),
|
||||
Self::Process(bin) => format!("Run {bin} — equivalent to running arbitrary code on this machine"),
|
||||
Self::FsRead(path) => format!("Read files under {path}, outside the project"),
|
||||
Self::FsWrite(path) => format!("Change files under {path}, outside the project"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,7 +102,7 @@ impl Capability {
|
||||
pub fn covers(&self, wanted: &Capability) -> bool {
|
||||
match (self, wanted) {
|
||||
(Self::Net(pattern), Self::Net(host)) => host_matches(pattern, host),
|
||||
(Self::FsRead(base), Self::FsRead(path)) => {
|
||||
(Self::FsRead(base), Self::FsRead(path)) | (Self::FsWrite(base), Self::FsWrite(path)) => {
|
||||
std::path::Path::new(path).starts_with(std::path::Path::new(base))
|
||||
}
|
||||
_ => self == wanted,
|
||||
@@ -116,6 +126,7 @@ impl fmt::Display for Capability {
|
||||
Self::ProjectRead => f.write_str("project.read"),
|
||||
Self::EditorRead => f.write_str("editor.read"),
|
||||
Self::EditorWrite => f.write_str("editor.write"),
|
||||
Self::ProjectWrite => f.write_str("project.write"),
|
||||
Self::VcsRead => f.write_str("vcs.read"),
|
||||
Self::VcsWrite => f.write_str("vcs.write"),
|
||||
Self::Storage => f.write_str("storage"),
|
||||
@@ -126,6 +137,7 @@ impl fmt::Display for Capability {
|
||||
Self::Net(h) => write!(f, "net:{h}"),
|
||||
Self::Process(b) => write!(f, "process:{b}"),
|
||||
Self::FsRead(p) => write!(f, "fs.read:{p}"),
|
||||
Self::FsWrite(p) => write!(f, "fs.write:{p}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -158,11 +170,11 @@ impl FromStr for Capability {
|
||||
}
|
||||
Ok(Self::Process(arg.to_owned()))
|
||||
}
|
||||
"fs.read" => {
|
||||
"fs.read" | "fs.write" => {
|
||||
if !std::path::Path::new(arg).is_absolute() && !arg.starts_with('~') {
|
||||
return Err(format!("{s:?}: use an absolute path (or ~/…)"));
|
||||
}
|
||||
Ok(Self::FsRead(arg.to_owned()))
|
||||
Ok(if kind == "fs.read" { Self::FsRead(arg.to_owned()) } else { Self::FsWrite(arg.to_owned()) })
|
||||
}
|
||||
_ => Err(format!("unknown capability {s:?}")),
|
||||
};
|
||||
@@ -171,6 +183,7 @@ impl FromStr for Capability {
|
||||
"project.read" | "project-read" => Self::ProjectRead,
|
||||
"editor.read" | "editor-read" => Self::EditorRead,
|
||||
"editor.write" | "editor-write" => Self::EditorWrite,
|
||||
"project.write" => Self::ProjectWrite,
|
||||
"vcs.read" => Self::VcsRead,
|
||||
"vcs.write" => Self::VcsWrite,
|
||||
"storage" => Self::Storage,
|
||||
@@ -224,6 +237,7 @@ mod tests {
|
||||
for s in [
|
||||
"project.read",
|
||||
"editor.write",
|
||||
"project.write",
|
||||
"vcs.write",
|
||||
"storage",
|
||||
"secrets",
|
||||
@@ -236,12 +250,12 @@ mod tests {
|
||||
assert_eq!(s.parse::<Capability>().unwrap().to_string(), s);
|
||||
}
|
||||
// Absolute paths are the platform's.
|
||||
let (git, etc) = if cfg!(windows) {
|
||||
(r"process:C:\Program Files\Git\bin\git.exe", r"fs.read:C:\Windows")
|
||||
let (git, etc, out) = if cfg!(windows) {
|
||||
(r"process:C:\Program Files\Git\bin\git.exe", r"fs.read:C:\Windows", r"fs.write:C:\out")
|
||||
} else {
|
||||
("process:/usr/bin/git", "fs.read:/etc")
|
||||
("process:/usr/bin/git", "fs.read:/etc", "fs.write:/out")
|
||||
};
|
||||
for s in [git, etc] {
|
||||
for s in [git, etc, out] {
|
||||
assert_eq!(s.parse::<Capability>().unwrap().to_string(), s);
|
||||
}
|
||||
assert_eq!("project-read".parse::<Capability>().unwrap(), Capability::ProjectRead);
|
||||
@@ -249,6 +263,7 @@ mod tests {
|
||||
assert!("net:a b".parse::<Capability>().is_err());
|
||||
assert!("process:./evil".parse::<Capability>().is_err());
|
||||
assert!("fs.read:rel".parse::<Capability>().is_err());
|
||||
assert!("fs.write:rel".parse::<Capability>().is_err());
|
||||
assert!("network".parse::<Capability>().is_err());
|
||||
}
|
||||
|
||||
|
||||
@@ -308,6 +308,13 @@ pub fn by_risk(caps: &[Capability]) -> Vec<(Risk, Vec<Capability>)> {
|
||||
|
||||
/// Resolves a `process:` program to an absolute path once, at grant time:
|
||||
/// absolute names are taken as is, others are looked up in `path_var`.
|
||||
/// The directory is canonicalized but the file name kept as found: `cargo`,
|
||||
/// `rustc` and friends are often links to a multicall shim (rustup, asdf,
|
||||
/// mise) that picks the tool by the name it was invoked under — resolving the
|
||||
/// link itself would start the shim with the tool's arguments. The grant
|
||||
/// still pins the target's content: a hash read through a link reads the file
|
||||
/// it points to, so relinking or replacing either still fails the
|
||||
/// approved-file check.
|
||||
pub fn resolve_program(name: &str, path_var: Option<&OsStr>) -> Result<PathBuf, String> {
|
||||
let candidate = Path::new(name);
|
||||
if candidate.is_absolute() {
|
||||
@@ -325,15 +332,21 @@ pub fn resolve_program(name: &str, path_var: Option<&OsStr>) -> Result<PathBuf,
|
||||
for ext in &exts {
|
||||
let p = dir.join(format!("{name}{ext}"));
|
||||
if is_executable(&p) {
|
||||
return Ok(dunce_canonical(&p));
|
||||
return Ok(canonical_dir(&p));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(format!("{name} was not found on PATH"))
|
||||
}
|
||||
|
||||
fn dunce_canonical(p: &Path) -> PathBuf {
|
||||
std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf())
|
||||
/// `p` with its parent canonicalized but the file name as found: PATH
|
||||
/// entries like `/var` → `/private/var` (macOS) or `~` links collapse to
|
||||
/// their real directory, while a linked program (`cargo` → rustup) keeps
|
||||
/// its link name so the shim still dispatches on argv[0].
|
||||
fn canonical_dir(p: &Path) -> PathBuf {
|
||||
let Some(dir) = p.parent() else { return p.to_path_buf() };
|
||||
let Some(name) = p.file_name() else { return p.to_path_buf() };
|
||||
std::fs::canonicalize(dir).map(|d| d.join(name)).unwrap_or_else(|_| p.to_path_buf())
|
||||
}
|
||||
|
||||
fn is_executable(p: &Path) -> bool {
|
||||
@@ -474,6 +487,42 @@ mod tests {
|
||||
assert!(l.check_binary(&r.subject, &cap).unwrap_err().contains("changed"));
|
||||
}
|
||||
|
||||
/// A program found as a link stays the link: multicall shims (rustup,
|
||||
/// asdf, mise) pick the tool by the name they were invoked under, so
|
||||
/// `Command::new` must see the link. The hash still covers the target —
|
||||
/// reading through the link reads it — so replacing either still trips
|
||||
/// the approved-file check.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn linked_programs_resolve_to_the_link() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let bin_dir = tmp.path().join("bin");
|
||||
let real_dir = tmp.path().join("real");
|
||||
std::fs::create_dir(&bin_dir).unwrap();
|
||||
std::fs::create_dir(&real_dir).unwrap();
|
||||
let target = real_dir.join("shim");
|
||||
std::fs::write(&target, "#!/bin/sh\necho v1\n").unwrap();
|
||||
std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
std::os::unix::fs::symlink(&target, bin_dir.join("cargo")).unwrap();
|
||||
|
||||
let path_var = std::env::join_paths([bin_dir.clone()]).unwrap();
|
||||
let resolved = resolve_program("cargo", Some(&path_var)).unwrap();
|
||||
// Directory canonicalized, file name kept — still the link.
|
||||
let want = std::fs::canonicalize(&bin_dir).unwrap().join("cargo");
|
||||
assert_eq!(resolved, want);
|
||||
assert!(resolved.symlink_metadata().unwrap().file_type().is_symlink());
|
||||
|
||||
let mut l = Ledger::in_memory();
|
||||
let r = req("1.0.0", "h", &["process:cargo"], &[]);
|
||||
let cap: Capability = "process:cargo".parse().unwrap();
|
||||
let bin = BinaryGrant { path: resolved.clone(), hash: file_hash(&resolved).unwrap() };
|
||||
l.confirm(&r, &[], [(cap.to_string(), bin)].into());
|
||||
assert_eq!(l.check_binary(&r.subject, &cap).unwrap(), resolved);
|
||||
std::fs::write(&target, "#!/bin/sh\necho evil\n").unwrap();
|
||||
assert!(l.check_binary(&r.subject, &cap).unwrap_err().contains("changed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hashes_and_grouping() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -31,6 +31,6 @@ pub use manifest::{
|
||||
Manifest, check_relative, engine_compatible, validate_item_id, validate_plugin_id, validate_point_id,
|
||||
};
|
||||
pub use point::{Commit, Disposable, ExtensionPoint, MAX_PACKAGE_FILE, Package, Placement, Prepared, decode};
|
||||
pub use registry::{ContributionInfo, ExtensionRegistry, PreparedSet};
|
||||
pub use registry::{ContributionInfo, ExtensionRegistry, LOCALES_DIR, LOCALES_POINT, PreparedSet};
|
||||
pub use ui::{UiContribution, UiDecl, UiPoint, UiStore, to_json};
|
||||
pub use when::validate_when;
|
||||
@@ -32,7 +32,7 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MANIFEST_FILE: &str = "plugin.toml";
|
||||
/// The plugin API (engine) version this host implements.
|
||||
pub const ENGINE_VERSION: &str = "1.2.0";
|
||||
pub const ENGINE_VERSION: &str = "1.3.0";
|
||||
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
|
||||
pub const LEGACY_API: &str = "0.1";
|
||||
/// Marketplace categories, in the order they are shown.
|
||||
@@ -54,6 +54,10 @@ pub struct Manifest {
|
||||
pub change_notes: Option<String>,
|
||||
/// Marketplace categories as declared (see [`Manifest::categories`]).
|
||||
pub declared_categories: Vec<String>,
|
||||
/// SVG shown in Settings › Plugins and the marketplace.
|
||||
pub icon: Option<PathBuf>,
|
||||
/// Its variant for dark themes.
|
||||
pub icon_dark: Option<PathBuf>,
|
||||
/// `engines.openidea` (a semver requirement), or the legacy `openidea-api`.
|
||||
pub engine: String,
|
||||
/// Written in the 0.1 format.
|
||||
@@ -175,6 +179,10 @@ struct Raw {
|
||||
#[serde(default)]
|
||||
categories: Vec<String>,
|
||||
#[serde(default)]
|
||||
icon: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
icon_dark: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
engines: Option<Engines>,
|
||||
/// 0.1 format.
|
||||
#[serde(default)]
|
||||
@@ -253,6 +261,8 @@ impl Manifest {
|
||||
license: raw.license,
|
||||
change_notes: raw.change_notes,
|
||||
declared_categories: raw.categories,
|
||||
icon: raw.icon,
|
||||
icon_dark: raw.icon_dark,
|
||||
engine,
|
||||
legacy,
|
||||
wasm: raw.wasm,
|
||||
@@ -270,6 +280,16 @@ impl Manifest {
|
||||
Self::parse(&src).map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// Refuses `what`, new in plugin API 1.`minor`, while `engines.openidea`
|
||||
/// still admits an older 1.x: those IDEs reject the manifest at install.
|
||||
pub fn needs_api(&self, what: &str, minor: u64) -> Result<(), String> {
|
||||
let older = |m| engine_compatible_with(&self.engine, &semver::Version::new(1, m, u64::MAX));
|
||||
if self.legacy || (0..minor).any(older) {
|
||||
return Err(format!("{what} is new in plugin API 1.{minor}: set engines.openidea to \"^1.{minor}\""));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate(&self) -> Result<(), String> {
|
||||
validate_plugin_id(&self.id)?;
|
||||
if self.name.trim().is_empty() {
|
||||
@@ -291,6 +311,21 @@ impl Manifest {
|
||||
if let Some(wasm) = &self.wasm {
|
||||
check_relative(wasm, "wasm")?;
|
||||
}
|
||||
if let Some(icon) = &self.icon {
|
||||
self.needs_api("`icon`", 2)?;
|
||||
check_relative(icon, "icon")?;
|
||||
}
|
||||
for cap in self.capabilities.required.iter().chain(&self.capabilities.optional) {
|
||||
if matches!(cap, Capability::ProjectWrite | Capability::FsWrite(_)) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 3)?;
|
||||
}
|
||||
}
|
||||
if let Some(dark) = &self.icon_dark {
|
||||
if self.icon.is_none() {
|
||||
return Err("`icon-dark` needs `icon`".into());
|
||||
}
|
||||
check_relative(dark, "icon-dark")?;
|
||||
}
|
||||
if self.wasm.is_none() && !self.activation.is_empty() {
|
||||
return Err("`activation` needs `wasm`: there is no code to activate".into());
|
||||
}
|
||||
@@ -376,9 +411,11 @@ pub fn engine_compatible(engine: &str, legacy: bool) -> bool {
|
||||
if legacy {
|
||||
return engine == LEGACY_API || engine.strip_prefix(LEGACY_API).is_some_and(|rest| rest.starts_with('.'));
|
||||
}
|
||||
let Ok(req) = semver::VersionReq::parse(engine) else { return false };
|
||||
let host = semver::Version::parse(ENGINE_VERSION).expect("valid engine version");
|
||||
req.matches(&host)
|
||||
engine_compatible_with(engine, &semver::Version::parse(ENGINE_VERSION).expect("valid engine version"))
|
||||
}
|
||||
|
||||
fn engine_compatible_with(engine: &str, api: &semver::Version) -> bool {
|
||||
semver::VersionReq::parse(engine).is_ok_and(|req| req.matches(api))
|
||||
}
|
||||
|
||||
/// Segments of `[a-z0-9][a-z0-9_-]*` joined by `.` (an optional publisher
|
||||
@@ -549,6 +586,38 @@ mod tests {
|
||||
assert!(err("id = \"ok\"\nname = \"N\"\nversion = \"1.0\"\nengines.openidea = \"^1.0\"").contains("version"));
|
||||
}
|
||||
|
||||
const BASE: &str = "id = \"ok\"\nname = \"N\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.2\"\n";
|
||||
|
||||
#[test]
|
||||
fn write_capabilities_need_api_1_3() {
|
||||
for cap in ["project.write", "fs.write:/opt/tool"] {
|
||||
let caps = format!("[capabilities]\noptional = [\"{cap}\"]\n");
|
||||
assert!(err(&format!("{BASE}{caps}")).contains("new in plugin API 1.3"), "{cap}");
|
||||
let m = Manifest::parse(&format!("{}{caps}", BASE.replace("^1.2", "^1.3"))).unwrap();
|
||||
assert_eq!(m.capabilities.optional[0].to_string(), cap);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_icons() {
|
||||
let m = Manifest::parse(&format!("{BASE}icon = \"icon.svg\"\nicon-dark = \"icon_dark.svg\"\n")).unwrap();
|
||||
assert_eq!(m.icon.as_deref(), Some(Path::new("icon.svg")));
|
||||
assert_eq!(m.icon_dark.as_deref(), Some(Path::new("icon_dark.svg")));
|
||||
assert_eq!(Manifest::parse(BASE).unwrap().icon, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_icons() {
|
||||
assert!(err(&format!("{BASE}icon-dark = \"d.svg\"\n")).contains("`icon-dark` needs `icon`"));
|
||||
assert!(err(&format!("{BASE}icon = \"../x.svg\"\n")).contains("icon"));
|
||||
assert!(err(&format!("{BASE}icon = \"/abs.svg\"\n")).contains("icon"));
|
||||
assert!(err(&format!("{BASE}icon = \"i.svg\"\nicon-dark = \"../d.svg\"\n")).contains("icon-dark"));
|
||||
for engine in ["^1.0", ">=1.1, <2"] {
|
||||
let old = BASE.replace("^1.2", engine);
|
||||
assert!(err(&format!("{old}icon = \"i.svg\"\n")).contains("new in plugin API 1.2"), "{engine}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids() {
|
||||
assert!(validate_plugin_id("openidea.material-icons").is_ok());
|
||||
|
||||
@@ -314,6 +314,14 @@ pub struct Endorsement {
|
||||
pub signature: String,
|
||||
}
|
||||
|
||||
/// A plugin's own icon (`icon`, `icon-dark` of its manifest): sanitised SVG markup.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginIcon {
|
||||
pub light: String,
|
||||
pub dark: Option<String>,
|
||||
}
|
||||
|
||||
/// A published plugin version.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -340,6 +348,10 @@ pub struct IndexEntry {
|
||||
/// Marketplace categories (`CATEGORIES`); an IDE ignores those it doesn't know.
|
||||
#[serde(default)]
|
||||
pub categories: Vec<String>,
|
||||
/// The manifest's icon, sanitised by whoever wrote the index and again by
|
||||
/// the IDE before showing it.
|
||||
#[serde(default)]
|
||||
pub icon: Option<PluginIcon>,
|
||||
}
|
||||
|
||||
impl IndexEntry {
|
||||
@@ -672,6 +684,7 @@ mod tests {
|
||||
capabilities: Vec::new(),
|
||||
engine: "^1.0".into(),
|
||||
categories: Vec::new(),
|
||||
icon: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,11 @@ use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The point behind a package's `locales/<tag>.json` catalogs: it has no
|
||||
/// `[[contributes.locales]]` table, the directory declares it.
|
||||
pub const LOCALES_POINT: &str = "locales";
|
||||
pub const LOCALES_DIR: &str = "locales";
|
||||
|
||||
/// A contribution as the plugin details page lists it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -127,6 +132,20 @@ impl ExtensionRegistry {
|
||||
set.items.push((point.id(), prepared));
|
||||
}
|
||||
}
|
||||
if let Some(point) = self.point(LOCALES_POINT)
|
||||
&& !pkg.manifest.contributes.contains_key(LOCALES_POINT)
|
||||
&& pkg.dir.join(LOCALES_DIR).is_dir()
|
||||
{
|
||||
let prepared = point
|
||||
.prepare(pkg, toml::Value::Table(Default::default()))
|
||||
.map_err(|e| format!("{LOCALES_DIR}: {}", strip_prefix(&e, LOCALES_POINT)))?;
|
||||
for f in &prepared.files {
|
||||
if !set.files.contains(f) {
|
||||
set.files.push(f.clone());
|
||||
}
|
||||
}
|
||||
set.items.push((point.id(), prepared));
|
||||
}
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ ide-vfs.workspace = true
|
||||
regex-syntax.workspace = true
|
||||
ide-workspace.workspace = true
|
||||
ide-language.workspace = true
|
||||
blake3.workspace = true
|
||||
ide-index.workspace = true
|
||||
ide-syntax.workspace = true
|
||||
ide-search.workspace = true
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
mod templates;
|
||||
|
||||
use ide_extension::{Manifest, validate_plugin_id};
|
||||
use ide_host::plugins::{PluginHost, read_market_url, resolve_market_href};
|
||||
use ide_host::plugins::{PluginHost, plugin_icon, read_market_url, resolve_market_href};
|
||||
use ide_plugin::{Limits, PluginEngine};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitCode};
|
||||
@@ -650,6 +650,7 @@ fn cmd_index(args: &[String]) -> Result<(), String> {
|
||||
capabilities: m.capabilities.all().map(|c| c.to_string()).collect(),
|
||||
engine: package::engine_requirement(&m.engine, built_for.as_ref()),
|
||||
categories: m.categories(),
|
||||
icon: plugin_icon(&ide_extension::Package::new(m.clone(), scratch.clone()))?,
|
||||
})
|
||||
})();
|
||||
let entry = entry.map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
@@ -812,20 +813,24 @@ mod tests {
|
||||
|
||||
/// A theme package `id` signed by `publisher` with `key`, packed into `out`.
|
||||
fn signed_theme(tmp: &Path, id: &str, publisher: &str, key: &str, out: &Path) {
|
||||
signed_theme_version(tmp, id, "0.1.0", "^1.0", publisher, key, out);
|
||||
signed_theme_version(tmp, id, "0.1.0", "^1.2", publisher, key, out);
|
||||
}
|
||||
|
||||
fn signed_theme_version(tmp: &Path, id: &str, version: &str, engine: &str, publisher: &str, key: &str, out: &Path) {
|
||||
let src = tmp.join("src").join(format!("{id}-{version}"));
|
||||
let vars = templates::Vars { id, name: id, sdk: None };
|
||||
// A manifest icon needs API 1.2.
|
||||
let icon = if engine == "^1.2" { "\nicon = \"icon.svg\"" } else { "" };
|
||||
for (rel, content) in templates::render(templates::Template::Theme, &vars) {
|
||||
let path = src.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let content = content
|
||||
.replace("version = \"0.1.0\"", &format!("version = \"{version}\""))
|
||||
.replace("engines.openidea = \"^1.0\"", &format!("engines.openidea = \"{engine}\""));
|
||||
.replace("engines.openidea = \"^1.0\"", &format!("engines.openidea = \"{engine}\"{icon}"));
|
||||
std::fs::write(path, content).unwrap();
|
||||
}
|
||||
std::fs::write(src.join("icon.svg"), r#"<svg viewBox="0 0 16 16"><rect width="16" height="16"/></svg>"#)
|
||||
.unwrap();
|
||||
std::fs::create_dir_all(out).unwrap();
|
||||
let args = [src.to_str().unwrap(), "--key", key, "--publisher", publisher, "--out"]
|
||||
.into_iter()
|
||||
@@ -921,6 +926,11 @@ mod tests {
|
||||
let listed: Vec<_> = index.plugins.iter().map(|e| (e.id.as_str(), e.publisher.as_str())).collect();
|
||||
assert_eq!(listed, [("alice.dawn", "alice"), ("openidea.night", "openidea")]);
|
||||
assert_eq!(index.plugins[1].categories, ["themes"], "implied by the theme");
|
||||
assert!(
|
||||
index.plugins[1].icon.as_ref().is_some_and(|i| i.light.contains("<rect")),
|
||||
"{:?}",
|
||||
index.plugins[1].icon
|
||||
);
|
||||
assert_eq!(index.plugins[1].download, "openidea.night-0.1.0.oiplugin");
|
||||
assert!(Path::new(&index.plugins[0].download).is_absolute(), "{}", index.plugins[0].download);
|
||||
|
||||
@@ -930,6 +940,34 @@ mod tests {
|
||||
assert!(err.contains("unknown publisher"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_index_carries_plugin_icons() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let t = tmp.path();
|
||||
let key = t.join("acme.key");
|
||||
std::fs::write(&key, PublisherKey::from_seed([6; 32]).seed_base64()).unwrap();
|
||||
let src = t.join("src");
|
||||
let vars = templates::Vars { id: "acme.iconic", name: "Iconic", sdk: None };
|
||||
for (rel, content) in templates::render(templates::Template::Theme, &vars) {
|
||||
let path = src.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, content).unwrap();
|
||||
}
|
||||
let manifest = std::fs::read_to_string(src.join("plugin.toml")).unwrap();
|
||||
let manifest = manifest.replace("engines.openidea = \"^1.0\"", "engines.openidea = \"^1.2\"");
|
||||
std::fs::write(src.join("plugin.toml"), format!("icon = \"icon.svg\"\n{manifest}")).unwrap();
|
||||
std::fs::write(src.join("icon.svg"), r#"<svg viewBox="0 0 16 16"><rect width="16" height="16"/></svg>"#)
|
||||
.unwrap();
|
||||
let out = t.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let (src, key) = (src.to_string_lossy().into_owned(), key.to_string_lossy().into_owned());
|
||||
let package = out.join("acme.iconic-0.1.0.oiplugin").to_string_lossy().into_owned();
|
||||
cmd_pack(&strings(&[&src, "--key", &key, "--publisher", "acme", "--out", &package])).unwrap();
|
||||
cmd_index(&strings(&[out.to_str().unwrap(), "--publisher", "acme", "--key", &key])).unwrap();
|
||||
let index = Index::parse(&std::fs::read_to_string(out.join("index.json")).unwrap()).unwrap();
|
||||
assert!(index.plugins[0].icon.as_ref().expect("icon").light.contains("<rect"));
|
||||
}
|
||||
|
||||
/// `cargo test` of a new Rust plugin (its own tests against the mock host) with this SDK.
|
||||
#[test]
|
||||
fn the_command_template_builds_against_the_sdk() {
|
||||
|
||||
@@ -78,6 +78,11 @@ async fn run(base: PathBuf) -> i32 {
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(root) = std::env::var_os(ide_host::trust::TRUSTED_ROOT_ENV)
|
||||
&& let Err(e) = host.trust.inherit(std::path::Path::new(&root))
|
||||
{
|
||||
tracing::warn!("cannot trust {}: {e}", root.to_string_lossy());
|
||||
}
|
||||
tracing::info!("openidea-server {} ready", env!("CARGO_PKG_VERSION"));
|
||||
let mut dispatcher = Dispatcher::standard();
|
||||
if let Some(plugins) = &plugins {
|
||||
|
||||
@@ -22,6 +22,10 @@ use std::time::Duration;
|
||||
|
||||
type Changes = Vec<(OsString, Option<OsString>)>;
|
||||
|
||||
/// Set by the desktop when the Dev Containers CLI already ran the lifecycle commands
|
||||
/// (`devcontainer up`): the server then doesn't run `postStartCommand` again.
|
||||
pub const LIFECYCLE_DONE_ENV: &str = "OPENIDEA_LIFECYCLE_DONE";
|
||||
|
||||
/// What Reload Environment changed.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -72,7 +76,7 @@ impl Environment {
|
||||
return None;
|
||||
}
|
||||
let config = self.load_project(root, sink);
|
||||
let post_start = config.and_then(|c| c.post_start);
|
||||
let post_start = config.and_then(|c| c.post_start).filter(|_| std::env::var_os(LIFECYCLE_DONE_ENV).is_none());
|
||||
let first = self.state.lock().post_started.insert(root.to_path_buf());
|
||||
post_start.filter(|_| first)
|
||||
}
|
||||
|
||||
@@ -170,8 +170,7 @@ impl KotlinBridge {
|
||||
let settings = self.settings.effective();
|
||||
let has_sources = tokio::task::spawn_blocking(move || {
|
||||
let model = crate::ops::build::load(&root, &cache, &settings);
|
||||
let enabled =
|
||||
model.maven.as_ref().is_some_and(|m| !m.projects.is_empty()) && kotlin_bridge::has_kotlin(&root);
|
||||
let enabled = kotlin_bridge::has_kotlin(&root, &model);
|
||||
(model, enabled)
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -223,6 +223,7 @@ impl Host {
|
||||
self.cancel_request(request);
|
||||
}
|
||||
let project = self.projects.write().remove(window)?;
|
||||
project.plugin_diagnostics.close();
|
||||
if let Some(plugins) = plugins::editor_plugin_host() {
|
||||
plugins.invalidate_client_navigation(&project.root, Some(window), None);
|
||||
plugins.set_active_file(window, None);
|
||||
@@ -248,7 +249,7 @@ impl Host {
|
||||
vec![project.notebooks.clone()],
|
||||
project.kotlin_bridge.iter().cloned().collect(),
|
||||
Some(project.lsp.clone()),
|
||||
Some((self.debugger.clone(), window.to_owned())),
|
||||
Some((self.debugger.clone(), window.to_owned(), project.root.clone())),
|
||||
Some(project),
|
||||
))
|
||||
}
|
||||
@@ -261,7 +262,7 @@ impl Host {
|
||||
notebooks: Vec<Arc<notebook::NotebookService>>,
|
||||
bridges: Vec<Arc<kotlin_bridge::KotlinBridge>>,
|
||||
lsp: Option<Arc<ide_lsp::LspManager>>,
|
||||
debug: Option<(Arc<ide_dap::DebugManager>, String)>,
|
||||
debug: Option<(Arc<ide_dap::DebugManager>, String, std::path::PathBuf)>,
|
||||
retired: Option<Arc<Project>>,
|
||||
) -> std::thread::JoinHandle<()> {
|
||||
for bridge in &bridges {
|
||||
@@ -286,8 +287,9 @@ impl Host {
|
||||
if let Some(lsp) = lsp {
|
||||
lsp.shutdown_all().await;
|
||||
}
|
||||
if let Some((debug, key)) = debug {
|
||||
if let Some((debug, key, root)) = debug {
|
||||
debug.stop_key(&key).await;
|
||||
debug.stop_under(&root).await;
|
||||
}
|
||||
});
|
||||
if let Some(retired) = retired {
|
||||
@@ -349,6 +351,14 @@ impl Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// Called on desktop exit: kills the runs and terminal shells still alive. Closing a
|
||||
/// window stops what it started, but a quit from the Dock, the app menu or a logout
|
||||
/// exits without closing the windows, and the process trees would outlive the app.
|
||||
pub fn stop_processes_on_exit(&self) {
|
||||
self.processes.kill_all();
|
||||
self.terminals.kill_all();
|
||||
}
|
||||
|
||||
/// Called before desktop exit, which may bypass document destructors.
|
||||
pub fn clear_workspace_edit_history_on_exit(&self) {
|
||||
for project in self.projects() {
|
||||
@@ -364,6 +374,7 @@ impl Host {
|
||||
self.terminals.kill_all();
|
||||
let projects: Vec<_> = self.projects.write().drain().map(|(_, p)| p).collect();
|
||||
for project in &projects {
|
||||
project.plugin_diagnostics.close();
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
bridge.stop();
|
||||
}
|
||||
|
||||
@@ -238,6 +238,11 @@ pub fn cancel(host: &Host, window: &str, task: String, subagent: Option<String>)
|
||||
host.project(window)?.agents.cancel(&task, subagent)
|
||||
}
|
||||
|
||||
/// Stops one of the task's background tasks.
|
||||
pub async fn stop_background(host: &Host, window: &str, task: String, background: String) -> IdeResult<()> {
|
||||
host.project(window)?.agents.stop_background(&task, &background).await
|
||||
}
|
||||
|
||||
/// Answers a permission request; `option: None` cancels it.
|
||||
pub fn respond(host: &Host, window: &str, task: String, permission: u32, option: Option<String>) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
@@ -297,6 +302,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("agent_rollback", |c| async move { rollback(&c.host, &c.window, c.arg("task")?, c.arg("turns")?).await });
|
||||
d.add("agent_probe", |c| async move { probe(&c.host, &c.window, c.arg("provider")?, c.arg("refresh")?).await });
|
||||
d.add("agent_cancel", |c| async move { cancel(&c.host, &c.window, c.arg("task")?, c.arg("subagent")?) });
|
||||
d.add("agent_stop_background", |call| async move {
|
||||
stop_background(&call.host, &call.window, call.arg("task")?, call.arg("background")?).await
|
||||
});
|
||||
d.add("agent_respond", |c| async move {
|
||||
respond(&c.host, &c.window, c.arg("task")?, c.arg("permission")?, c.arg("option")?)
|
||||
});
|
||||
|
||||
@@ -5,10 +5,11 @@ use crate::rpc::Dispatcher;
|
||||
use crate::{Host, Project, apply_workspace_edit};
|
||||
|
||||
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
|
||||
use ide_build::maven::PomGoto;
|
||||
use ide_build::pom_edit::{ArtifactKey, Exclusion};
|
||||
use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress};
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::{FileEdit, IdeError, IdeEvent, IdeResult, Location, Range, RequestId, WorkspaceEdit};
|
||||
use ide_core::{FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
@@ -16,14 +17,6 @@ fn join_err(e: tokio::task::JoinError) -> IdeError {
|
||||
IdeError::internal(e.to_string())
|
||||
}
|
||||
|
||||
/// `JAVA_HOME`: the project JDK, else the installed JDK matching `release` (none
|
||||
/// when the project names no version).
|
||||
fn java_env(project_jdk: Option<&ide_sdk::java::Jdk>, release: Option<u32>) -> BTreeMap<String, String> {
|
||||
let jdks = ide_sdk::java::installed_jdks();
|
||||
let jdk = project_jdk.or_else(|| release.and_then(|r| ide_sdk::java::pick_jdk(&jdks, Some(r))));
|
||||
jdk.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())])).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The build model with the launch settings applied: the JDK (`JAVA_HOME`), and
|
||||
/// the Maven home and options from Settings › Maven.
|
||||
pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
|
||||
@@ -39,7 +32,7 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
|
||||
let mvn = ide_sdk::apply::maven_command(root, settings);
|
||||
let options = ide_sdk::apply::maven_options(root, settings);
|
||||
for p in &mut m.projects {
|
||||
p.env = java_env(jdk.as_ref(), p.java_version);
|
||||
p.env = ide_sdk::apply::maven_build_env(root, settings, p.java_version);
|
||||
if let Some(mvn) = &mvn {
|
||||
p.command = mvn.to_string_lossy().into_owned();
|
||||
}
|
||||
@@ -47,8 +40,8 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
|
||||
}
|
||||
}
|
||||
for g in &mut model.gradle {
|
||||
g.env = ide_sdk::apply::gradle_env(root, settings, java_env(jdk.as_ref(), g.java_version));
|
||||
g.command = ide_sdk::apply::gradle_command(root, &root.join(&g.dir), settings).to_string_lossy().into_owned();
|
||||
g.env = ide_sdk::apply::gradle_build_env(root, &root.join(&g.dir), &g.command, settings, g.java_version);
|
||||
}
|
||||
// A failed sync of a project no installed JDK can build says so first (with a Download JDK action).
|
||||
let missing = |release: Option<u32>| match jdk {
|
||||
@@ -63,7 +56,11 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
|
||||
if let Some(m) = &mut model.maven
|
||||
&& m.sync_error.is_some()
|
||||
{
|
||||
let hint = m.projects.iter().find_map(|p| missing(p.java_version));
|
||||
let hint = if settings.languages.java.maven.runner_jre.trim().is_empty() {
|
||||
m.projects.iter().find_map(|p| missing(p.java_version))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
explain(&mut m.sync_error, hint);
|
||||
}
|
||||
for g in &mut model.gradle {
|
||||
@@ -76,6 +73,42 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
|
||||
model
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
let kind = match plan.system {
|
||||
compile::BuildSystem::Cargo => "cargo",
|
||||
compile::BuildSystem::Go => "go",
|
||||
compile::BuildSystem::TypeScript => "npm",
|
||||
_ => return plan,
|
||||
};
|
||||
for step in &mut plan.steps {
|
||||
let mut config = ide_run::RunConfig {
|
||||
id: String::new(),
|
||||
name: String::new(),
|
||||
kind: kind.into(),
|
||||
command: step.program.clone(),
|
||||
args: step.args.clone(),
|
||||
cwd: Some(step.cwd.clone().into()),
|
||||
env: step.env.clone(),
|
||||
detected: true,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
config.extras.module = Some(ide_core::ipc_path::to_ipc(&step.cwd));
|
||||
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut config), root, settings);
|
||||
if kind == "go" {
|
||||
config.extras.params.insert("useTags".into(), "true".into());
|
||||
ide_sdk::go::apply_to_run(&mut config, &settings.languages.go.build_tags);
|
||||
}
|
||||
step.program = config.command;
|
||||
step.args = config.args;
|
||||
step.env = config.env;
|
||||
}
|
||||
plan
|
||||
}
|
||||
|
||||
/// `model` building with the Maven profiles of the last sync (`-P`), as Maven runs from
|
||||
/// the tool window do.
|
||||
fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
|
||||
@@ -404,6 +437,27 @@ pub async fn maven_dependency_declaration(
|
||||
.map_err(join_err)?
|
||||
}
|
||||
|
||||
/// The go-to-declaration target at `pos` of the Maven POM `pom` (project-relative, or
|
||||
/// absolute for a parent POM opened from the local repository): the definition of the
|
||||
/// `${property}` at the caret, or the `<dependencyManagement>` / `<pluginManagement>`
|
||||
/// entry providing the dependency's / plugin's version, along the parent chain (into
|
||||
/// the local repository when a parent is not in the project). `None` when nothing
|
||||
/// resolvable is under the caret.
|
||||
pub async fn maven_goto_declaration(host: &Host, window: &str, pom: String, pos: Pos) -> IdeResult<Option<PomGoto>> {
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let given = Path::new(&pom);
|
||||
let path = if given.is_absolute() { given.to_path_buf() } else { project.root.join(given) };
|
||||
let text = project.text_of(&path)?;
|
||||
let settings = project.settings.effective();
|
||||
let repo = ide_sdk::apply::maven_local_repository(&project.root, &settings)
|
||||
.or_else(ide_build::maven::default_local_repo);
|
||||
Ok(ide_build::maven::goto_declaration(&text, &path, pos, repo))
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)?
|
||||
}
|
||||
|
||||
/// Adds an `<exclusion>` of `exclusion` to the declaration of the direct dependency
|
||||
/// `dependency` of the Maven module `pom`, through the open document when there is one
|
||||
/// (saved). Returns the declaration; nothing changes when it already excludes it.
|
||||
@@ -467,7 +521,11 @@ pub async fn build_run(
|
||||
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective();
|
||||
let member_cache = cache.join(crate::project::project_key(member));
|
||||
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
|
||||
let plan = compile::plan(member, &model, kind, file.as_deref(), settings.cmake.profiles.as_deref())?;
|
||||
let plan = prepare_plan(
|
||||
compile::plan(member, &model, kind, file.as_deref(), settings.cmake.profiles.as_deref())?,
|
||||
member,
|
||||
&settings,
|
||||
);
|
||||
match &mut combined {
|
||||
Some(combined) => combined.steps.extend(plan.steps),
|
||||
None => combined = Some(plan),
|
||||
@@ -477,13 +535,17 @@ pub async fn build_run(
|
||||
plan.title = workspace.name;
|
||||
plan
|
||||
} else {
|
||||
compile::plan(
|
||||
prepare_plan(
|
||||
compile::plan(
|
||||
&root,
|
||||
&with_profiles(load(&root, &cache, &settings), &cache),
|
||||
kind,
|
||||
file.as_deref(),
|
||||
settings.cmake.profiles.as_deref(),
|
||||
)?,
|
||||
&root,
|
||||
&with_profiles(load(&root, &cache, &settings), &cache),
|
||||
kind,
|
||||
file.as_deref(),
|
||||
settings.cmake.profiles.as_deref(),
|
||||
)?
|
||||
&settings,
|
||||
)
|
||||
};
|
||||
let result = compile::run(&root, &plan, &token, &|e| {
|
||||
let _ = on_event.send(e);
|
||||
@@ -538,6 +600,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("maven_dependency_declaration", |c| async move {
|
||||
maven_dependency_declaration(&c.host, &c.window, c.arg("pom")?, c.arg("dependency")?).await
|
||||
});
|
||||
d.add("maven_goto_declaration", |c| async move {
|
||||
maven_goto_declaration(&c.host, &c.window, c.arg("pom")?, c.arg("pos")?).await
|
||||
});
|
||||
d.add("maven_exclude_dependency", |c| async move {
|
||||
maven_exclude_dependency(&c.host, &c.window, c.arg("pom")?, c.arg("dependency")?, c.arg("exclusion")?).await
|
||||
});
|
||||
@@ -556,9 +621,49 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod gradle_settings_tests {
|
||||
mod build_tool_settings_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn builds_apply_the_same_explicit_toolchains_as_runs() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
let tool = |name: &str| format!("{name}{}", std::env::consts::EXE_SUFFIX);
|
||||
for name in ["cargo", "go"] {
|
||||
let path = root.join("sdk").join("bin").join(tool(name));
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "").unwrap();
|
||||
}
|
||||
let mut settings = Settings::default();
|
||||
settings.languages.rust.toolchain = "sdk".into();
|
||||
settings.languages.go.goroot = "sdk".into();
|
||||
settings.languages.go.build_tags.custom = "integration".into();
|
||||
settings.languages.node.package_manager = "yarn".into();
|
||||
for (marker, source, program) in [
|
||||
(
|
||||
"Cargo.toml",
|
||||
"[package]\nname='demo'\nversion='0.1.0'",
|
||||
root.join("sdk").join("bin").join(tool("cargo")).to_string_lossy().into_owned(),
|
||||
),
|
||||
("go.mod", "module demo", root.join("sdk").join("bin").join(tool("go")).to_string_lossy().into_owned()),
|
||||
("package.json", r#"{"scripts":{"build":"echo built"},"packageManager":"pnpm@10"}"#, "yarn".into()),
|
||||
] {
|
||||
let dir = root.join(marker.replace('.', "-"));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join(marker), source).unwrap();
|
||||
let plan = prepare_plan(
|
||||
compile::plan(&dir, &Default::default(), BuildKind::Artifacts, None, None).unwrap(),
|
||||
root,
|
||||
&settings,
|
||||
);
|
||||
assert_eq!(plan.steps[0].program, program);
|
||||
assert_eq!(plan.steps[0].cwd, dir);
|
||||
if marker == "go.mod" {
|
||||
assert!(plan.steps[0].args.contains(&"-tags=integration".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linking_retains_the_implicit_build_and_unlinking_all_stays_empty() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -601,6 +706,34 @@ mod gradle_settings_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_for_maven_sync_goals_and_compile_uses_runner_jre() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::write(root.join("pom.xml"),
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>app</artifactId><version>1</version></project>"#
|
||||
).unwrap();
|
||||
for name in ["project-jdk", "runner-jdk"] {
|
||||
let home = root.join(name);
|
||||
std::fs::create_dir_all(home.join("bin")).unwrap();
|
||||
std::fs::write(home.join("bin").join(if cfg!(windows) { "java.exe" } else { "java" }), "").unwrap();
|
||||
std::fs::write(home.join("release"), "JAVA_VERSION=\"21\"\n").unwrap();
|
||||
}
|
||||
let mut settings = Settings::default();
|
||||
settings.languages.java.jdk = "project-jdk".into();
|
||||
for runner in ["", "runner-jdk"] {
|
||||
settings.languages.java.maven.runner_jre = runner.into();
|
||||
let expected = root.join(if runner.is_empty() { "project-jdk" } else { runner });
|
||||
let model = load(&root, &root.join("cache"), &settings);
|
||||
assert_eq!(model.maven.as_ref().unwrap().projects[0].env["JAVA_HOME"], expected.to_string_lossy());
|
||||
let plan = compile::plan(&root, &model, BuildKind::Build, None, None).unwrap();
|
||||
assert!(!plan.steps.is_empty());
|
||||
for step in plan.steps {
|
||||
assert_eq!(step.env["JAVA_HOME"], expected.to_string_lossy());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_for_sync_tasks_and_compile_uses_gradle_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -103,7 +103,8 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("db_explain", |c| async move {
|
||||
let (request, id, statement) =
|
||||
(c.arg::<RequestId>("request")?, c.arg::<String>("id")?, c.arg::<String>("statement")?);
|
||||
explain(&c.host, &c.window, request, &id, &statement).await
|
||||
let schema = c.arg::<Option<String>>("schema")?;
|
||||
explain(&c.host, &c.window, request, &id, &statement, schema.as_deref()).await
|
||||
});
|
||||
d.add("db_history", |c| async move {
|
||||
let id = c.arg::<String>("id")?;
|
||||
@@ -130,7 +131,8 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
c.arg::<Option<u32>>("skip")?.unwrap_or(0),
|
||||
c.arg::<u32>("maxRows")?,
|
||||
);
|
||||
execute(&c.host, &c.window, request, &id, statements, skip, max_rows).await
|
||||
let schema = c.arg::<Option<String>>("schema")?;
|
||||
execute(&c.host, &c.window, request, &id, statements, skip, max_rows, schema.as_deref()).await
|
||||
});
|
||||
d.add("db_table_page", |c| async move {
|
||||
let (request, id, schema, table) = (
|
||||
@@ -289,10 +291,11 @@ pub async fn explain(
|
||||
request: RequestId,
|
||||
id: &str,
|
||||
statement: &str,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<Vec<PlanNode>> {
|
||||
let db = host.project(window)?.db.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = db.explain(id, statement, &cancel).await;
|
||||
let result = db.explain(id, statement, &cancel, schema).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
@@ -327,7 +330,9 @@ pub fn statements(host: &Host, window: &str, id: &str, text: &str, from: u32, to
|
||||
|
||||
/// Runs `statements` in order on data source `id`, stopping at the first
|
||||
/// error. Each result reads past its first `skip` rows (a later page) and keeps
|
||||
/// `max_rows`. Cancel with `cancel_request(request)`.
|
||||
/// `max_rows`. `schema` is the console's active context: the connection running
|
||||
/// each statement is put in it first. Cancel with `cancel_request(request)`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn execute(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -336,12 +341,13 @@ pub async fn execute(
|
||||
statements: Vec<SqlStatement>,
|
||||
skip: u32,
|
||||
max_rows: u32,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<Vec<StatementOutcome>> {
|
||||
let db = host.project(window)?.db.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let mut out = Vec::new();
|
||||
for statement in statements {
|
||||
match db.execute_from(id, &statement.text, skip as usize, max_rows.max(1) as usize, &cancel).await {
|
||||
match db.execute_from(id, &statement.text, skip as usize, max_rows.max(1) as usize, &cancel, schema).await {
|
||||
Ok(result) => out.push(StatementOutcome { statement, result: Some(result), error: None }),
|
||||
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => {
|
||||
host.end_request(request);
|
||||
|
||||
@@ -28,9 +28,11 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
let settings = settings.clone();
|
||||
config = host
|
||||
.blocking(move || {
|
||||
ide_sdk::go::debug_environment(&root, &settings, &mut config.env);
|
||||
ide_sdk::go::configure_environment(&root, &settings, &mut config.env);
|
||||
ide_sdk::go::apply_to_debug(
|
||||
&mut config.env,
|
||||
&mut config.program,
|
||||
&mut config.args,
|
||||
&mut config.extra_json,
|
||||
&settings.languages.go.build_tags,
|
||||
)?;
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
//! Repository version lookups for manifest inspections and completion.
|
||||
use crate::{Host, rpc::Dispatcher};
|
||||
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, RequestId};
|
||||
use ide_workspace::dependencies::{DependencyVersionSource, DependencyVersions, cargo};
|
||||
use ide_workspace::dependencies::{DependencyVersionSource, DependencyVersions, cargo, go};
|
||||
use std::collections::BTreeMap;
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
struct CratesIo;
|
||||
impl DependencyVersionSource for CratesIo {
|
||||
@@ -21,6 +25,76 @@ impl DependencyVersionSource for CratesIo {
|
||||
}
|
||||
}
|
||||
|
||||
struct GoModules {
|
||||
root: PathBuf,
|
||||
env: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl DependencyVersionSource for GoModules {
|
||||
fn id(&self) -> &'static str {
|
||||
"go-modules"
|
||||
}
|
||||
|
||||
fn cache_key(&self, package: &str) -> Option<String> {
|
||||
let mut hash = DefaultHasher::new();
|
||||
(&self.root, &self.env, package).hash(&mut hash);
|
||||
Some(format!("{}-{:016x}", self.id(), hash.finish()))
|
||||
}
|
||||
|
||||
fn fetch(&self, package: &str, cancel: &CancellationToken) -> IdeResult<Vec<String>> {
|
||||
let search =
|
||||
self.env.get("PATH").map(std::ffi::OsString::from).unwrap_or_else(ide_core::tool_path::search_path);
|
||||
let go = ide_core::tool_path::find_command("go", &search, &self.root)
|
||||
.ok_or_else(|| IdeError::unavailable("Go SDK is unavailable"))?;
|
||||
// A partially edited go.mod is often invalid. Query outside it while
|
||||
// keeping the SDK and proxy/private module configuration.
|
||||
let dir = tempfile::tempdir()?;
|
||||
let mut cmd = Command::new(go);
|
||||
cmd.current_dir(dir.path())
|
||||
.env("PATH", search)
|
||||
.envs(&self.env)
|
||||
.env("GO111MODULE", "on")
|
||||
.env("GOFLAGS", "")
|
||||
.env("GOWORK", "off")
|
||||
.env("GIT_TERMINAL_PROMPT", "0")
|
||||
.args(["list", "-m", "-versions", "-f", "{{range .Versions}}{{println .}}{{end}}", "--", package]);
|
||||
let query = cancel.child_token();
|
||||
// Fetches run on Host::blocking's Tokio pool, which keeps a runtime current.
|
||||
let deadline = tokio::spawn({
|
||||
let query = query.clone();
|
||||
async move {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
|
||||
query.cancel();
|
||||
}
|
||||
});
|
||||
let output = ide_tools::run_streamed(cmd, &query, &|_| {});
|
||||
deadline.abort();
|
||||
Ok(go::listed_versions(&output?))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
#[path = "dependencies/go_tests.rs"]
|
||||
mod go_tests;
|
||||
|
||||
fn go_source(project: &crate::Project, config_dir: &Path, path: &Path) -> IdeResult<GoModules> {
|
||||
let member = ide_workspace::workspace::Workspace::load(&project.root)?.and_then(|workspace| {
|
||||
workspace
|
||||
.projects
|
||||
.into_iter()
|
||||
.filter(|root| path.starts_with(root))
|
||||
.max_by_key(|root| root.components().count())
|
||||
});
|
||||
let settings = match &member {
|
||||
Some(root) => ide_workspace::SettingsStore::load(config_dir, Some(root)).effective(),
|
||||
None => project.settings.effective(),
|
||||
};
|
||||
let root = member.unwrap_or_else(|| project.root.clone());
|
||||
let mut env = BTreeMap::new();
|
||||
ide_sdk::go::configure_environment(&root, &settings, &mut env);
|
||||
Ok(GoModules { root, env })
|
||||
}
|
||||
|
||||
/// `offset` limits a completion request to its version string; inspections omit it.
|
||||
pub async fn dependency_versions(
|
||||
host: &Host,
|
||||
@@ -31,11 +105,24 @@ pub async fn dependency_versions(
|
||||
) -> IdeResult<Vec<DependencyVersions>> {
|
||||
let project = host.project(window)?;
|
||||
let cache = host.dependency_versions.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let config_dir = host.config_dir.clone();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if snap.large || snap.read_only || snap.path.file_name().is_none_or(|n| n != "Cargo.toml") {
|
||||
if snap.large || snap.read_only {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if snap.path.file_name().is_some_and(|name| name == "go.mod") {
|
||||
let Some(dependency) = offset.and_then(|offset| go::dependency_at(&snap.text, offset)) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
project.require_trust()?;
|
||||
let source = go_source(&project, &config_dir, snap.path.as_ref())?;
|
||||
let versions = cache.versions(&source, &dependency.package, &cancel)?;
|
||||
return Ok(vec![DependencyVersions { dependency, versions, update: None }]);
|
||||
}
|
||||
if snap.path.file_name().is_none_or(|name| name != "Cargo.toml") {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
use super::*;
|
||||
use ide_workspace::dependencies::VersionCache;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn source(dir: &Path, script: &str) -> GoModules {
|
||||
let bin = dir.join("bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
let go = bin.join("go");
|
||||
std::fs::write(&go, format!("#!/bin/sh\n{script}\n")).unwrap();
|
||||
std::fs::set_permissions(&go, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
GoModules {
|
||||
root: dir.to_owned(),
|
||||
env: BTreeMap::from([
|
||||
("PATH".into(), bin.to_string_lossy().into_owned()),
|
||||
("PROJECT_ROOT".into(), dir.to_string_lossy().into_owned()),
|
||||
("GOPROXY".into(), "https://user:[email protected]".into()),
|
||||
("GOPRIVATE".into(), "private.example/token".into()),
|
||||
("GOWORK".into(), "broken.work".into()),
|
||||
("GOFLAGS".into(), "-mod=vendor".into()),
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn go_query_is_isolated_and_persists_only_hashed_configuration_and_versions() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let source = source(
|
||||
dir.path(),
|
||||
r#"set -eu
|
||||
[ "$PWD" != "$PROJECT_ROOT" ]
|
||||
[ "$GOPROXY" = 'https://user:[email protected]' ]
|
||||
[ "$GOPRIVATE" = 'private.example/token' ]
|
||||
[ "$GOWORK" = off ]
|
||||
[ "$GOFLAGS" = '' ]
|
||||
[ "$GO111MODULE" = on ]
|
||||
[ "$GIT_TERMINAL_PROMPT" = 0 ]
|
||||
[ "$1 $2 $3 $4" = 'list -m -versions -f' ]
|
||||
[ "$5" = '{{range .Versions}}{{println .}}{{end}}' ]
|
||||
[ "$6 $7" = '-- example.com/Org/Lib/v2' ]
|
||||
printf 'v2.9.0\nv2.10.0\n'"#,
|
||||
);
|
||||
let key = source.cache_key("example.com/Org/Lib/v2").unwrap();
|
||||
assert_ne!(key, source.cache_key("example.com/org/lib/v2").unwrap());
|
||||
let mut other = GoModules { root: source.root.join("member"), env: source.env.clone() };
|
||||
assert_ne!(key, other.cache_key("example.com/Org/Lib/v2").unwrap());
|
||||
other.root = source.root.clone();
|
||||
other.env.insert("GOPROXY".into(), "https://other.example".into());
|
||||
assert_ne!(key, other.cache_key("example.com/Org/Lib/v2").unwrap());
|
||||
let cache_dir = dir.path().join("cache");
|
||||
let disk = cache_dir.clone();
|
||||
let versions = tokio::task::spawn_blocking(move || {
|
||||
VersionCache::new(cache_dir).versions(&source, "example.com/Org/Lib/v2", &CancellationToken::new())
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(versions, ["v2.10.0", "v2.9.0"]);
|
||||
let entries: Vec<_> = std::fs::read_dir(disk).unwrap().map(Result::unwrap).collect();
|
||||
assert_eq!(entries.len(), 1, "the hashed key passes the cache filename filter");
|
||||
assert_eq!(entries[0].file_name().to_str().unwrap(), format!("{key}.json"));
|
||||
let cached = std::fs::read_to_string(entries[0].path()).unwrap();
|
||||
for sensitive in ["secret", "proxy.example", "private.example", "token", "PROJECT_ROOT"] {
|
||||
assert!(!cached.contains(sensitive), "configuration must not be persisted: {sensitive}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn failed_go_queries_are_silent_and_not_persisted() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let source = source(dir.path(), "echo 'private module or offline proxy' >&2\nexit 1");
|
||||
let cache_dir = dir.path().join("cache");
|
||||
let disk = cache_dir.clone();
|
||||
let versions = tokio::task::spawn_blocking(move || {
|
||||
VersionCache::new(cache_dir).versions(&source, "private.example/module", &CancellationToken::new())
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(versions.is_empty());
|
||||
assert!(!disk.exists());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn stalled_go_queries_obey_the_deadline_and_parent_cancellation() {
|
||||
for cancel_parent in [false, true] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let source = source(dir.path(), "exec /bin/sleep 60");
|
||||
let cancel = CancellationToken::new();
|
||||
let query = cancel.clone();
|
||||
let started = Instant::now();
|
||||
let work = tokio::task::spawn_blocking(move || {
|
||||
VersionCache::new(source.root.join("cache")).versions(&source, "example.com/stalled", &query)
|
||||
});
|
||||
if cancel_parent {
|
||||
tokio::time::sleep(Duration::from_millis(150)).await;
|
||||
cancel.cancel();
|
||||
assert!(work.await.unwrap().is_err());
|
||||
assert!(started.elapsed() < Duration::from_secs(3));
|
||||
} else {
|
||||
assert!(work.await.unwrap().unwrap().is_empty());
|
||||
assert!(started.elapsed() >= Duration::from_secs(10));
|
||||
assert!(started.elapsed() < Duration::from_secs(15));
|
||||
assert!(!cancel.is_cancelled(), "a query deadline must not cancel its caller");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,9 +91,10 @@ async fn resolve_launch(
|
||||
}
|
||||
}
|
||||
info.class_paths = class_paths;
|
||||
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
|
||||
let compile_ms = started.elapsed().as_millis() - lsp_ms;
|
||||
// The project JDK, else the JDK jdtls compiles the module against, else one matching its Java version.
|
||||
let project_jdk = ide_sdk::apply::project_jdk(&project.root, &settings);
|
||||
// The module/project JDK, else the JDK jdtls compiles the module against, else one matching its Java version.
|
||||
let project_jdk = ide_sdk::apply::module_jdk(&project.root, &module, &settings);
|
||||
let from_jdtls = info.java_home.as_deref().map(ide_sdk::java::java_executable).filter(|p| p.is_file());
|
||||
let java = project_jdk.map(|j| ide_sdk::java::java_executable(&j.home)).or(from_jdtls).or_else(|| {
|
||||
// The build model's level includes what the module inherits from its parent POMs.
|
||||
@@ -153,6 +154,41 @@ fn entry_key(path: &str, windows: bool) -> String {
|
||||
if windows { key.to_lowercase() } else { key }
|
||||
}
|
||||
|
||||
fn apply_library_classpath(
|
||||
info: &mut JavaLaunchInfo,
|
||||
root: &std::path::Path,
|
||||
libraries: &[ide_core::settings::ProjectLibrary],
|
||||
test: bool,
|
||||
) {
|
||||
use ide_core::settings::DependencyScope;
|
||||
let entries: Vec<_> = libraries
|
||||
.iter()
|
||||
.flat_map(|lib| {
|
||||
let allowed = match lib.scope {
|
||||
DependencyScope::Compile | DependencyScope::Runtime => true,
|
||||
DependencyScope::Test | DependencyScope::Provided => test,
|
||||
};
|
||||
lib.classes.iter().filter_map(move |entry| {
|
||||
ide_sdk::apply::setting_path(root, entry).map(|path| (path.to_string_lossy().into_owned(), allowed))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
// JDT may already have returned these archives on either classpath.
|
||||
for paths in [&mut info.class_paths, &mut info.module_paths] {
|
||||
paths.retain(|path| {
|
||||
let matching: Vec<_> = entries.iter().filter(|(entry, _)| same_entry(path, entry, cfg!(windows))).collect();
|
||||
matching.is_empty() || matching.iter().any(|(_, allowed)| *allowed)
|
||||
});
|
||||
}
|
||||
for (entry, allowed) in entries {
|
||||
if allowed
|
||||
&& !info.class_paths.iter().chain(&info.module_paths).any(|path| same_entry(path, &entry, cfg!(windows)))
|
||||
{
|
||||
info.class_paths.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn same_entry(a: &str, b: &str, windows: bool) -> bool {
|
||||
a == b || entry_key(a, windows) == entry_key(b, windows)
|
||||
}
|
||||
@@ -220,6 +256,36 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn library_scopes_filter_jdt_classpaths_and_module_paths() {
|
||||
use ide_core::settings::{DependencyScope, ProjectLibrary};
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let scopes =
|
||||
[DependencyScope::Compile, DependencyScope::Runtime, DependencyScope::Test, DependencyScope::Provided];
|
||||
let libraries: Vec<_> = scopes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, scope)| ProjectLibrary {
|
||||
classes: vec![format!("lib/{i}.jar")],
|
||||
scope: *scope,
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
let paths: Vec<_> =
|
||||
(0..4).map(|i| root.path().join(format!("lib/{i}.jar")).to_string_lossy().into_owned()).collect();
|
||||
for test in [false, true] {
|
||||
let mut info =
|
||||
JavaLaunchInfo { class_paths: paths.clone(), module_paths: paths.clone(), ..Default::default() };
|
||||
apply_library_classpath(&mut info, root.path(), &libraries, test);
|
||||
let expected = if test { &paths[..] } else { &paths[..2] };
|
||||
assert_eq!(info.class_paths, expected);
|
||||
assert_eq!(info.module_paths, expected);
|
||||
}
|
||||
let mut info = JavaLaunchInfo::default();
|
||||
apply_library_classpath(&mut info, root.path(), &libraries, false);
|
||||
assert_eq!(info.class_paths, &paths[..2]);
|
||||
}
|
||||
|
||||
/// JDT LS and our build model spell a module output differently on Windows; the
|
||||
/// snapshot must still replace it, or resources (MyBatis mapper XML) load twice.
|
||||
#[test]
|
||||
|
||||
+391
-34
@@ -3,9 +3,11 @@ use crate::Host;
|
||||
use crate::apply_workspace_edit as apply_edit;
|
||||
use crate::plugins::{ProviderKind, editor_providers_for as editor_providers};
|
||||
use crate::rpc::Dispatcher;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{DocId, IdeResult, Location, Pos, Range, RequestId, ServerId, TextEdit, WorkspaceEdit};
|
||||
use ide_lsp::types::*;
|
||||
use ide_plugin::ProviderDocument;
|
||||
use std::path::Path;
|
||||
|
||||
async fn prepare_actions(
|
||||
project: std::sync::Arc<crate::Project>,
|
||||
@@ -46,7 +48,7 @@ pub async fn lsp_completion(
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Completion) else { return result };
|
||||
let items = plugin_call(move || plugins.provide_completion(&d, pos, trigger.as_deref())).await.unwrap_or_default();
|
||||
if items.is_empty() {
|
||||
return result;
|
||||
return Ok(result.unwrap_or(CompletionList { is_incomplete: true, items: Vec::new() }));
|
||||
}
|
||||
let mut list = result.unwrap_or(CompletionList { is_incomplete: false, items: Vec::new() });
|
||||
list.items.extend(items.into_iter().map(|(_, item)| plugin_completion(item)));
|
||||
@@ -84,7 +86,12 @@ const PLUGIN_SERVER: ServerId = ServerId(0);
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
struct PluginActionRef {
|
||||
plugin: String,
|
||||
data: String,
|
||||
data: Option<String>,
|
||||
/// Opened once the action is applied.
|
||||
open: Option<ide_core::IpcPath>,
|
||||
/// Listed by the plugin's `file-actions` export, which resolves it.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
file: bool,
|
||||
}
|
||||
|
||||
/// A plugin's `completion-item.kind` (wit/providers.wit lists them).
|
||||
@@ -194,9 +201,24 @@ pub async fn lsp_hover(
|
||||
) -> IdeResult<Option<Hover>> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = lsp.hover(doc, pos, cancel).await;
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Hover) else {
|
||||
let result = lsp.hover(doc, pos, cancel).await;
|
||||
host.end_request(request);
|
||||
return result;
|
||||
};
|
||||
let (result, hovers) =
|
||||
tokio::join!(lsp.hover(doc, pos, cancel), plugin_call(move || plugins.provide_hover(&d, pos)));
|
||||
host.end_request(request);
|
||||
result
|
||||
let hovers = hovers.unwrap_or_default();
|
||||
if hovers.is_empty() {
|
||||
return result;
|
||||
}
|
||||
let server = match result {
|
||||
Ok(server) => server,
|
||||
Err(e) if matches!(e.kind, ErrorKind::NotFound | ErrorKind::Unavailable) => None,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
Ok(crate::plugins::merge_hover(server, hovers))
|
||||
}
|
||||
|
||||
pub async fn lsp_signature_help(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeResult<Option<SignatureHelp>> {
|
||||
@@ -221,14 +243,65 @@ pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: Got
|
||||
}
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Definition) else { return result };
|
||||
let found = plugin_call(move || plugins.provide_definition(&d, pos)).await.unwrap_or_default();
|
||||
if found.is_empty() {
|
||||
return result;
|
||||
let found: Vec<Location> =
|
||||
found.into_iter().map(|l| Location { path: l.path.into(), range: l.range, uri: None }).collect();
|
||||
let in_string = !found.is_empty() && in_string_literal(host, window, doc, pos).await;
|
||||
definition_targets(result, found, in_string)
|
||||
}
|
||||
|
||||
async fn in_string_literal(host: &Host, window: &str, doc: DocId, pos: Pos) -> bool {
|
||||
let Ok(project) = host.project(window) else { return false };
|
||||
blocking(move || {
|
||||
let snap = project.documents.text_snapshot(doc)?;
|
||||
if snap.large {
|
||||
return Ok(false);
|
||||
}
|
||||
let s = ide_syntax::Snapshot::doc(doc, snap.version, &snap.language, &snap.text);
|
||||
Ok(string_at(&project.structure, &s, pos))
|
||||
})
|
||||
.await
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn string_at(structure: &ide_syntax::StructureService, snap: &ide_syntax::Snapshot, pos: Pos) -> bool {
|
||||
let cancel = ide_core::CancellationToken::new();
|
||||
let Ok(Some(at)) = structure.node_at(snap, Range::new(pos, pos), &cancel) else { return false };
|
||||
let stringy = |kind: &str| kind.contains("string") || kind.contains("heredoc") || kind.contains("nowdoc");
|
||||
let part = |kind: &str| kind.contains("content") || kind.contains("fragment") || kind.contains("escape");
|
||||
stringy(&at.node.kind) || (part(&at.node.kind) && at.ancestors.first().is_some_and(|parent| stringy(&parent.kind)))
|
||||
}
|
||||
|
||||
fn definition_targets(
|
||||
server: IdeResult<Vec<Location>>,
|
||||
plugin: Vec<Location>,
|
||||
in_string: bool,
|
||||
) -> IdeResult<Vec<Location>> {
|
||||
if plugin.is_empty() {
|
||||
return server.map(without_generated_helpers);
|
||||
}
|
||||
let mut out = result.unwrap_or_default();
|
||||
out.extend(found.into_iter().map(|l| Location { path: l.path.into(), range: l.range, uri: None }));
|
||||
if in_string {
|
||||
return Ok(plugin);
|
||||
}
|
||||
let same_place = |l: &Location| plugin.iter().any(|p| p.path == l.path && p.range.start.line == l.range.start.line);
|
||||
let server: Vec<Location> =
|
||||
without_generated_helpers(server.unwrap_or_default()).into_iter().filter(|l| !same_place(l)).collect();
|
||||
let mut out = plugin;
|
||||
out.extend(server);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn without_generated_helpers(locations: Vec<Location>) -> Vec<Location> {
|
||||
let generated = |l: &Location| {
|
||||
let path = l.path.to_string_lossy().replace('\\', "/");
|
||||
let file = path.rsplit('/').next().unwrap_or(&path);
|
||||
file.starts_with("_ide_helper") || file == ".phpstorm.meta.php" || path.contains("/vendor/_laravel_ide")
|
||||
};
|
||||
if locations.iter().all(generated) {
|
||||
return locations;
|
||||
}
|
||||
locations.into_iter().filter(|l| !generated(l)).collect()
|
||||
}
|
||||
|
||||
/// Gutter markers from plugins (`line-markers` providers) for `doc`.
|
||||
pub async fn plugin_line_markers(
|
||||
host: &Host,
|
||||
@@ -307,7 +380,11 @@ pub async fn lsp_resolve_class_file(host: &Host, window: &str, path: std::path::
|
||||
|
||||
/// References of the symbol at `pos`. `project_wide` also searches project files
|
||||
/// outside the language server's analysis scope; bulk scans over many symbols
|
||||
/// leave it off. Cancel with `cancel_request(request)`.
|
||||
/// leave it off. Java, `project_wide`: without `libraries`, the dependencies and the JDK
|
||||
/// are not searched; with it, those found in the sources arrive on `on_partial` before
|
||||
/// the slower search for the rest, and the result has them all. Cancel with
|
||||
/// `cancel_request(request)`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn lsp_references(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -316,10 +393,24 @@ pub async fn lsp_references(
|
||||
pos: Pos,
|
||||
include_declaration: bool,
|
||||
project_wide: bool,
|
||||
libraries: bool,
|
||||
on_partial: super::Channel<References>,
|
||||
) -> IdeResult<References> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = lsp.references(doc, pos, include_declaration, project_wide, cancel).await;
|
||||
let result = lsp
|
||||
.references_streaming(
|
||||
doc,
|
||||
pos,
|
||||
include_declaration,
|
||||
project_wide,
|
||||
libraries,
|
||||
cancel,
|
||||
Some(&|refs| {
|
||||
let _ = on_partial.send(refs);
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
@@ -358,7 +449,7 @@ pub async fn lsp_code_actions(
|
||||
};
|
||||
let plugin_actions: Vec<CodeAction> = plugin_actions
|
||||
.into_iter()
|
||||
.map(|(plugin, a)| plugin_code_action(&plugin, a))
|
||||
.map(|(plugin, a)| plugin_code_action(&plugin, &project.root, a))
|
||||
.filter(|a| {
|
||||
only.is_empty()
|
||||
|| a.kind.as_ref().is_some_and(|k| only.iter().any(|o| k == o || k.starts_with(&format!("{o}."))))
|
||||
@@ -374,23 +465,26 @@ pub async fn lsp_code_actions(
|
||||
prepare_actions(project, doc, version, actions).await
|
||||
}
|
||||
|
||||
fn plugin_code_action(plugin: &str, a: ide_plugin::CodeAction) -> CodeAction {
|
||||
// With `data` and no edits, the plugin computes them when the action is picked.
|
||||
let lazy = a.edits.is_empty() && a.data.is_some();
|
||||
let files: Vec<_> = a
|
||||
.edits
|
||||
.into_iter()
|
||||
.map(|(path, edits)| ide_core::FileEdit::Edit { path: path.into(), edits, version: None })
|
||||
.collect();
|
||||
let data = a
|
||||
.data
|
||||
.filter(|_| lazy)
|
||||
.and_then(|data| serde_json::to_value(PluginActionRef { plugin: plugin.to_owned(), data }).ok());
|
||||
fn plugin_code_action(plugin: &str, root: &Path, a: ide_plugin::CodeAction) -> CodeAction {
|
||||
// With `data` and nothing to apply, the plugin computes the edits when the action is picked.
|
||||
let lazy = a.edits.is_empty() && a.operations.is_empty() && a.data.is_some();
|
||||
let (files, open, disabled_reason) = match plugin_file_edits(root, &a) {
|
||||
Ok((files, open)) => (files, open, None),
|
||||
Err(reason) => (Vec::new(), None, Some(reason)),
|
||||
};
|
||||
let data = (lazy || open.is_some())
|
||||
.then(|| PluginActionRef {
|
||||
plugin: plugin.to_owned(),
|
||||
data: a.data.filter(|_| lazy),
|
||||
open: open.map(Into::into),
|
||||
file: a.file_action,
|
||||
})
|
||||
.and_then(|r| serde_json::to_value(r).ok());
|
||||
CodeAction {
|
||||
title: a.title,
|
||||
kind: a.kind,
|
||||
is_preferred: a.preferred,
|
||||
disabled_reason: None,
|
||||
disabled_reason,
|
||||
edit: (!lazy).then(|| WorkspaceEdit { files, preconditions: Vec::new() }),
|
||||
command: None,
|
||||
data,
|
||||
@@ -398,6 +492,53 @@ fn plugin_code_action(plugin: &str, a: ide_plugin::CodeAction) -> CodeAction {
|
||||
}
|
||||
}
|
||||
|
||||
/// The action's file operations, then its text edits, as one workspace edit's files, and the
|
||||
/// file to open. An action with file operations or an `open` target stays inside the project
|
||||
/// root as a whole: a path outside it disables the action.
|
||||
fn plugin_file_edits(
|
||||
root: &Path,
|
||||
a: &ide_plugin::CodeAction,
|
||||
) -> Result<(Vec<ide_core::FileEdit>, Option<std::path::PathBuf>), String> {
|
||||
use ide_core::FileEdit;
|
||||
use ide_plugin::FileOperation;
|
||||
let confine = !a.operations.is_empty() || a.open.is_some();
|
||||
let confined = |path: &Path| ide_plugin::resolve_new_in_root(root, &path.to_string_lossy());
|
||||
let mut files = Vec::new();
|
||||
let mut created_with_text = Vec::new();
|
||||
for operation in &a.operations {
|
||||
match operation {
|
||||
FileOperation::Create { path, text, overwrite } => {
|
||||
let path = confined(path)?;
|
||||
files.push(FileEdit::Create { path: path.clone().into(), overwrite: *overwrite });
|
||||
if !text.is_empty() {
|
||||
let start = Range::point(Pos::new(0, 0));
|
||||
files.push(FileEdit::Edit {
|
||||
path: path.clone().into(),
|
||||
edits: vec![TextEdit { range: start, new_text: text.clone() }],
|
||||
version: None,
|
||||
});
|
||||
created_with_text.push(path);
|
||||
}
|
||||
}
|
||||
FileOperation::Rename { from, to } => {
|
||||
files.push(FileEdit::Rename { from: confined(from)?.into(), to: confined(to)?.into() });
|
||||
}
|
||||
FileOperation::Delete { path } => {
|
||||
files.push(FileEdit::Delete { path: confined(path)?.into(), recursive: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
for (path, edits) in &a.edits {
|
||||
let path = if confine { confined(path)? } else { path.clone() };
|
||||
if created_with_text.contains(&path) {
|
||||
return Err("put the text of a created file in its `create`, not in an edit".into());
|
||||
}
|
||||
files.push(FileEdit::Edit { path: path.into(), edits: edits.clone(), version: None });
|
||||
}
|
||||
let open = a.open.as_deref().map(confined).transpose()?;
|
||||
Ok((files, open))
|
||||
}
|
||||
|
||||
/// A code action resolved by whoever offered it: its language server, or
|
||||
/// the plugin its `data` names.
|
||||
async fn resolve_action(host: &Host, window: &str, doc: DocId, action: CodeAction) -> IdeResult<CodeAction> {
|
||||
@@ -414,11 +555,16 @@ async fn resolve_action(host: &Host, window: &str, doc: DocId, action: CodeActio
|
||||
kind: action.kind.clone(),
|
||||
preferred: action.is_preferred,
|
||||
edits: Vec::new(),
|
||||
data: Some(r.data),
|
||||
operations: Vec::new(),
|
||||
open: None,
|
||||
data: r.data,
|
||||
file_action: r.file,
|
||||
};
|
||||
let plugin = r.plugin.clone();
|
||||
let resolved = blocking(move || plugins.resolve_code_action(&plugin, &d, pending)).await?;
|
||||
Ok(plugin_code_action(&r.plugin, ide_plugin::CodeAction { data: None, ..resolved }))
|
||||
let invocation = ide_plugin::Invocation { client: Some(window.to_owned()), ..Default::default() };
|
||||
let resolved = blocking(move || plugins.resolve_code_action(&plugin, &d, pending, invocation)).await?;
|
||||
let root = host.project(window)?.root.clone();
|
||||
Ok(plugin_code_action(&r.plugin, &root, ide_plugin::CodeAction { data: None, ..resolved }))
|
||||
}
|
||||
|
||||
/// Cancellable code actions with the kinds the servers advertise (Refactor This, refactoring availability).
|
||||
@@ -441,7 +587,7 @@ pub async fn lsp_code_action_query(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Resolves a code action's edit without applying it (intention preview).
|
||||
/// Resolves a code action's edit without applying it.
|
||||
pub async fn lsp_resolve_code_action(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -469,11 +615,15 @@ pub async fn lsp_apply_code_action(host: &Host, window: &str, doc: DocId, action
|
||||
} else {
|
||||
action
|
||||
};
|
||||
if let Some(reason) = &action.disabled_reason {
|
||||
return Err(ide_core::IdeError::invalid(reason.clone()));
|
||||
}
|
||||
if let Some(edit) = &action.edit {
|
||||
let documents = project.documents.clone();
|
||||
let edit = edit.clone();
|
||||
blocking(move || apply_edit(&documents, &edit)).await?;
|
||||
}
|
||||
open_plugin_action_target(&action, window);
|
||||
if let Some(command) = action.command
|
||||
&& !(action.edit.is_some() && is_client_follow_up(&project, doc, None, &command).await)
|
||||
{
|
||||
@@ -482,6 +632,24 @@ pub async fn lsp_apply_code_action(host: &Host, window: &str, doc: DocId, action
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The plugin and the file its action asks to show once applied.
|
||||
fn plugin_action_open(action: &CodeAction) -> Option<(String, ide_core::IpcPath)> {
|
||||
if action.server != PLUGIN_SERVER {
|
||||
return None;
|
||||
}
|
||||
let r = action.data.clone().and_then(|d| serde_json::from_value::<PluginActionRef>(d).ok())?;
|
||||
Some((r.plugin, r.open?))
|
||||
}
|
||||
|
||||
/// Opens the file a plugin's action asked to show, now that the action is applied.
|
||||
fn open_plugin_action_target(action: &CodeAction, window: &str) {
|
||||
let (Some((plugin, path)), Some(plugins)) = (plugin_action_open(action), crate::plugins::editor_plugin_host())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
plugins.open_file(&plugin, window, path);
|
||||
}
|
||||
|
||||
/// A command after a code action's edit that no server provides: what other editors'
|
||||
/// extensions do once the edit is applied (vtsls' `_typescript.didOrganizeImports`). The edit
|
||||
/// is the action; there is nothing to run.
|
||||
@@ -592,11 +760,41 @@ pub async fn lsp_format(
|
||||
}
|
||||
|
||||
pub async fn lsp_inlay_hints(host: &Host, window: &str, doc: DocId, range: Range) -> IdeResult<Vec<InlayHint>> {
|
||||
host.project(window)?.lsp.inlay_hints(doc, range).await
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::InlayHints) else {
|
||||
return lsp.inlay_hints(doc, range).await;
|
||||
};
|
||||
let (result, hints) =
|
||||
tokio::join!(lsp.inlay_hints(doc, range), plugin_call(move || plugins.provide_inlay_hints(&d, range)));
|
||||
let hints = hints.unwrap_or_default();
|
||||
if hints.is_empty() {
|
||||
return result;
|
||||
}
|
||||
let server = match result {
|
||||
Ok(server) => server,
|
||||
Err(e) if matches!(e.kind, ErrorKind::NotFound | ErrorKind::Unavailable) => Vec::new(),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
Ok(crate::plugins::merge_inlay_hints(server, hints, range))
|
||||
}
|
||||
|
||||
pub async fn lsp_semantic_tokens(host: &Host, window: &str, doc: DocId) -> IdeResult<Option<SemanticTokens>> {
|
||||
host.project(window)?.lsp.semantic_tokens(doc).await
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::SemanticTokens) else {
|
||||
return lsp.semantic_tokens(doc).await;
|
||||
};
|
||||
let (result, tokens) =
|
||||
tokio::join!(lsp.semantic_tokens(doc), plugin_call(move || plugins.provide_semantic_tokens(&d)));
|
||||
let tokens = tokens.unwrap_or_default();
|
||||
if tokens.is_empty() {
|
||||
return result;
|
||||
}
|
||||
let server = match result {
|
||||
Ok(server) => server,
|
||||
Err(e) if matches!(e.kind, ErrorKind::NotFound | ErrorKind::Unavailable) => None,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
Ok(Some(crate::plugins::merge_semantic_tokens(server, tokens)))
|
||||
}
|
||||
|
||||
pub async fn lsp_code_lens(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<CodeLens>> {
|
||||
@@ -731,6 +929,8 @@ pub async fn lsp_execute_code_action(
|
||||
return Err(ide_core::IdeError::cancelled());
|
||||
}
|
||||
let edited = action.edit.is_some();
|
||||
// A plugin's action may name a file to show once applied; the caller opens it.
|
||||
let open = plugin_action_open(&action).map(|(_, path)| path);
|
||||
if let Some(edit) = action.edit {
|
||||
let documents = project.documents.clone();
|
||||
tokio::task::spawn_blocking(move || apply_edit(&documents, &edit))
|
||||
@@ -746,7 +946,7 @@ pub async fn lsp_execute_code_action(
|
||||
.execute_action_command(doc, action.server, command, answers, cancel)
|
||||
.await
|
||||
.map(|paths| paths.into_iter().map(ide_core::IpcPath::from).collect()),
|
||||
None => Ok(Vec::new()),
|
||||
None => Ok(open.into_iter().collect()),
|
||||
}
|
||||
}
|
||||
.await;
|
||||
@@ -789,6 +989,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
);
|
||||
d.add("lsp_virtual_document", |c| async move { lsp_virtual_document(&c.host, &c.window, c.arg("uri")?).await });
|
||||
d.add("lsp_references", |c| async move {
|
||||
let on_partial = c.sender("onPartial")?;
|
||||
lsp_references(
|
||||
&c.host,
|
||||
&c.window,
|
||||
@@ -797,6 +998,8 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
c.arg("pos")?,
|
||||
c.arg("includeDeclaration")?,
|
||||
c.arg("projectWide")?,
|
||||
c.arg("libraries")?,
|
||||
on_partial,
|
||||
)
|
||||
.await
|
||||
});
|
||||
@@ -907,18 +1110,172 @@ mod tests {
|
||||
kind: None,
|
||||
preferred: false,
|
||||
edits,
|
||||
operations: Vec::new(),
|
||||
open: None,
|
||||
data: data.map(str::to_owned),
|
||||
file_action: false,
|
||||
};
|
||||
let lazy = plugin_code_action("acme.x", action(Vec::new(), Some("ref")));
|
||||
let root = Path::new("/p");
|
||||
let lazy = plugin_code_action("acme.x", root, action(Vec::new(), Some("ref")));
|
||||
assert!(lazy.edit.is_none());
|
||||
let r: PluginActionRef = serde_json::from_value(lazy.data.unwrap()).unwrap();
|
||||
assert_eq!((r.plugin.as_str(), r.data.as_str()), ("acme.x", "ref"));
|
||||
assert_eq!((r.plugin.as_str(), r.data.as_deref()), ("acme.x", Some("ref")));
|
||||
// With edits, `data` is the plugin's business: applied as is.
|
||||
let edit = TextEdit { range: Range::default(), new_text: "x".into() };
|
||||
let eager = plugin_code_action("acme.x", action(vec![("/a".into(), vec![edit])], Some("ref")));
|
||||
let eager = plugin_code_action("acme.x", root, action(vec![("/a".into(), vec![edit])], Some("ref")));
|
||||
assert!(eager.edit.is_some() && eager.data.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_definitions_own_strings_and_join_the_server_elsewhere() {
|
||||
let at = |path: &str, line: u32| Location {
|
||||
path: path.into(),
|
||||
range: Range::new(Pos::new(line, 0), Pos::new(line, 4)),
|
||||
uri: None,
|
||||
};
|
||||
let paths = |found: IdeResult<Vec<Location>>| {
|
||||
found.unwrap().into_iter().map(|l| l.path.to_string_lossy().into_owned()).collect::<Vec<_>>()
|
||||
};
|
||||
let xml = at("/p/src/main/resources/UserMapper.xml", 3);
|
||||
let java = at("/p/src/main/java/UserMapper.java", 7);
|
||||
let helper = at("/p/_ide_helper.php", 1);
|
||||
let route = at("/p/routes/web.php", 2);
|
||||
let guess = at("/p/app/helpers.php", 9);
|
||||
|
||||
assert_eq!(
|
||||
paths(definition_targets(Ok(vec![java.clone(), helper.clone()]), vec![xml.clone()], false)),
|
||||
["/p/src/main/resources/UserMapper.xml", "/p/src/main/java/UserMapper.java"]
|
||||
);
|
||||
assert_eq!(
|
||||
paths(definition_targets(Ok(vec![xml.clone(), java.clone()]), vec![xml.clone()], false)),
|
||||
["/p/src/main/resources/UserMapper.xml", "/p/src/main/java/UserMapper.java"]
|
||||
);
|
||||
assert_eq!(
|
||||
paths(definition_targets(Ok(vec![guess.clone(), helper.clone()]), vec![route.clone()], true)),
|
||||
["/p/routes/web.php"]
|
||||
);
|
||||
assert_eq!(
|
||||
paths(definition_targets(Err(ide_core::IdeError::unavailable("no server")), vec![route.clone()], false)),
|
||||
["/p/routes/web.php"]
|
||||
);
|
||||
assert_eq!(paths(definition_targets(Ok(vec![helper, guess]), Vec::new(), false)), ["/p/app/helpers.php"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positions_inside_string_literals_are_told_apart() {
|
||||
let syntax = std::sync::Arc::new(ide_language::Syntax::new());
|
||||
let structure = ide_syntax::StructureService::new(std::sync::Arc::new(ide_language::SyntaxCache::new(syntax)));
|
||||
let php = ide_core::LanguageId::new("php");
|
||||
let text = "<?php\nreturn to_route('users.show', $user);\necho \"Hi {$name}\";\n";
|
||||
let snap = ide_syntax::Snapshot::text(&php, text);
|
||||
assert!(string_at(&structure, &snap, Pos::new(1, 20)), "inside 'users.show'");
|
||||
assert!(!string_at(&structure, &snap, Pos::new(1, 9)), "on to_route");
|
||||
assert!(!string_at(&structure, &snap, Pos::new(1, 35)), "on $user");
|
||||
assert!(!string_at(&structure, &snap, Pos::new(2, 12)), "on an interpolated variable");
|
||||
let java = ide_core::LanguageId::new("java");
|
||||
let text = "class A {\n User find(long id) { return mapper.selectById(\"users\"); }\n}\n";
|
||||
let snap = ide_syntax::Snapshot::text(&java, text);
|
||||
assert!(!string_at(&structure, &snap, Pos::new(1, 9)), "on a method name");
|
||||
assert!(string_at(&structure, &snap, Pos::new(1, 53)), "inside \"users\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_ide_helpers_give_way_to_real_declarations() {
|
||||
let at = |path: &str| Location { path: path.into(), range: Range::default(), uri: None };
|
||||
let paths =
|
||||
|found: Vec<Location>| found.into_iter().map(|l| l.path.to_string_lossy().into_owned()).collect::<Vec<_>>();
|
||||
let real = at("/app/app/Models/User.php");
|
||||
let helper = at("/app/_ide_helper_models.php");
|
||||
let meta = at("/app/.phpstorm.meta.php");
|
||||
let vendor = at("/app/vendor/_laravel_idea/_ide_helper.php");
|
||||
assert_eq!(
|
||||
paths(without_generated_helpers(vec![helper.clone(), real.clone(), meta.clone(), vendor])),
|
||||
["/app/app/Models/User.php"]
|
||||
);
|
||||
assert_eq!(
|
||||
paths(without_generated_helpers(vec![helper.clone(), meta.clone()])),
|
||||
["/app/_ide_helper_models.php", "/app/.phpstorm.meta.php"]
|
||||
);
|
||||
assert!(without_generated_helpers(Vec::new()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plugin_action_maps_its_file_operations_before_its_edits_and_stays_in_the_project() {
|
||||
use ide_core::FileEdit;
|
||||
use ide_plugin::FileOperation;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("proj");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let root = root.canonicalize().unwrap();
|
||||
let action = |operations: Vec<FileOperation>| ide_plugin::CodeAction {
|
||||
title: "Create view".into(),
|
||||
kind: Some("quickfix".into()),
|
||||
preferred: false,
|
||||
edits: vec![(root.join("a.txt"), vec![TextEdit { range: Range::default(), new_text: "x".into() }])],
|
||||
operations,
|
||||
open: Some(root.join("views/home.html")),
|
||||
data: None,
|
||||
file_action: true,
|
||||
};
|
||||
|
||||
let created = plugin_code_action(
|
||||
"acme.x",
|
||||
&root,
|
||||
action(vec![
|
||||
FileOperation::Create { path: "views/home.html".into(), text: "<h1/>".into(), overwrite: false },
|
||||
FileOperation::Rename { from: root.join("old.txt"), to: root.join("new.txt") },
|
||||
FileOperation::Delete { path: root.join("gone.txt") },
|
||||
]),
|
||||
);
|
||||
assert_eq!(created.disabled_reason, None);
|
||||
let files = created.edit.unwrap().files;
|
||||
let home = root.join("views/home.html");
|
||||
assert!(matches!(&files[0], FileEdit::Create { path, overwrite: false } if **path == home));
|
||||
assert!(
|
||||
matches!(&files[1], FileEdit::Edit { path, edits, .. } if **path == home && edits[0].new_text == "<h1/>")
|
||||
);
|
||||
assert!(matches!(&files[2], FileEdit::Rename { to, .. } if **to == root.join("new.txt")));
|
||||
assert!(matches!(&files[3], FileEdit::Delete { recursive: false, .. }));
|
||||
assert!(matches!(&files[4], FileEdit::Edit { path, .. } if **path == root.join("a.txt")));
|
||||
let r: PluginActionRef = serde_json::from_value(created.data.unwrap()).unwrap();
|
||||
assert_eq!(r.data, None);
|
||||
assert!(r.file, "resolved by the file-actions export");
|
||||
let opened = r.open.unwrap().to_path_buf();
|
||||
assert!(opened.components().eq(dunce::simplified(&home).components()), "{opened:?}");
|
||||
|
||||
let outside = tmp.path().join("evil.txt");
|
||||
let mut open_outside = action(Vec::new());
|
||||
open_outside.open = Some(outside.clone());
|
||||
assert!(plugin_code_action("acme.x", &root, open_outside).disabled_reason.is_some());
|
||||
let mut edit_outside = action(vec![FileOperation::Delete { path: root.join("gone.txt") }]);
|
||||
edit_outside.edits.push((outside, Vec::new()));
|
||||
assert!(plugin_code_action("acme.x", &root, edit_outside).disabled_reason.is_some());
|
||||
let mut edit_created =
|
||||
action(vec![FileOperation::Create { path: root.join("n.txt"), text: "x".into(), overwrite: false }]);
|
||||
edit_created.edits = vec![(root.join("n.txt"), Vec::new())];
|
||||
assert!(plugin_code_action("acme.x", &root, edit_created).disabled_reason.is_some());
|
||||
|
||||
for outside in [tmp.path().join("evil.txt"), "../evil.txt".into()] {
|
||||
for operation in [
|
||||
FileOperation::Create { path: outside.clone(), text: String::new(), overwrite: false },
|
||||
FileOperation::Rename { from: root.join("old.txt"), to: outside.clone() },
|
||||
FileOperation::Delete { path: outside.clone() },
|
||||
] {
|
||||
let rejected = plugin_code_action("acme.x", &root, action(vec![operation]));
|
||||
assert!(rejected.disabled_reason.is_some_and(|r| r.contains("outside the project root")));
|
||||
assert!(rejected.edit.unwrap().files.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
// `data` and nothing to apply: the file-actions export computes it when picked.
|
||||
let mut lazy = action(Vec::new());
|
||||
(lazy.edits, lazy.open, lazy.data) = (Vec::new(), None, Some("ref".into()));
|
||||
let lazy = plugin_code_action("acme.x", &root, lazy);
|
||||
assert!(lazy.edit.is_none());
|
||||
let r: PluginActionRef = serde_json::from_value(lazy.data.unwrap()).unwrap();
|
||||
assert_eq!((r.data.as_deref(), r.file), (Some("ref"), true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_completion_kind_the_plugin_api_documents_is_understood() {
|
||||
let wit = include_str!("../../../../wit/providers.wit");
|
||||
|
||||
@@ -28,9 +28,12 @@ pub fn configs(host: &Host, window: &str) -> IdeResult<Vec<RunConfig>> {
|
||||
task.target = format!("workspace:{}:{}", key, task.target);
|
||||
}
|
||||
}
|
||||
for id in &mut config.extras.compound {
|
||||
*id = format!("workspace:{key}:{id}");
|
||||
}
|
||||
config.id = format!("workspace:{}:{}", key, config.id);
|
||||
config.name = format!("{name} / {}", config.name);
|
||||
config.cwd = Some(config.cwd.map(|p| member.join(&*p)).unwrap_or_else(|| member.clone()).into());
|
||||
ide_run::scope::rebase(&mut config, &member, None);
|
||||
config.detected = true;
|
||||
if !user.iter().any(|u| u.id == config.id) && !root_suppressed.contains(&config.id) {
|
||||
all.push(config);
|
||||
@@ -51,10 +54,18 @@ fn detected_and_saved(
|
||||
suppressed: &[String],
|
||||
) -> Vec<RunConfig> {
|
||||
let excluded_poms = crate::project::unlinked_maven_poms(root, settings);
|
||||
let gradle = settings
|
||||
.languages
|
||||
.java
|
||||
.gradle
|
||||
.linked_projects
|
||||
.as_ref()
|
||||
.map(|_| ide_build::gradle::load_linked(root, &settings.languages.java.gradle));
|
||||
let mut all: Vec<RunConfig> =
|
||||
ide_run::detect_with_profiles(root, &excluded_poms, settings.cmake.profiles.as_deref())
|
||||
.into_iter()
|
||||
.filter(|d| !suppressed.contains(&d.id) && !saved.iter().any(|u| u.id == d.id))
|
||||
.filter(|d| linked_config(root, gradle.as_deref(), &excluded_poms, d))
|
||||
.collect();
|
||||
all.extend(saved.iter().cloned());
|
||||
for config in all.iter_mut().filter(|c| !matches!(c.kind.as_str(), "gradle" | "maven")) {
|
||||
@@ -63,6 +74,41 @@ fn detected_and_saved(
|
||||
all
|
||||
}
|
||||
|
||||
fn linked_config(
|
||||
root: &std::path::Path,
|
||||
gradle: Option<&[ide_build::GradleModel]>,
|
||||
excluded_poms: &[std::path::PathBuf],
|
||||
config: &RunConfig,
|
||||
) -> bool {
|
||||
let module = config
|
||||
.extras
|
||||
.module
|
||||
.as_deref()
|
||||
.map(std::path::Path::new)
|
||||
.or(config.cwd.as_deref())
|
||||
.unwrap_or(std::path::Path::new(""));
|
||||
let owner = ide_core::project_roots::resolve(root, module);
|
||||
if matches!(config.kind.as_str(), "maven" | "application" | "spring-boot")
|
||||
&& excluded_poms.iter().any(|pom| ide_core::project_roots::resolve(root, pom).parent() == Some(owner.as_path()))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if gradle.is_some()
|
||||
&& (config.kind == "gradle"
|
||||
|| (matches!(config.kind.as_str(), "application" | "spring-boot")
|
||||
&& ["build.gradle", "build.gradle.kts"].iter().any(|name| owner.join(name).is_file())))
|
||||
{
|
||||
return gradle.unwrap_or_default().iter().any(|build| {
|
||||
if config.kind == "gradle" {
|
||||
root.join(&build.dir) == owner
|
||||
} else {
|
||||
build.projects.iter().any(|p| root.join(&p.dir) == owner)
|
||||
}
|
||||
});
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Saves the user configurations. They come from [`configs`], toolchains applied, so what
|
||||
/// settings derived is dropped again: only the user's own choices reach `run.toml`.
|
||||
pub fn save_configs(
|
||||
@@ -87,11 +133,22 @@ pub fn save_configs(
|
||||
fn settings_for(
|
||||
host: &Host,
|
||||
project: &crate::project::Project,
|
||||
config: &RunConfig,
|
||||
config: &mut RunConfig,
|
||||
) -> IdeResult<(std::path::PathBuf, ide_core::settings::Settings)> {
|
||||
let member = ide_workspace::workspace::Workspace::load(&project.root)?.and_then(|workspace| {
|
||||
let cwd = config.cwd.as_deref()?;
|
||||
workspace.projects.into_iter().filter(|root| cwd.starts_with(root)).max_by_key(|root| root.components().count())
|
||||
let workspace = ide_workspace::workspace::Workspace::load(&project.root)?;
|
||||
if workspace.is_some() {
|
||||
if config.extras.module.is_none() && !matches!(config.kind.as_str(), "application" | "spring-boot") {
|
||||
config.extras.module = config.cwd.as_deref().map(ide_core::ipc_path::to_ipc);
|
||||
}
|
||||
ide_run::scope::rebase(config, &project.root, None);
|
||||
}
|
||||
let member = workspace.and_then(|workspace| {
|
||||
let owner = ide_run::scope::owner(&project.root, config);
|
||||
workspace
|
||||
.projects
|
||||
.into_iter()
|
||||
.filter(|root| owner.starts_with(root))
|
||||
.max_by_key(|root| root.components().count())
|
||||
});
|
||||
Ok(match member {
|
||||
Some(root) => {
|
||||
@@ -109,11 +166,11 @@ pub fn without_derived(host: &Host, window: &str, configs: Vec<RunConfig>) -> Id
|
||||
let project = host.project(window)?;
|
||||
configs
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
.map(|mut c| {
|
||||
if c.kind == "gradle" {
|
||||
return Ok(c);
|
||||
}
|
||||
let (root, settings) = settings_for(host, &project, &c)?;
|
||||
let (root, settings) = settings_for(host, &project, &mut c)?;
|
||||
Ok(ide_sdk::apply::without_derived(&c, &root, &settings))
|
||||
})
|
||||
.collect()
|
||||
@@ -127,7 +184,7 @@ pub fn apply_settings(host: &Host, window: &str, configs: Vec<RunConfig>) -> Ide
|
||||
.into_iter()
|
||||
.map(|mut c| {
|
||||
if c.kind != "gradle" {
|
||||
let (root, settings) = settings_for(host, &project, &c)?;
|
||||
let (root, settings) = settings_for(host, &project, &mut c)?;
|
||||
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut c), &root, &settings);
|
||||
}
|
||||
Ok(c)
|
||||
@@ -174,13 +231,13 @@ pub async fn start(host: &Host, window: &str, config: RunConfig, on_output: Emit
|
||||
.run(&settings, &project.root, &config, project.sink.clone(), Box::new(move |c| out(c)))
|
||||
.await;
|
||||
}
|
||||
let (root, settings) = settings_for(host, &project, &config)?;
|
||||
let mut config = config;
|
||||
let (root, settings) = settings_for(host, &project, &mut config)?;
|
||||
let root = &root;
|
||||
// Configurations made in the UI name bare tools (`godot`) that may live outside PATH.
|
||||
// Maven re-applies too: a config listed before a settings change (daemon toggle,
|
||||
// Maven home) keeps the launcher that was current then; re-resolving at launch is
|
||||
// what makes the setting take effect without reopening the project.
|
||||
let mut config = config;
|
||||
if config.kind == "maven" {
|
||||
ide_sdk::apply::prepare_maven_run(&mut config, root, &settings);
|
||||
} else if matches!(config.kind.as_str(), "gradle" | "tomcat") {
|
||||
@@ -295,3 +352,31 @@ pub fn list(host: &Host) -> Vec<RunInfo> {
|
||||
mod commands;
|
||||
mod container;
|
||||
pub use commands::*;
|
||||
|
||||
#[cfg(test)]
|
||||
mod ownership_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn unlinked_builds_do_not_reappear_as_detected_application_configs() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
for name in ["maven", "gradle"] {
|
||||
let dir = root.join(name);
|
||||
std::fs::create_dir_all(dir.join("src/main/java")).unwrap();
|
||||
std::fs::write(
|
||||
dir.join("src/main/java/App.java"),
|
||||
"@SpringBootApplication class App { public static void main(String[] a) {} }",
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
std::fs::write(root.join("maven/pom.xml"), "<project><build><plugins><plugin><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>").unwrap();
|
||||
std::fs::write(root.join("gradle/build.gradle.kts"), "plugins { id(\"org.springframework.boot\") }").unwrap();
|
||||
let defaults = detected_and_saved(root, &Default::default(), &[], &[]);
|
||||
assert!(defaults.iter().any(|c| c.kind == "spring-boot"));
|
||||
let mut settings = ide_core::settings::Settings::default();
|
||||
settings.languages.java.maven.unlinked_projects = vec!["maven/pom.xml".into()];
|
||||
settings.languages.java.gradle.linked_projects = Some(vec![]);
|
||||
let configs = detected_and_saved(root, &settings, &[], &[]);
|
||||
assert!(configs.is_empty(), "{configs:?}");
|
||||
}
|
||||
}
|
||||
@@ -181,6 +181,16 @@ pub async fn run_tomcat_home(host: &Host, window: &str, home: String) -> IdeResu
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
pub async fn run_tomcat_installations(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
) -> IdeResult<Vec<ide_run::tomcat::TomcatInstallation>> {
|
||||
host.require_trust(window)?;
|
||||
tokio::task::spawn_blocking(ide_run::tomcat::detect_installations)
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
}
|
||||
|
||||
pub async fn run_tomcat_artifacts(host: &Host, window: &str) -> IdeResult<Vec<ide_build::web::WebArtifact>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
@@ -212,7 +222,7 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
|
||||
&project.root,
|
||||
&model,
|
||||
id,
|
||||
&ide_run::tomcat::base_dir(&project.cache_dir, &config.id),
|
||||
&ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?,
|
||||
)?;
|
||||
plan.env.extend(config.env.clone());
|
||||
let mut build = RunConfig {
|
||||
@@ -278,7 +288,7 @@ pub async fn run_tomcat_sync(
|
||||
let module = dunce::canonicalize(project.root.join(module))?;
|
||||
let class_paths: Vec<_> =
|
||||
class_paths.iter().filter_map(|p| dunce::canonicalize(project.root.join(p)).ok()).collect();
|
||||
let base = ide_run::tomcat::base_dir(&project.cache_dir, &config.id);
|
||||
let base = ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?;
|
||||
ide_run::tomcat::sync_outputs(&base, &module, &class_paths, resources_only)
|
||||
})
|
||||
.await
|
||||
@@ -297,6 +307,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
run_application_publish(&c.host, &c.window, c.arg("config")?, c.arg("classPaths")?, c.arg("mainClass")?).await
|
||||
});
|
||||
d.add("run_tomcat_home", |c| async move { run_tomcat_home(&c.host, &c.window, c.arg("home")?).await });
|
||||
d.add("run_tomcat_installations", |c| async move { run_tomcat_installations(&c.host, &c.window).await });
|
||||
d.add("run_tomcat_artifacts", |c| async move { run_tomcat_artifacts(&c.host, &c.window).await });
|
||||
d.add("run_tomcat_build", |c| async move { run_tomcat_build(&c.host, &c.window, c.arg("config")?).await });
|
||||
d.add("run_tomcat_sync", |c| async move {
|
||||
|
||||
@@ -6,19 +6,32 @@ use ide_core::remote_settings::{RunTarget, RunTargetKind};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_docker::DockerEndpoint;
|
||||
use ide_remote::docker::{
|
||||
ContainerRun, compose_container_root, container_config, container_name, default_container_root,
|
||||
ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, compose_container_root, container_config,
|
||||
container_name, default_container_root,
|
||||
};
|
||||
use ide_run::RunConfig;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Set by the Debug action on a configuration that runs on a container target: the
|
||||
/// program starts under debugpy and waits for the debugger.
|
||||
const DEBUG_PARAM: &str = "containerDebug";
|
||||
|
||||
/// `config` rewritten to run in a new container of `target`'s image or service.
|
||||
pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config: RunConfig) -> IdeResult<RunConfig> {
|
||||
if config.kind == "dotnet" || config.kind == "dotnet-test" {
|
||||
return Err(IdeError::invalid(".NET Project requires the local machine"));
|
||||
}
|
||||
let debug = config.extras.params.get(DEBUG_PARAM).is_some_and(|v| v == "true");
|
||||
if debug && config.debug_adapter.as_deref() != Some("debugpy") {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"'{}' can't be debugged in a container: only Python run configurations can",
|
||||
config.name
|
||||
)));
|
||||
}
|
||||
let endpoint = endpoint(&host.data_dir, &target)?;
|
||||
let root = root.to_path_buf();
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || {
|
||||
if !ide_docker::endpoint_is_local(&endpoint)? {
|
||||
return Err(IdeError::invalid(format!(
|
||||
@@ -39,6 +52,7 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
|
||||
};
|
||||
let file_env = env_files(&root, &config)?;
|
||||
let name = container_name(&config.id, &unique());
|
||||
let debugging = if debug { Some(Debugging::prepare(&data_dir)?) } else { None };
|
||||
container_config(
|
||||
&config,
|
||||
&ContainerRun {
|
||||
@@ -50,12 +64,45 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
|
||||
file_env: &file_env,
|
||||
name: &name,
|
||||
user: user(&root, &target),
|
||||
debug: debugging.as_ref().map(|d| ContainerDebug {
|
||||
port: d.port,
|
||||
bootstrap_dir: &d.bootstrap_dir,
|
||||
debugpy: d.debugpy.as_deref(),
|
||||
}),
|
||||
},
|
||||
)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// What a debug run mounts and publishes.
|
||||
struct Debugging {
|
||||
port: u16,
|
||||
bootstrap_dir: PathBuf,
|
||||
debugpy: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Debugging {
|
||||
fn prepare(data_dir: &Path) -> IdeResult<Self> {
|
||||
// The bootstrap is (re)written on each run, so it matches this version of the IDE.
|
||||
let bootstrap_dir = data_dir.join("container-debug");
|
||||
std::fs::create_dir_all(&bootstrap_dir)?;
|
||||
std::fs::write(bootstrap_dir.join(DEBUG_BOOTSTRAP_NAME), DEBUG_BOOTSTRAP)?;
|
||||
// The managed install the local debugger falls back to (`ide_dap::adapter::prepare_debugpy`).
|
||||
let tools = ide_dap::adapter::tools_root().unwrap_or_else(|| ide_tools::tools_dir(data_dir));
|
||||
let lib = ide_tools::python_lib_dir(&tools, ide_dap::adapter::DEBUGPY_TOOL);
|
||||
let debugpy = lib.join("debugpy").join("__init__.py").is_file().then_some(lib);
|
||||
Ok(Self { port: free_port()?, bootstrap_dir, debugpy })
|
||||
}
|
||||
}
|
||||
|
||||
/// A port nobody listens on here: debugpy listens on the same port in the container,
|
||||
/// published on the loopback interface.
|
||||
fn free_port() -> IdeResult<u16> {
|
||||
let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?;
|
||||
Ok(listener.local_addr()?.port())
|
||||
}
|
||||
|
||||
/// The target's Docker connection (Services tool window), by id; none = the CLI's daemon.
|
||||
fn endpoint(data_dir: &Path, target: &RunTarget) -> IdeResult<DockerEndpoint> {
|
||||
let id = target.docker_connection.trim();
|
||||
|
||||
@@ -46,10 +46,21 @@ pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<V
|
||||
}
|
||||
|
||||
/// The interpreter the project uses: the configured one, else its virtualenv.
|
||||
pub fn sdk_python_effective(host: &Host, window: &str) -> IdeResult<Option<ide_core::IpcPath>> {
|
||||
pub fn sdk_python_effective(host: &Host, window: &str, near: Option<PathBuf>) -> IdeResult<Option<ide_core::IpcPath>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
Ok(ide_sdk::apply::python_interpreter(&project.root, &project.settings.effective()).map(Into::into))
|
||||
let member = ide_workspace::workspace::Workspace::load(&project.root)?.and_then(|w| {
|
||||
let near = near.as_deref()?;
|
||||
w.projects.into_iter().filter(|root| near.starts_with(root)).max_by_key(|root| root.components().count())
|
||||
});
|
||||
let (root, settings) = match member {
|
||||
Some(root) => {
|
||||
let settings = ide_workspace::SettingsStore::load(&host.config_dir, Some(&root)).effective();
|
||||
(root, settings)
|
||||
}
|
||||
None => (project.root.clone(), project.settings.effective()),
|
||||
};
|
||||
Ok(ide_sdk::apply::python_interpreter_near(&root, near.as_deref(), &settings).map(Into::into))
|
||||
}
|
||||
|
||||
/// The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`.
|
||||
@@ -60,6 +71,19 @@ pub fn sdk_php_effective(host: &Host, window: &str) -> IdeResult<Option<ide_core
|
||||
Ok(ide_sdk::apply::setting_path(&project.root, &settings.languages.php.interpreter).map(Into::into))
|
||||
}
|
||||
|
||||
/// The version of the PHP interpreter `php` and of the Xdebug it loads, run in `cwd` (default: the
|
||||
/// project root).
|
||||
pub async fn sdk_php_xdebug(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
php: PathBuf,
|
||||
cwd: Option<PathBuf>,
|
||||
) -> IdeResult<ide_sdk::php::PhpXdebug> {
|
||||
host.require_trust(window)?;
|
||||
let cwd = cwd.or_else(|| host.project(window).ok().map(|p| p.root.clone()));
|
||||
tokio::task::spawn_blocking(move || ide_sdk::php::xdebug(&php, cwd.as_deref())).await.map_err(join_err)?
|
||||
}
|
||||
|
||||
/// The PHP language level of the project `path` belongs to (a workspace member, by path, as
|
||||
/// the language server configuration picks it).
|
||||
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
|
||||
@@ -125,25 +149,56 @@ pub async fn sdk_php_composer_install(
|
||||
|
||||
/// SDK / library source folders shown under "External Libraries" in the Project view,
|
||||
/// with the Maven / Gradle dependency jars of the build model.
|
||||
pub async fn sdk_project_libraries(host: &Host, window: &str) -> IdeResult<Vec<ide_sdk::libraries::LibraryGroup>> {
|
||||
pub async fn sdk_project_libraries(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
on_groups: Channel<Vec<ide_sdk::libraries::LibraryGroup>>,
|
||||
) -> IdeResult<Vec<ide_sdk::libraries::LibraryGroup>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let (root, cache, settings) = (project.root.clone(), project.build_cache_dir(), project.settings.effective());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = crate::ops::build::load(&root, &cache, &settings);
|
||||
let deps: Vec<ide_sdk::libraries::BuildDependency> = ide_build::dependency_coordinates(&root, &model)
|
||||
.into_iter()
|
||||
.map(|c| ide_sdk::libraries::BuildDependency {
|
||||
gradle: c.gradle,
|
||||
group: c.group_id,
|
||||
artifact: c.artifact_id,
|
||||
version: c.version,
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let libraries = {
|
||||
let (root, settings, cancel, on_groups) = (root.clone(), settings.clone(), cancel.clone(), on_groups.clone());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
ide_sdk::libraries::project_libraries_stream(&root, &settings, &[], &cancel, &|groups| {
|
||||
let _ = on_groups.send(groups);
|
||||
})
|
||||
.collect();
|
||||
ide_sdk::libraries::project_libraries(&root, &settings, &deps)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)
|
||||
})
|
||||
};
|
||||
let dependencies = {
|
||||
let cancel = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
if cancel.is_cancelled() {
|
||||
return Vec::new();
|
||||
}
|
||||
let model = crate::ops::build::load(&root, &cache, &settings);
|
||||
let deps: Vec<ide_sdk::libraries::BuildDependency> = ide_build::dependency_coordinates(&root, &model)
|
||||
.into_iter()
|
||||
.map(|c| ide_sdk::libraries::BuildDependency {
|
||||
gradle: c.gradle,
|
||||
group: c.group_id,
|
||||
artifact: c.artifact_id,
|
||||
version: c.version,
|
||||
})
|
||||
.collect();
|
||||
if cancel.is_cancelled() {
|
||||
return Vec::new();
|
||||
}
|
||||
let groups = ide_sdk::libraries::dependency_groups(&root, &settings, &deps);
|
||||
if !cancel.is_cancelled() {
|
||||
let _ = on_groups.send(groups.clone());
|
||||
}
|
||||
groups
|
||||
})
|
||||
};
|
||||
let (libraries, dependencies) = tokio::join!(libraries, dependencies);
|
||||
host.end_request(request);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
Ok(ide_sdk::libraries::merge_groups([libraries.map_err(join_err)?, dependencies.map_err(join_err)?].concat()))
|
||||
}
|
||||
|
||||
/// Looks up `names` (bare command names): `node_modules/.bin` above `near`, then the search path.
|
||||
@@ -162,10 +217,11 @@ pub async fn sdk_locate_tools(
|
||||
.map_err(join_err)
|
||||
}
|
||||
|
||||
/// `base -m venv location`; output lines stream through `on_output`.
|
||||
/// Creates a Python environment with `tool` (`venv` / `uv` / `poetry`); output streams through `on_output`.
|
||||
pub async fn sdk_python_create_venv(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
tool: ide_sdk::python::VenvTool,
|
||||
base: PathBuf,
|
||||
location: PathBuf,
|
||||
request: RequestId,
|
||||
@@ -174,7 +230,7 @@ pub async fn sdk_python_create_venv(
|
||||
host.require_trust(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
ide_sdk::python::create_venv(&base, &location, &cancel, &|line| {
|
||||
ide_sdk::python::create_venv(tool, &base, &location, &cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
@@ -232,8 +288,9 @@ pub async fn sdk_python_pip(
|
||||
/// Commands of this module the remote server answers.
|
||||
pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("sdk_detect", |c| async move { sdk_detect(&c.host, &c.window, c.arg("kind")?).await });
|
||||
d.add("sdk_python_effective", |c| async move { sdk_python_effective(&c.host, &c.window) });
|
||||
d.add("sdk_python_effective", |c| async move { sdk_python_effective(&c.host, &c.window, c.arg("near")?) });
|
||||
d.add("sdk_php_effective", |c| async move { sdk_php_effective(&c.host, &c.window) });
|
||||
d.add("sdk_php_xdebug", |c| async move { sdk_php_xdebug(&c.host, &c.window, c.arg("php")?, c.arg("cwd")?).await });
|
||||
d.add(
|
||||
"sdk_php_language_level",
|
||||
|c| async move { sdk_php_language_level(&c.host, &c.window, c.arg("path")?).await },
|
||||
@@ -242,7 +299,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
"sdk_php_composer_install",
|
||||
|c| async move { sdk_php_composer_install(&c.host, &c.window, c.arg("path")?).await },
|
||||
);
|
||||
d.add("sdk_project_libraries", |c| async move { sdk_project_libraries(&c.host, &c.window).await });
|
||||
d.add("sdk_project_libraries", |c| async move {
|
||||
sdk_project_libraries(&c.host, &c.window, c.arg("request")?, c.sender("onGroups")?).await
|
||||
});
|
||||
d.add("sdk_locate_tools", |c| async move {
|
||||
sdk_locate_tools(&c.host, &c.window, c.arg("names")?, c.arg("near")?).await
|
||||
});
|
||||
@@ -250,6 +309,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
sdk_python_create_venv(
|
||||
&c.host,
|
||||
&c.window,
|
||||
c.arg("tool")?,
|
||||
c.arg("base")?,
|
||||
c.arg("location")?,
|
||||
c.arg("request")?,
|
||||
|
||||
@@ -583,12 +583,15 @@ pub async fn vcs_create_branch(
|
||||
name: String,
|
||||
start: Option<String>,
|
||||
checkout: bool,
|
||||
overwrite: Option<bool>,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let recorded = checkout.then_some("Git checkout");
|
||||
blocking(move || {
|
||||
project.with_repo_recorded(repo.as_deref(), recorded, |r| r.create_branch(&name, start.as_deref(), checkout))
|
||||
project.with_repo_recorded(repo.as_deref(), recorded, |r| {
|
||||
r.create_branch_with_overwrite(&name, start.as_deref(), checkout, overwrite.unwrap_or(false))
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -1335,7 +1338,16 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
vcs_checkout(&c.host, &c.window, c.arg("repo")?, c.arg("branch")?, c.arg("create")?, c.arg("options")?).await
|
||||
});
|
||||
d.add("vcs_create_branch", |c| async move {
|
||||
vcs_create_branch(&c.host, &c.window, c.arg("repo")?, c.arg("name")?, c.arg("start")?, c.arg("checkout")?).await
|
||||
vcs_create_branch(
|
||||
&c.host,
|
||||
&c.window,
|
||||
c.arg("repo")?,
|
||||
c.arg("name")?,
|
||||
c.arg("start")?,
|
||||
c.arg("checkout")?,
|
||||
c.arg("overwrite")?,
|
||||
)
|
||||
.await
|
||||
});
|
||||
d.add(
|
||||
"vcs_undo_commit",
|
||||
|
||||
+1533
-73
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,28 @@
|
||||
//! The Commit view's side of the `commit` API, as the window commands
|
||||
//! `plugin_answer_commit` / `plugin_commit_checks` serve it — the desktop for
|
||||
//! local projects, `openidea-server` for remote ones.
|
||||
|
||||
use super::{CommitSelection, PluginCommitCheckRef, PluginCommitCheckResult, PluginHost};
|
||||
use ide_core::{IdeError, IdeResult, RequestId};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Runs the plugins' before-commit checks `checks` on what `selection` commits,
|
||||
/// until request `request` is cancelled.
|
||||
pub async fn commit_checks(
|
||||
host: &crate::Host,
|
||||
plugins: Arc<PluginHost>,
|
||||
window: &str,
|
||||
selection: CommitSelection,
|
||||
checks: Vec<PluginCommitCheckRef>,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Vec<PluginCommitCheckResult>> {
|
||||
host.require_trust(window)?;
|
||||
let invocation = super::views::view_invocation(host, window, None, None)?;
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || plugins.commit_checks(invocation, selection, checks, &cancel))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
.and_then(|r| r);
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! Versioned, project-scoped diagnostics for unsaved editor buffers.
|
||||
use super::{PluginHost, ProviderKind, editor_plugin_host};
|
||||
use ide_core::{CancellationToken, Diagnostic, DocId, IdeEvent, SharedSink};
|
||||
use ide_plugin::ProviderDocument;
|
||||
use ide_text::AppliedChange;
|
||||
use ide_workspace::documents::DocumentObserver;
|
||||
use ide_workspace::{DocumentInfo, Documents};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
const DEBOUNCE: Duration = Duration::from_millis(300);
|
||||
|
||||
struct Document {
|
||||
snapshot: ProviderDocument,
|
||||
cancel: CancellationToken,
|
||||
sources: HashSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
closed: bool,
|
||||
documents: HashMap<DocId, Document>,
|
||||
generations: HashMap<String, u64>,
|
||||
}
|
||||
|
||||
/// One incarnation of one project's documents, shared by all its editors.
|
||||
pub(crate) struct Diagnostics {
|
||||
state: Arc<Mutex<State>>,
|
||||
sink: SharedSink,
|
||||
runtime: tokio::runtime::Handle,
|
||||
documents: Weak<Documents>,
|
||||
root: std::path::PathBuf,
|
||||
}
|
||||
|
||||
impl Diagnostics {
|
||||
pub fn new(
|
||||
sink: SharedSink,
|
||||
runtime: tokio::runtime::Handle,
|
||||
documents: &Arc<Documents>,
|
||||
root: &Path,
|
||||
) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
state: Arc::default(),
|
||||
sink,
|
||||
runtime,
|
||||
documents: Arc::downgrade(documents),
|
||||
root: root.to_path_buf(),
|
||||
})
|
||||
}
|
||||
|
||||
fn emit(&self, path: &Path, plugin: &str, items: Vec<Diagnostic>) {
|
||||
self.sink.emit(IdeEvent::Diagnostics {
|
||||
path: path.to_path_buf().into(),
|
||||
source: format!("plugin-provider:{plugin}"),
|
||||
items,
|
||||
});
|
||||
}
|
||||
|
||||
fn clear_document(&self, doc: &Document) {
|
||||
doc.cancel.cancel();
|
||||
for plugin in &doc.sources {
|
||||
self.emit(&doc.snapshot.path, plugin, Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn close(&self) {
|
||||
let mut state = self.state.lock();
|
||||
state.closed = true;
|
||||
for (_, doc) in state.documents.drain() {
|
||||
self.clear_document(&doc);
|
||||
}
|
||||
}
|
||||
|
||||
fn schedule(&self, id: DocId, state: &mut State) {
|
||||
let Some(doc) = state.documents.get_mut(&id) else { return };
|
||||
doc.cancel.cancel();
|
||||
doc.cancel = CancellationToken::new();
|
||||
let Some(host) = editor_plugin_host() else { return };
|
||||
if host.providers.plugins_for(ProviderKind::Diagnostics, &doc.snapshot.language).is_empty() {
|
||||
return;
|
||||
}
|
||||
// Register only once per project incarnation; no project is retained by the host.
|
||||
let weak = Arc::downgrade(&self.state);
|
||||
{
|
||||
let mut projects = host.diagnostic_projects.lock();
|
||||
projects.retain(|(state, _)| state.strong_count() > 0);
|
||||
if !projects.iter().any(|(state, _)| state.ptr_eq(&weak)) {
|
||||
projects.push((weak.clone(), self.sink.clone()));
|
||||
}
|
||||
}
|
||||
let root = self.root.clone();
|
||||
let (mut snapshot, cancel, sink, documents) =
|
||||
(doc.snapshot.clone(), doc.cancel.clone(), self.sink.clone(), self.documents.clone());
|
||||
let lifecycle_generations = state.generations.clone();
|
||||
self.runtime.spawn(async move {
|
||||
tokio::time::sleep(DEBOUNCE).await;
|
||||
if cancel.is_cancelled() || weak.strong_count() == 0 {
|
||||
return;
|
||||
}
|
||||
let _ = tokio::task::spawn_blocking(move || {
|
||||
let Some(documents) = documents.upgrade() else { return };
|
||||
let Ok(current) = documents.snapshot(id) else { return };
|
||||
if u64::from(current.version) != snapshot.version
|
||||
|| current.path.0 != snapshot.path
|
||||
|| current.language.as_str() != snapshot.language
|
||||
|| cancel.is_cancelled()
|
||||
{
|
||||
return;
|
||||
}
|
||||
snapshot.text = current.text;
|
||||
drop(documents);
|
||||
|
||||
let generations = host.providers.diagnostic_generations(&snapshot.language);
|
||||
let results = if snapshot.text.len() <= super::navigation::MAX_DOCUMENT_BYTES {
|
||||
host.provide_project_diagnostics(Some(&root), &snapshot, &cancel)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let Some(state) = weak.upgrade() else { return };
|
||||
let mut state = state.lock();
|
||||
if state.closed || cancel.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
let matching: HashSet<_> = host
|
||||
.diagnostic_plugins(Some(&root), &snapshot.language)
|
||||
.into_iter()
|
||||
.map(|p| p.id().to_owned())
|
||||
.filter(|p| lifecycle_generations.get(p) == state.generations.get(p))
|
||||
.collect();
|
||||
let latest = host.providers.diagnostic_generations(&snapshot.language);
|
||||
let Some(doc) = state.documents.get_mut(&id) else { return };
|
||||
if doc.snapshot.version != snapshot.version || doc.snapshot.path != snapshot.path {
|
||||
return;
|
||||
}
|
||||
let mut current = HashSet::new();
|
||||
for (plugin, items) in results {
|
||||
if !matching.contains(&plugin)
|
||||
|| !generations.get(&plugin).is_some_and(|seq| latest.get(&plugin) == Some(seq))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
current.insert(plugin.clone());
|
||||
sink.emit(IdeEvent::Diagnostics {
|
||||
path: snapshot.path.clone().into(),
|
||||
source: format!("plugin-provider:{plugin}"),
|
||||
items,
|
||||
});
|
||||
}
|
||||
for plugin in doc.sources.difference(¤t) {
|
||||
sink.emit(IdeEvent::Diagnostics {
|
||||
path: snapshot.path.clone().into(),
|
||||
source: format!("plugin-provider:{plugin}"),
|
||||
items: Vec::new(),
|
||||
});
|
||||
}
|
||||
doc.sources = current;
|
||||
})
|
||||
.await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl DocumentObserver for Diagnostics {
|
||||
fn opened(&self, info: &DocumentInfo) {
|
||||
let mut state = self.state.lock();
|
||||
if state.closed {
|
||||
return;
|
||||
}
|
||||
if let Some(old) = state.documents.remove(&info.id) {
|
||||
self.clear_document(&old);
|
||||
}
|
||||
if info.large || info.uri.is_some() {
|
||||
return;
|
||||
}
|
||||
state.documents.insert(
|
||||
info.id,
|
||||
Document {
|
||||
snapshot: ProviderDocument {
|
||||
path: info.path.0.clone(),
|
||||
language: info.language.to_string(),
|
||||
version: u64::from(info.version),
|
||||
text: String::new(),
|
||||
},
|
||||
cancel: CancellationToken::new(),
|
||||
sources: HashSet::new(),
|
||||
},
|
||||
);
|
||||
self.schedule(info.id, &mut state);
|
||||
}
|
||||
|
||||
fn changed(&self, id: DocId, path: &Path, version: u32, _: &[AppliedChange], _text: &dyn Fn() -> String) {
|
||||
let mut state = self.state.lock();
|
||||
if state.closed {
|
||||
return;
|
||||
}
|
||||
let Some(doc) = state.documents.get_mut(&id) else { return };
|
||||
if doc.snapshot.path != path {
|
||||
self.clear_document(doc);
|
||||
doc.sources.clear();
|
||||
}
|
||||
doc.snapshot.path = path.to_path_buf();
|
||||
doc.snapshot.version = u64::from(version);
|
||||
self.schedule(id, &mut state);
|
||||
}
|
||||
|
||||
fn closed(&self, id: DocId, _: &Path) {
|
||||
if let Some(doc) = self.state.lock().documents.remove(&id) {
|
||||
self.clear_document(&doc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Diagnostics {
|
||||
fn drop(&mut self) {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) type ProjectState = (Weak<Mutex<State>>, SharedSink);
|
||||
|
||||
impl PluginHost {
|
||||
pub(super) fn clear_provider_diagnostics(&self, plugin: &str) {
|
||||
// Clone before taking a project's state lock (edits register in the other order).
|
||||
let projects = self.diagnostic_projects.lock().clone();
|
||||
for (state, sink) in projects {
|
||||
if let Some(state) = state.upgrade() {
|
||||
let mut state = state.lock();
|
||||
// A completed answer can still be waiting for another provider.
|
||||
*state.generations.entry(plugin.to_owned()).or_default() += 1;
|
||||
for doc in state.documents.values_mut() {
|
||||
if doc.sources.remove(plugin) {
|
||||
sink.emit(IdeEvent::Diagnostics {
|
||||
path: doc.snapshot.path.clone().into(),
|
||||
source: format!("plugin-provider:{plugin}"),
|
||||
items: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
//! `[[contributes.endpoints]]`: HTTP routes a plugin finds in a project. The UI
|
||||
//! asks for them (`plugin_endpoints`); the host caches each plugin's list per
|
||||
//! project until a file matching its globs changes, then emits `EndpointsChanged`.
|
||||
use super::{PluginEvent, PluginHost};
|
||||
use ide_core::{IdeResult, ipc_path::to_ipc};
|
||||
use ide_extension::{Capability, Package, UiDecl, decode};
|
||||
use ide_plugin::{Endpoint, HostError, Invocation};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
pub(super) const POINT: &str = "endpoints";
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Decl {
|
||||
files: Vec<String>,
|
||||
}
|
||||
|
||||
pub(super) fn declaration(pkg: &Package, value: toml::Value) -> Result<UiDecl, String> {
|
||||
let d: Decl = decode(POINT, value)?;
|
||||
pkg.manifest.needs_api("contributes.endpoints", 3)?;
|
||||
if pkg.manifest.wasm.is_none() || d.files.is_empty() || d.files.len() > 64 {
|
||||
return Err("contributes.endpoints needs code and 1–64 file globs".into());
|
||||
}
|
||||
for file in &d.files {
|
||||
if file.is_empty()
|
||||
|| file.len() > 1024
|
||||
|| file.starts_with('/')
|
||||
|| file.contains('\\')
|
||||
|| file.contains(':')
|
||||
|| file.split('/').any(|p| p == "..")
|
||||
{
|
||||
return Err("endpoint file globs must be project-relative".into());
|
||||
}
|
||||
matcher(file).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let key = serde_json::to_string(&d.files).map_err(|e| e.to_string())?;
|
||||
Ok(UiDecl::new(key, "HTTP endpoints", serde_json::to_value(d).map_err(|e| e.to_string())?))
|
||||
}
|
||||
|
||||
fn matcher(glob: &str) -> Result<globset::GlobMatcher, globset::Error> {
|
||||
Ok(globset::GlobBuilder::new(glob).literal_separator(true).build()?.compile_matcher())
|
||||
}
|
||||
|
||||
/// A route as the UI gets it.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginEndpoint {
|
||||
/// `None` accepts any method.
|
||||
pub method: Option<String>,
|
||||
/// Path parameters in braces: `/photos/{id}`.
|
||||
pub path: String,
|
||||
pub framework: String,
|
||||
/// Display name, e.g. `PhotosController#show`.
|
||||
pub handler: Option<String>,
|
||||
/// Where the route is declared.
|
||||
pub location: ide_core::Location,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Endpoints {
|
||||
/// Bumped by every invalidation: a list computed across one is kept but not trusted.
|
||||
epoch: u64,
|
||||
cache: BTreeMap<(String, PathBuf), Cached>,
|
||||
}
|
||||
|
||||
struct Cached {
|
||||
list: Arc<Vec<PluginEndpoint>>,
|
||||
fresh: bool,
|
||||
}
|
||||
|
||||
impl PluginHost {
|
||||
/// `plugin`'s routes in the project `root`: the cached list while no file
|
||||
/// matching its globs changed, else computed again. Runs plugin code, so
|
||||
/// call it on a blocking thread. A failed or invalid run keeps the last list.
|
||||
pub fn endpoints(&self, plugin: &str, root: &Path) -> IdeResult<Arc<Vec<PluginEndpoint>>> {
|
||||
let Some(workspace) = self.shared.workspace() else { return Ok(Arc::default()) };
|
||||
let open = |root: &Path| workspace.projects().iter().any(|r| r == root) && workspace.trusted(root);
|
||||
let loaded = self.get(plugin)?;
|
||||
let key = (plugin.to_owned(), root.to_path_buf());
|
||||
let epoch = {
|
||||
let mut state = self.endpoints.lock();
|
||||
state.cache.retain(|(_, r), _| open(r));
|
||||
if !open(root) || !self.endpoint_eligible(&loaded, root) {
|
||||
return Ok(Arc::default());
|
||||
}
|
||||
if let Some(cached) = state.cache.get(&key).filter(|c| c.fresh) {
|
||||
return Ok(cached.list.clone());
|
||||
}
|
||||
state.epoch
|
||||
};
|
||||
let invocation = Invocation { workspace_root: Some(root.to_path_buf()), ..Default::default() };
|
||||
let result = self
|
||||
.code_call(plugin, invocation, "endpoints", |rt, ctx| rt.endpoints(ctx, Duration::from_secs(2)))
|
||||
.and_then(|items| {
|
||||
validate(root, items, &*workspace).map_err(|e| ide_core::IdeError::invalid(e.to_string()))
|
||||
});
|
||||
let mut state = self.endpoints.lock();
|
||||
// Disabled, replaced or closed meanwhile: its routes are gone.
|
||||
let current = self.plugins.read().get(plugin).is_some_and(|p| Arc::ptr_eq(p, &loaded));
|
||||
if !current || !open(root) || !self.endpoint_eligible(&loaded, root) {
|
||||
state.cache.remove(&key);
|
||||
return Ok(Arc::default());
|
||||
}
|
||||
let fresh = state.epoch == epoch;
|
||||
let list = match result {
|
||||
Ok(list) => Arc::new(list),
|
||||
Err(e) => {
|
||||
tracing::warn!(plugin, "endpoints failed: {e}");
|
||||
state.cache.get(&key).map(|c| c.list.clone()).unwrap_or_default()
|
||||
}
|
||||
};
|
||||
state.cache.insert(key, Cached { list: list.clone(), fresh });
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
pub(super) fn clear_plugin_endpoints(&self, plugin: &str) {
|
||||
let mut state = self.endpoints.lock();
|
||||
state.epoch += 1;
|
||||
let roots: Vec<PathBuf> = state.cache.keys().filter(|(id, _)| id == plugin).map(|(_, r)| r.clone()).collect();
|
||||
state.cache.retain(|(id, _), _| id != plugin);
|
||||
drop(state);
|
||||
for root in roots {
|
||||
self.emit(None, PluginEvent::EndpointsChanged { plugin_id: plugin.to_owned(), root: to_ipc(&root).into() });
|
||||
}
|
||||
}
|
||||
|
||||
/// Called by the project's file watcher; doesn't run plugin code.
|
||||
pub fn invalidate_endpoints(&self, root: &Path, paths: &[PathBuf]) {
|
||||
let rel: Vec<&Path> = paths.iter().filter_map(|p| p.strip_prefix(root).ok()).collect();
|
||||
if rel.is_empty() {
|
||||
return;
|
||||
}
|
||||
let declarations = self.ui.items(POINT, None);
|
||||
let mut state = self.endpoints.lock();
|
||||
state.epoch += 1;
|
||||
let mut changed = Vec::new();
|
||||
for ((plugin, project), cached) in &mut state.cache {
|
||||
let matches = project == root
|
||||
&& declarations.iter().filter(|d| &d.plugin_id == plugin).any(|d| {
|
||||
d.decl["files"].as_array().is_some_and(|globs| {
|
||||
globs
|
||||
.iter()
|
||||
.filter_map(|g| matcher(g.as_str()?).ok())
|
||||
.any(|m| rel.iter().any(|p| m.is_match(p)))
|
||||
})
|
||||
});
|
||||
if matches && cached.fresh {
|
||||
cached.fresh = false;
|
||||
changed.push(plugin.clone());
|
||||
}
|
||||
}
|
||||
drop(state);
|
||||
for plugin_id in changed {
|
||||
self.emit(None, PluginEvent::EndpointsChanged { plugin_id, root: to_ipc(root).into() });
|
||||
}
|
||||
}
|
||||
|
||||
fn endpoint_eligible(&self, plugin: &super::LoadedPlugin, root: &Path) -> bool {
|
||||
plugin.status().is_live()
|
||||
&& plugin.dev_root.as_deref().is_none_or(|r| r == root)
|
||||
&& !self.ui.items(POINT, Some(plugin.id())).is_empty()
|
||||
&& {
|
||||
let meta = plugin.meta.lock();
|
||||
meta.pending.is_empty() && meta.granted.contains(&Capability::ProjectRead)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate(
|
||||
root: &Path,
|
||||
items: Vec<Endpoint>,
|
||||
workspace: &dyn super::PluginWorkspace,
|
||||
) -> Result<Vec<PluginEndpoint>, HostError> {
|
||||
if items.len() > 10_000 {
|
||||
return Err(HostError::Invalid("at most 10,000 endpoints".into()));
|
||||
}
|
||||
let mut bytes = 0usize;
|
||||
let mut document_bytes = 0usize;
|
||||
let mut texts: BTreeMap<PathBuf, Vec<usize>> = BTreeMap::new();
|
||||
let mut validated = Vec::with_capacity(items.len());
|
||||
for e in items {
|
||||
bytes += e.path.len()
|
||||
+ e.method.as_ref().map_or(0, String::len)
|
||||
+ e.framework.len()
|
||||
+ e.handler.as_ref().map_or(0, String::len)
|
||||
+ e.location.path.as_os_str().len();
|
||||
if bytes > 4 << 20
|
||||
|| e.path.len() > 8192
|
||||
|| !e.path.starts_with('/')
|
||||
|| e.path.chars().any(char::is_whitespace)
|
||||
|| e.path.chars().any(char::is_control)
|
||||
|| e.method.as_ref().is_some_and(|m| {
|
||||
m.is_empty() || m.len() > 32 || !m.bytes().all(|b| b.is_ascii_uppercase() || b == b'-')
|
||||
})
|
||||
|| e.framework.is_empty()
|
||||
|| e.framework.len() > 256
|
||||
|| e.framework.chars().any(char::is_control)
|
||||
|| e.handler.as_ref().is_some_and(|h| h.len() > 1024 || h.chars().any(char::is_control))
|
||||
{
|
||||
return Err(HostError::Invalid("invalid endpoint or batch larger than 4 MiB".into()));
|
||||
}
|
||||
let path = ide_plugin::resolve_in_root(root, &e.location.path.to_string_lossy()).map_err(HostError::Invalid)?;
|
||||
if !texts.contains_key(&path) {
|
||||
let text = workspace
|
||||
.buffer_text(&path)
|
||||
.map(Ok)
|
||||
.unwrap_or_else(|| ide_plugin::read_text(&path).map_err(HostError::Invalid));
|
||||
let text = text?;
|
||||
document_bytes += text.len();
|
||||
if document_bytes > 16 << 20 {
|
||||
return Err(HostError::Invalid("endpoint declaration documents exceed 16 MiB".into()));
|
||||
}
|
||||
texts.insert(
|
||||
path.clone(),
|
||||
text.split('\n').map(|line| line.trim_end_matches('\r').encode_utf16().count()).collect(),
|
||||
);
|
||||
}
|
||||
let lines = &texts[&path];
|
||||
let range = e.location.range;
|
||||
if range.start > range.end
|
||||
|| [range.start, range.end]
|
||||
.iter()
|
||||
.any(|p| lines.get(p.line as usize).is_none_or(|len| p.col as usize > *len))
|
||||
{
|
||||
return Err(HostError::Invalid("endpoint location is outside its UTF-16 document range".into()));
|
||||
}
|
||||
validated.push(PluginEndpoint {
|
||||
method: e.method,
|
||||
path: e.path,
|
||||
framework: e.framework,
|
||||
handler: e.handler,
|
||||
location: ide_core::Location { path: to_ipc(&path).into(), range, uri: None },
|
||||
});
|
||||
}
|
||||
Ok(validated)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::{Pos, Range};
|
||||
struct Workspace;
|
||||
impl super::super::PluginWorkspace for Workspace {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
vec![]
|
||||
}
|
||||
fn buffer_text(&self, _: &Path) -> Option<String> {
|
||||
None
|
||||
}
|
||||
fn document(&self, _: &Path) -> Option<(u64, String)> {
|
||||
None
|
||||
}
|
||||
fn trusted(&self, _: &Path) -> bool {
|
||||
true
|
||||
}
|
||||
fn project_of(&self, _: &str) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
fn apply_edits(&self, _: &Path, _: u64, _: &[ide_core::TextEdit]) -> Result<u64, HostError> {
|
||||
unreachable!()
|
||||
}
|
||||
fn publish_diagnostics(&self, _: &str, _: &Path, _: Vec<ide_core::Diagnostic>) -> Result<(), HostError> {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
fn endpoint(path: PathBuf) -> Endpoint {
|
||||
Endpoint {
|
||||
method: Some("GET".into()),
|
||||
path: "/users/{id}".into(),
|
||||
framework: "Rails".into(),
|
||||
handler: None,
|
||||
location: ide_plugin::Location { path, range: Range::new(Pos::new(0, 2), Pos::new(0, 3)) },
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn validates_entire_rooted_batch_with_utf16_positions() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().canonicalize().unwrap();
|
||||
let file = root.join("routes.rb");
|
||||
std::fs::write(&file, "😀x\n").unwrap();
|
||||
let good = endpoint(file.clone());
|
||||
let items = validate(&root, vec![good.clone()], &Workspace).unwrap();
|
||||
assert_eq!(items[0].location.range.end.col, 3);
|
||||
assert!(items[0].handler.is_none());
|
||||
for bad in [
|
||||
Endpoint { method: Some("GET\nPOST".into()), ..good.clone() },
|
||||
Endpoint { path: "https://example.com".into(), ..good.clone() },
|
||||
Endpoint { path: "/bad\r\nPOST /".into(), ..good.clone() },
|
||||
Endpoint { handler: Some("bad\nhandler".into()), ..good.clone() },
|
||||
Endpoint {
|
||||
location: ide_plugin::Location {
|
||||
path: file.clone(),
|
||||
range: Range::new(Pos::new(0, 0), Pos::new(0, 4)),
|
||||
},
|
||||
..good.clone()
|
||||
},
|
||||
Endpoint {
|
||||
location: ide_plugin::Location { path: root.join("../outside"), range: Range::default() },
|
||||
..good.clone()
|
||||
},
|
||||
] {
|
||||
assert!(validate(&root, vec![good.clone(), bad], &Workspace).is_err());
|
||||
}
|
||||
assert!(validate(&root, vec![good.clone(); 10_001], &Workspace).is_err());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let outside = tempfile::NamedTempFile::new().unwrap();
|
||||
std::os::unix::fs::symlink(outside.path(), root.join("escape")).unwrap();
|
||||
assert!(validate(&root, vec![endpoint(root.join("escape"))], &Workspace).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
//! Project-relative event filters, kept with runtime subscriptions across idle reclaim.
|
||||
use super::{LoadedPlugin, PluginHost};
|
||||
use globset::{GlobBuilder, GlobMatcher};
|
||||
use ide_plugin::{EventKind, HostError, WorkbenchEvent};
|
||||
use std::{
|
||||
collections::{BTreeSet, HashMap},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct Subscriptions {
|
||||
pub kinds: HashMap<String, BTreeSet<EventKind>>,
|
||||
pub paths: HashMap<String, HashMap<String, PathFilter>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct PathFilter {
|
||||
pub globs: Vec<String>,
|
||||
matchers: Vec<GlobMatcher>,
|
||||
}
|
||||
|
||||
impl PathFilter {
|
||||
pub fn new(kind: &str, globs: Vec<String>) -> Result<Self, HostError> {
|
||||
if !matches!(kind, "file-opened" | "file-saved") {
|
||||
return Err(HostError::Invalid("subscribe-paths supports file-opened and file-saved".into()));
|
||||
}
|
||||
if globs.len() > 64 {
|
||||
return Err(HostError::Invalid("at most 64 event path globs".into()));
|
||||
}
|
||||
let mut matchers = Vec::new();
|
||||
for input in &globs {
|
||||
let glob = input.trim_start_matches("./");
|
||||
if glob.is_empty()
|
||||
|| input.len() > 1024
|
||||
|| glob.starts_with('/')
|
||||
|| glob.contains('\\')
|
||||
|| glob.contains(':')
|
||||
|| glob.chars().any(char::is_control)
|
||||
|| glob.split('/').any(|c| c == "..")
|
||||
{
|
||||
return Err(HostError::Invalid(
|
||||
"event globs must be project-relative paths, at most 1024 bytes each".into(),
|
||||
));
|
||||
}
|
||||
matchers.push(
|
||||
GlobBuilder::new(glob)
|
||||
.literal_separator(true)
|
||||
.build()
|
||||
.map_err(|e| HostError::Invalid(format!("invalid event glob: {e}")))?
|
||||
.compile_matcher(),
|
||||
);
|
||||
}
|
||||
Ok(Self { globs, matchers })
|
||||
}
|
||||
|
||||
pub fn matches(&self, root: &Path, path: &Path) -> bool {
|
||||
let path = ide_plugin::resolve_real(path);
|
||||
let root = ide_plugin::resolve_real(root);
|
||||
path.strip_prefix(&root).is_ok_and(|relative| self.matchers.iter().any(|m| m.is_match(relative)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Subscriptions {
|
||||
pub fn remove(&mut self, plugin: &str) -> bool {
|
||||
self.kinds.remove(plugin).is_some() | self.paths.remove(plugin).is_some()
|
||||
}
|
||||
/// Subscribes to every event of `kind`, dropping its path filter.
|
||||
pub fn set(&mut self, plugin: &str, kind: EventKind) -> bool {
|
||||
let removed = self.paths.get_mut(plugin).is_some_and(|filters| filters.remove(kind.name()).is_some());
|
||||
self.kinds.entry(plugin.to_owned()).or_default().insert(kind) | removed
|
||||
}
|
||||
pub fn set_paths(&mut self, plugin: &str, kind: &str, filter: PathFilter) -> bool {
|
||||
let mut changed = false;
|
||||
if let Some(kind) = EventKind::parse(kind) {
|
||||
changed = self.kinds.entry(plugin.to_owned()).or_default().insert(kind);
|
||||
}
|
||||
let previous = self.paths.entry(plugin.to_owned()).or_default().insert(kind.to_owned(), filter.clone());
|
||||
previous.is_none_or(|old| old.globs != filter.globs) | changed
|
||||
}
|
||||
pub fn unsubscribe(&mut self, plugin: &str, kind: &str) -> bool {
|
||||
let removed = self.paths.get_mut(plugin).is_some_and(|filters| filters.remove(kind).is_some());
|
||||
let off = EventKind::parse(kind)
|
||||
.is_some_and(|kind| self.kinds.get_mut(plugin).is_some_and(|kinds| kinds.remove(&kind)));
|
||||
removed | off
|
||||
}
|
||||
}
|
||||
|
||||
impl PluginHost {
|
||||
pub(super) fn filter_path_events(
|
||||
&self,
|
||||
plugin: &LoadedPlugin,
|
||||
client: Option<&str>,
|
||||
events: &[WorkbenchEvent],
|
||||
subs: &Subscriptions,
|
||||
) -> Vec<WorkbenchEvent> {
|
||||
let Some(filters) = subs.paths.get(plugin.id()) else { return events.to_vec() };
|
||||
let workspace = self.shared.workspace();
|
||||
events
|
||||
.iter()
|
||||
.filter(|event| {
|
||||
let path = match event {
|
||||
WorkbenchEvent::FileOpened(path) | WorkbenchEvent::FileSaved(path) => Path::new(path),
|
||||
_ => return true,
|
||||
};
|
||||
let Some(filter) = filters.get(event.kind().name()) else { return true };
|
||||
if !path.is_absolute() {
|
||||
return false;
|
||||
}
|
||||
let Some(workspace) = &workspace else { return false };
|
||||
let root = match client {
|
||||
Some(client) => workspace.project_of(client),
|
||||
None => {
|
||||
let real = ide_plugin::resolve_real(path);
|
||||
workspace
|
||||
.projects()
|
||||
.into_iter()
|
||||
.filter(|r| real.starts_with(ide_plugin::resolve_real(r)))
|
||||
.max_by_key(|r| r.components().count())
|
||||
}
|
||||
};
|
||||
let Some(root) = root else { return false };
|
||||
if plugin.dev_root.as_deref().is_some_and(|r| r != root) {
|
||||
return false;
|
||||
}
|
||||
filter.matches(&root, path)
|
||||
})
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn glob_validation_is_bounded_and_project_relative() {
|
||||
for invalid in ["", "/etc/*", "../*", "a/../b", "C:/a", "a\\b", "a\nb", "["] {
|
||||
assert!(PathFilter::new("file-opened", vec![invalid.into()]).is_err(), "{invalid:?}");
|
||||
}
|
||||
assert!(PathFilter::new("editor-focused", vec!["*".into()]).is_err());
|
||||
assert!(PathFilter::new("file-saved", vec!["*".into(); 65]).is_err());
|
||||
assert!(PathFilter::new("file-saved", vec!["./".repeat(513)]).is_err());
|
||||
assert!(PathFilter::new("file-saved", vec![]).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matchers_use_or_semantics_and_component_boundaries() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(root.path()).unwrap();
|
||||
let filter = PathFilter::new("file-opened", vec!["./config/*.yaml".into(), "src/**/*.rs".into()]).unwrap();
|
||||
for path in ["config/a.yaml", "src/main.rs", "src/深い/a.rs"] {
|
||||
assert!(filter.matches(&root, &root.join(path)), "{path}");
|
||||
}
|
||||
for path in ["config/nested/a.yaml", "other/a.yaml", "src/a.ts"] {
|
||||
assert!(!filter.matches(&root, &root.join(path)), "{path}");
|
||||
}
|
||||
assert!(!filter.matches(&root, &root.with_extension("other").join("config/a.yaml")));
|
||||
assert!(!PathFilter::new("file-opened", vec![]).unwrap().matches(&root, &root.join("a")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subscriptions_replace_atomically_and_legacy_subscribe_clears_filters() {
|
||||
let mut subs = Subscriptions::default();
|
||||
subs.set_paths("plugin", "file-opened", PathFilter::new("file-opened", vec!["*.rs".into()]).unwrap());
|
||||
assert!(subs.kinds["plugin"].contains(&EventKind::FileOpened));
|
||||
subs.set_paths("plugin", "file-opened", PathFilter::new("file-opened", vec![]).unwrap());
|
||||
assert!(subs.paths["plugin"]["file-opened"].globs.is_empty());
|
||||
subs.set("plugin", EventKind::FileOpened);
|
||||
assert!(subs.paths["plugin"].is_empty());
|
||||
subs.set_paths("plugin", "file-saved", PathFilter::new("file-saved", vec!["*".into()]).unwrap());
|
||||
assert!(subs.unsubscribe("plugin", "file-saved"));
|
||||
assert!(subs.remove("plugin"));
|
||||
assert!(subs.paths.is_empty() && subs.kinds.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use ide_lsp::types::{Hover, Markup};
|
||||
use ide_plugin::PluginHover;
|
||||
|
||||
pub(crate) fn merge(server: Option<Hover>, plugin: Vec<PluginHover>) -> Option<Hover> {
|
||||
if plugin.is_empty() {
|
||||
return server;
|
||||
}
|
||||
let mut parts = Vec::with_capacity(plugin.len() + 1);
|
||||
let mut range = None;
|
||||
if let Some(h) = server {
|
||||
range = h.range;
|
||||
if !h.contents.value.trim().is_empty() {
|
||||
parts.push(if h.contents.kind == "markdown" { h.contents.value } else { escape(&h.contents.value) });
|
||||
}
|
||||
}
|
||||
for h in plugin {
|
||||
range = range.or(h.range);
|
||||
parts.push(h.markdown);
|
||||
}
|
||||
Some(Hover { contents: Markup { kind: "markdown".into(), value: parts.join("\n\n---\n\n") }, range })
|
||||
}
|
||||
|
||||
fn escape(plain: &str) -> String {
|
||||
let mut out = String::with_capacity(plain.len() + plain.len() / 4);
|
||||
for c in plain.chars() {
|
||||
match c {
|
||||
'\n' => out.push_str(" \n"),
|
||||
'\\' | '`' | '*' | '_' | '{' | '}' | '[' | ']' | '<' | '>' | '(' | ')' | '#' | '+' | '-' | '.' | '!'
|
||||
| '|' => {
|
||||
out.push('\\');
|
||||
out.push(c);
|
||||
}
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::{Pos, Range};
|
||||
|
||||
fn range(line: u32, from: u32, to: u32) -> Range {
|
||||
Range::new(Pos::new(line, from), Pos::new(line, to))
|
||||
}
|
||||
|
||||
fn plugin(markdown: &str, at: Option<Range>) -> PluginHover {
|
||||
PluginHover { markdown: markdown.into(), range: at }
|
||||
}
|
||||
|
||||
fn server(kind: &str, value: &str, at: Option<Range>) -> Hover {
|
||||
Hover { contents: Markup { kind: kind.into(), value: value.into() }, range: at }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_content_follows_the_server_hover() {
|
||||
let merged = merge(
|
||||
Some(server("markdown", "```php\nfunction route()\n```", Some(range(3, 4, 9)))),
|
||||
vec![plugin("**orders.index** · `GET /orders`", Some(range(3, 10, 22)))],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(merged.contents.kind, "markdown");
|
||||
assert_eq!(merged.contents.value, "```php\nfunction route()\n```\n\n---\n\n**orders.index** · `GET /orders`");
|
||||
assert_eq!(merged.range, Some(range(3, 4, 9)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_server_hover_the_plugins_answer_alone() {
|
||||
let merged = merge(None, vec![plugin("one", None), plugin("two", Some(range(1, 0, 3)))]).unwrap();
|
||||
assert_eq!(merged.contents.value, "one\n\n---\n\ntwo");
|
||||
assert_eq!(merged.range, Some(range(1, 0, 3)));
|
||||
assert!(merge(None, Vec::new()).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_text_from_the_server_keeps_its_characters() {
|
||||
let merged = merge(Some(server("plaintext", "a_b *c*\nd", None)), vec![plugin("x", None)]).unwrap();
|
||||
assert_eq!(merged.contents.value, "a\\_b \\*c\\* \nd\n\n---\n\nx");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_server_hover_is_left_out() {
|
||||
let merged = merge(Some(server("markdown", " ", None)), vec![plugin("x", None)]).unwrap();
|
||||
assert_eq!(merged.contents.value, "x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_plugin_content_keeps_the_server_hover() {
|
||||
let kept = merge(Some(server("plaintext", "a_b", Some(range(0, 0, 1)))), Vec::new()).unwrap();
|
||||
assert_eq!((kept.contents.kind.as_str(), kept.contents.value.as_str()), ("plaintext", "a_b"));
|
||||
assert_eq!(kept.range, Some(range(0, 0, 1)));
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@
|
||||
|
||||
use super::icon_extensions::{Choice, DARK_SUFFIX, Extensions, Group, IconDefinition, Pattern, check_icon_id};
|
||||
use super::icon_settings::{self, SettingsSection};
|
||||
use ide_extension::package::PluginIcon;
|
||||
use ide_extension::{Package, UiDecl, check_relative, decode, validate_item_id};
|
||||
use serde::Deserialize;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
@@ -33,8 +34,10 @@ use std::path::PathBuf;
|
||||
|
||||
pub const POINT_ID: &str = "iconThemes";
|
||||
const MAX_ICONS: usize = 5000;
|
||||
const MAX_SVG: usize = 64 << 10;
|
||||
pub(super) const MAX_SVG: usize = 64 << 10;
|
||||
const MAX_MAPPINGS: usize = 20_000;
|
||||
/// A plugin's own icon is inline in every plugin listing and index entry.
|
||||
pub const MAX_PLUGIN_ICON: usize = 16 << 10;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -90,16 +93,24 @@ pub fn svg_prefix(theme: &str) -> String {
|
||||
format!("iconTheme/{theme}/svg/")
|
||||
}
|
||||
|
||||
/// An SVG icon of the package, size-checked and sanitised.
|
||||
pub(super) fn read_icon(pkg: &Package, path: &std::path::Path) -> Result<String, String> {
|
||||
/// An SVG icon of the package, size-checked (`max` bytes) and sanitised.
|
||||
pub(super) fn read_icon(pkg: &Package, path: &std::path::Path, max: usize) -> Result<String, String> {
|
||||
check_relative(path, "icon")?;
|
||||
let svg = pkg.read_text(path)?;
|
||||
if svg.len() > MAX_SVG {
|
||||
return Err(format!("{}: larger than {} KiB", path.display(), MAX_SVG >> 10));
|
||||
if svg.len() > max {
|
||||
return Err(format!("{}: larger than {} KiB", path.display(), max >> 10));
|
||||
}
|
||||
sanitize_svg(&svg).map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// The manifest's `icon` / `icon-dark`, read and sanitised.
|
||||
pub fn plugin_icon(pkg: &Package) -> Result<Option<PluginIcon>, String> {
|
||||
let read = |path: &std::path::Path| read_icon(pkg, path, MAX_PLUGIN_ICON);
|
||||
let Some(light) = &pkg.manifest.icon else { return Ok(None) };
|
||||
let dark = pkg.manifest.icon_dark.as_deref().map(read).transpose()?;
|
||||
Ok(Some(PluginIcon { light: read(light)?, dark }))
|
||||
}
|
||||
|
||||
pub(super) fn icon_theme(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
let d: Decl = decode(POINT_ID, decl)?;
|
||||
validate_item_id(&d.id, "icon theme id")?;
|
||||
@@ -166,7 +177,7 @@ pub(super) fn icon_theme(pkg: &Package, decl: toml::Value) -> Result<UiDecl, Str
|
||||
for (icon, def) in &theme.icon_definitions {
|
||||
let dark = def.dark().map(|path| (path, DARK_SUFFIX));
|
||||
for (path, suffix) in std::iter::once((def.light(), "")).chain(dark) {
|
||||
let clean = read_icon(pkg, path)?;
|
||||
let clean = read_icon(pkg, path, MAX_SVG)?;
|
||||
assets.push((format!("{}{icon}{suffix}", svg_prefix(&d.id)), clean));
|
||||
files.push(path.clone());
|
||||
}
|
||||
@@ -499,6 +510,8 @@ fn check_value(key: &str, value: &str) -> Result<(), String> {
|
||||
if lower.contains("javascript:")
|
||||
|| lower.contains("expression(")
|
||||
|| lower.contains("@import")
|
||||
// These CSS image/URL functions accept bare strings, bypassing url().
|
||||
|| ["image(", "image-set(", "src("].iter().any(|function| lower.contains(function))
|
||||
|| value.contains('\\')
|
||||
{
|
||||
return Err("unsafe value".into());
|
||||
@@ -596,6 +609,10 @@ mod tests {
|
||||
r##"<svg><use xlink:href="data:image/svg+xml,..."/></svg>"##,
|
||||
r##"<svg><rect style="fill:url(https://evil)"/></svg>"##,
|
||||
r##"<svg><rect fill="url( 'http://x' )"/></svg>"##,
|
||||
r##"<svg><rect style="background-image:image-set('https://evil/x.png' 1x)"/></svg>"##,
|
||||
r##"<svg><rect style="background-image:-webkit-image-set('https://evil/x.png' 1x)"/></svg>"##,
|
||||
r##"<svg><rect style="background-image:image('https://evil/x.png')"/></svg>"##,
|
||||
r##"<svg><rect style="fill:src('https://evil/x.svg')"/></svg>"##,
|
||||
r##"<!DOCTYPE svg [<!ENTITY x "y">]><svg/>"##,
|
||||
r##"<svg><![CDATA[x]]></svg>"##,
|
||||
r##"<svg><a href="#x"/></svg>"##,
|
||||
|
||||
@@ -121,7 +121,12 @@ pub async fn plugin_navigation_index(
|
||||
plugins.index_navigation(
|
||||
&project.root,
|
||||
crate::plugins::navigation::Snapshot { path: &path, version, text: &text, symbols: &symbols, scope },
|
||||
Invocation { client: Some(client.clone()), workspace_root: Some(project.root.clone()), editor: None },
|
||||
Invocation {
|
||||
client: Some(client.clone()),
|
||||
workspace_root: Some(project.root.clone()),
|
||||
editor: None,
|
||||
selected_paths: Vec::new(),
|
||||
},
|
||||
)?;
|
||||
// A document edit while WASM was executing must not publish stale ranges.
|
||||
if cancel.is_cancelled() || document.is_some_and(|id| project.documents.version(id).ok() != version) {
|
||||
@@ -135,6 +140,17 @@ pub async fn plugin_navigation_index(
|
||||
result
|
||||
}
|
||||
|
||||
/// The HTTP routes `plugin_id` reports for this window's project.
|
||||
pub async fn plugin_endpoints(
|
||||
host: &crate::Host,
|
||||
plugins: Arc<PluginHost>,
|
||||
window: &str,
|
||||
plugin_id: String,
|
||||
) -> IdeResult<Vec<crate::plugins::endpoints::PluginEndpoint>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || Ok(plugins.endpoints(&plugin_id, &project.root)?.as_ref().clone())).await
|
||||
}
|
||||
|
||||
pub async fn plugin_navigation_goto(
|
||||
host: &crate::Host,
|
||||
plugins: Arc<PluginHost>,
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
use ide_core::Range;
|
||||
use ide_lsp::types::{InlayHint, InlayKind};
|
||||
use ide_plugin::PluginInlayHint;
|
||||
|
||||
pub(crate) fn merge(server: Vec<InlayHint>, plugin: Vec<PluginInlayHint>, range: Range) -> Vec<InlayHint> {
|
||||
let inside = |h: &PluginInlayHint| {
|
||||
let at = (h.position.line, h.position.col);
|
||||
(range.start.line, range.start.col) <= at && at <= (range.end.line, range.end.col)
|
||||
};
|
||||
let mut out = server;
|
||||
out.extend(plugin.into_iter().filter(inside).map(|h| InlayHint {
|
||||
position: h.position,
|
||||
label: h.label,
|
||||
kind: match h.kind.as_str() {
|
||||
"type" => InlayKind::Type,
|
||||
"parameter" => InlayKind::Parameter,
|
||||
_ => InlayKind::Other,
|
||||
},
|
||||
padding_left: h.padding_left,
|
||||
padding_right: h.padding_right,
|
||||
tooltip: h.tooltip,
|
||||
parts: Vec::new(),
|
||||
}));
|
||||
out.sort_by_key(|h| (h.position.line, h.position.col));
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::Pos;
|
||||
|
||||
fn plugin(line: u32, col: u32, label: &str, kind: &str) -> PluginInlayHint {
|
||||
PluginInlayHint {
|
||||
position: Pos::new(line, col),
|
||||
label: label.into(),
|
||||
kind: kind.into(),
|
||||
tooltip: Some("from the plugin".into()),
|
||||
padding_left: true,
|
||||
padding_right: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn server(line: u32, col: u32, label: &str) -> InlayHint {
|
||||
InlayHint {
|
||||
position: Pos::new(line, col),
|
||||
label: label.into(),
|
||||
kind: InlayKind::Parameter,
|
||||
padding_left: false,
|
||||
padding_right: true,
|
||||
tooltip: None,
|
||||
parts: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn summary(hints: &[InlayHint]) -> Vec<(u32, u32, String)> {
|
||||
hints.iter().map(|h| (h.position.line, h.position.col, h.label.clone())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_hints_join_the_servers_in_position_order() {
|
||||
let range = Range::new(Pos::new(0, 0), Pos::new(10, 0));
|
||||
let merged = merge(
|
||||
vec![server(2, 4, "name:"), server(5, 1, "id:")],
|
||||
vec![plugin(3, 9, ": string", "type"), plugin(2, 1, "GET /orders", "other")],
|
||||
range,
|
||||
);
|
||||
assert_eq!(
|
||||
summary(&merged),
|
||||
[
|
||||
(2, 1, "GET /orders".to_owned()),
|
||||
(2, 4, "name:".to_owned()),
|
||||
(3, 9, ": string".to_owned()),
|
||||
(5, 1, "id:".to_owned())
|
||||
]
|
||||
);
|
||||
let typed = merged.iter().find(|h| h.label == ": string").unwrap();
|
||||
assert!(matches!(typed.kind, InlayKind::Type));
|
||||
assert!(typed.padding_left && !typed.padding_right);
|
||||
assert_eq!(typed.tooltip.as_deref(), Some("from the plugin"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_kinds_are_other_and_hints_outside_the_range_are_dropped() {
|
||||
let range = Range::new(Pos::new(2, 5), Pos::new(4, 3));
|
||||
let merged = merge(
|
||||
Vec::new(),
|
||||
vec![plugin(2, 4, "before", "type"), plugin(3, 0, "in", "route"), plugin(4, 4, "after", "type")],
|
||||
range,
|
||||
);
|
||||
assert_eq!(summary(&merged), [(3, 0, "in".to_owned())]);
|
||||
assert!(matches!(merged[0].kind, InlayKind::Other));
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,10 @@
|
||||
//! Release builds pin the official publisher to the keys they were built
|
||||
//! with, so no index can sign `openidea.*` plugins with another key.
|
||||
|
||||
use super::icons::{MAX_PLUGIN_ICON, sanitize_svg};
|
||||
use super::{PackageFile, PluginEvent, PluginHost, PluginSource, PluginStatus, PluginUpdate, install};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_extension::package::{self, Index, IndexEntry, PackageSignature, SIGNATURE_FILE};
|
||||
use ide_extension::package::{self, Index, IndexEntry, PackageSignature, PluginIcon, SIGNATURE_FILE};
|
||||
use ide_extension::{MANIFEST_FILE, Manifest};
|
||||
use semver::Version;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -67,6 +68,14 @@ fn pinned(mut index: Index, official_keys: &[String]) -> Index {
|
||||
index
|
||||
}
|
||||
|
||||
/// An index's icon as the UI may show it: sanitised again, as any index may
|
||||
/// have written it; without a light variant that passes, none.
|
||||
fn safe_icon(icon: PluginIcon) -> Option<PluginIcon> {
|
||||
// Before sanitising too: an index may hold megabytes of it.
|
||||
let clean = |svg: String| (svg.len() <= MAX_PLUGIN_ICON).then(|| sanitize_svg(&svg).ok()).flatten();
|
||||
Some(PluginIcon { light: clean(icon.light)?, dark: icon.dark.and_then(clean) })
|
||||
}
|
||||
|
||||
/// Reads `url`: `http(s)://…`, `file://…` or a local path.
|
||||
pub fn read_url(url: &str, max: usize) -> Result<Vec<u8>, String> {
|
||||
if url.starts_with("https://") || url.starts_with("http://") {
|
||||
@@ -242,7 +251,9 @@ impl PluginHost {
|
||||
.get(&entry.id)
|
||||
.filter(|p| p.source == PluginSource::Installed)
|
||||
.map(|p| p.manifest().version.clone());
|
||||
MarketPlugin { entry: entry.clone(), installed, compatible }
|
||||
let mut entry = entry.clone();
|
||||
entry.icon = entry.icon.and_then(safe_icon);
|
||||
MarketPlugin { entry, installed, compatible }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -350,7 +361,7 @@ impl PluginHost {
|
||||
pub(super) fn package_files_in(&self, dir: &Path) -> IdeResult<Vec<PathBuf>> {
|
||||
let manifest = Manifest::load(dir).map_err(IdeError::invalid)?;
|
||||
let pkg = ide_extension::Package::new(manifest, dir.to_path_buf());
|
||||
let set = self.registry.prepare(&pkg).map_err(IdeError::invalid)?;
|
||||
let set = self.prepare(&pkg).map_err(IdeError::invalid)?;
|
||||
Ok(set.files.into_iter().chain(pkg.manifest.wasm.clone()).collect())
|
||||
}
|
||||
|
||||
@@ -418,6 +429,7 @@ impl PluginHost {
|
||||
level: ide_plugin::NotificationLevel::Warning,
|
||||
title: format!("{} was disabled", plugin.manifest().name),
|
||||
body: format!("The marketplace revoked this plugin: {reason}"),
|
||||
actions: Vec::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,11 +16,17 @@
|
||||
//! projects) and folders linked with `openidea-plugin link` (`links.json`).
|
||||
|
||||
mod api;
|
||||
pub mod commit;
|
||||
pub(crate) mod diagnostics;
|
||||
pub mod endpoints;
|
||||
mod event_paths;
|
||||
mod hover;
|
||||
mod icon_extensions;
|
||||
mod icon_patterns;
|
||||
mod icon_settings;
|
||||
mod icons;
|
||||
pub mod index_ops;
|
||||
mod inlay_hints;
|
||||
mod install;
|
||||
pub mod intellij;
|
||||
mod market;
|
||||
@@ -30,6 +36,7 @@ mod providers;
|
||||
pub mod remote;
|
||||
pub mod remote_host;
|
||||
mod run_detectors;
|
||||
mod semantic_tokens;
|
||||
mod theme;
|
||||
mod types;
|
||||
pub mod ui_points;
|
||||
@@ -37,7 +44,11 @@ pub mod views;
|
||||
pub mod web;
|
||||
|
||||
pub use api::{FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
|
||||
pub use icons::{map_asset as icon_theme_map_asset, sanitize_svg, svg_prefix as icon_theme_svg_prefix};
|
||||
pub(crate) use hover::merge as merge_hover;
|
||||
pub use icons::{
|
||||
MAX_PLUGIN_ICON, map_asset as icon_theme_map_asset, plugin_icon, sanitize_svg, svg_prefix as icon_theme_svg_prefix,
|
||||
};
|
||||
pub(crate) use inlay_hints::merge as merge_inlay_hints;
|
||||
pub use market::{
|
||||
INDEX_FILE as MARKET_INDEX_FILE, MarketPlugin, OFFICIAL_INDEX as OFFICIAL_MARKET_INDEX, OFFICIAL_PUBLISHER,
|
||||
read_url as read_market_url, resolve as resolve_market_href,
|
||||
@@ -45,6 +56,7 @@ pub use market::{
|
||||
pub use points::{COMMANDS, CommandDecl, register_builtin_points};
|
||||
pub use providers::{ProviderKind, set_editor_providers};
|
||||
pub(crate) use providers::{editor_plugin_host, editor_providers as editor_providers_for};
|
||||
pub(crate) use semantic_tokens::merge as merge_semantic_tokens;
|
||||
pub use theme::{ThemeDef, ThemeKind};
|
||||
pub use types::*;
|
||||
|
||||
@@ -57,7 +69,8 @@ use ide_extension::{
|
||||
use ide_language::plugin_point::PluginLanguages;
|
||||
use ide_language::{LanguageConfig, ProgramPin};
|
||||
use ide_plugin::{
|
||||
Actor, ActorError, CANCELLED, CallError, HostApi, Invocation, Limits, PluginEngine, Runtime, RuntimeSetup,
|
||||
Actor, ActorError, CANCELLED, CallError, HostApi, HostError, Invocation, Limits, PluginEngine, Runtime,
|
||||
RuntimeSetup,
|
||||
};
|
||||
use parking_lot::{Condvar, Mutex, RwLock};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -184,6 +197,8 @@ const IDLE_BATCH: Duration = Duration::from_secs(2);
|
||||
|
||||
struct LoadedPlugin {
|
||||
pkg: Package,
|
||||
/// Read at load so disabled and failed plugins show it too.
|
||||
icon: Option<ide_extension::package::PluginIcon>,
|
||||
/// The manifest failed to parse: `pkg` is a placeholder.
|
||||
invalid: bool,
|
||||
source: PluginSource,
|
||||
@@ -311,6 +326,9 @@ pub struct PluginHost {
|
||||
/// `[[contributes.providers]]` of enabled plugins.
|
||||
providers: Arc<providers::Providers>,
|
||||
navigation: Mutex<navigation::NavigationIndex>,
|
||||
endpoints: Mutex<endpoints::Endpoints>,
|
||||
web_ptys: Mutex<BTreeMap<String, Vec<web::WebPtySession>>>,
|
||||
diagnostic_projects: Mutex<Vec<diagnostics::ProjectState>>,
|
||||
/// Validated UI declarations of installed packages (start-up reuses them).
|
||||
index: Arc<ContributionIndex>,
|
||||
ledger: Mutex<Ledger>,
|
||||
@@ -367,7 +385,8 @@ impl PluginHost {
|
||||
let ui = UiStore::new();
|
||||
let index = Arc::new(ContributionIndex::new(
|
||||
plugins_dir.join(".cache").join("contributions"),
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
// Revalidate SVGs accepted before URL-valued CSS functions were rejected.
|
||||
concat!(env!("CARGO_PKG_VERSION"), ":svg-2"),
|
||||
));
|
||||
ui.set_index(Some(index.clone()));
|
||||
let languages = PluginLanguages::new();
|
||||
@@ -400,6 +419,9 @@ impl PluginHost {
|
||||
run_detectors,
|
||||
providers,
|
||||
navigation: Mutex::default(),
|
||||
endpoints: Mutex::default(),
|
||||
web_ptys: Mutex::default(),
|
||||
diagnostic_projects: Mutex::default(),
|
||||
index,
|
||||
plugins: RwLock::default(),
|
||||
state: Mutex::new(state),
|
||||
@@ -688,6 +710,15 @@ impl PluginHost {
|
||||
Ok(self.ui.assets_with_prefix(id, prefix).into_iter().map(|(k, v)| (k, v.to_string())).collect())
|
||||
}
|
||||
|
||||
/// The UI language windows run in, as `locale()` reports it to plugin code.
|
||||
pub fn set_ui_locale(&self, tag: &str) {
|
||||
*self.shared.locale.write() = tag.to_owned();
|
||||
}
|
||||
|
||||
pub fn ui_locale(&self) -> String {
|
||||
self.shared.locale.read().clone()
|
||||
}
|
||||
|
||||
pub fn set_enabled(&self, id: &str, enabled: bool) -> IdeResult<()> {
|
||||
let _guard = self.lifecycle.lock();
|
||||
let plugin = self.get(id)?;
|
||||
@@ -892,6 +923,7 @@ impl PluginHost {
|
||||
level: ide_plugin::NotificationLevel::Warning,
|
||||
title: format!("{name} update rolled back"),
|
||||
body: message.clone(),
|
||||
actions: Vec::new(),
|
||||
},
|
||||
);
|
||||
self.changed();
|
||||
@@ -1070,6 +1102,65 @@ impl PluginHost {
|
||||
})
|
||||
}
|
||||
|
||||
/// The detail tabs of item `key` of a Services or `detail = true` view.
|
||||
pub fn service_detail(
|
||||
&self,
|
||||
id: &str,
|
||||
view: &str,
|
||||
key: &str,
|
||||
invocation: Invocation,
|
||||
) -> IdeResult<Vec<ide_plugin::ServiceTab>> {
|
||||
self.detail_view(id, view)?;
|
||||
let (view, key) = (view.to_owned(), key.to_owned());
|
||||
self.code_call(id, invocation, "rendering the item's detail pane", move |rt, inv| {
|
||||
rt.service_detail(&view, &key, inv)
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs the program of the log tab `tab` of node `key`'s pane, with the
|
||||
/// arguments of the toggles in `on`, streaming its output until it exits
|
||||
/// or `cancel` fires; returns its exit code. The pane is asked of the
|
||||
/// plugin again, so the UI never names what runs. Needs the plugin's
|
||||
/// `process:<program>` grant.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn stream_service_log(
|
||||
&self,
|
||||
id: &str,
|
||||
view: &str,
|
||||
key: &str,
|
||||
tab: &str,
|
||||
on: &[String],
|
||||
invocation: Invocation,
|
||||
cancel: &ide_core::CancellationToken,
|
||||
on_line: &dyn Fn(PluginOutputLine),
|
||||
) -> IdeResult<Option<i32>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let cwd = invocation.workspace_root.clone();
|
||||
let tabs = self.service_detail(id, view, key, invocation)?;
|
||||
let Some(ide_plugin::ServicePane::Log(log)) = tabs.into_iter().find(|t| t.id == tab).map(|t| t.body) else {
|
||||
return Err(IdeError::not_found(format!("the pane of {key:?} has no log tab {tab:?}")));
|
||||
};
|
||||
let toggled = log.toggles.into_iter().filter(|t| on.contains(&t.id)).flat_map(|t| t.args);
|
||||
let args: Vec<String> = log.args.into_iter().chain(toggled).collect();
|
||||
let plugin =
|
||||
self.plugins.read().get(id).cloned().ok_or_else(|| IdeError::not_found(format!("plugin {id:?}")))?;
|
||||
let cap = Capability::Process(log.program.clone());
|
||||
if !plugin.meta.lock().granted.iter().any(|g| g.covers(&cap)) {
|
||||
let denied = HostError::Denied(cap.to_string()).to_string();
|
||||
return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, denied));
|
||||
}
|
||||
let api = api::PluginApi { pkg: plugin.pkg.clone(), shared: self.shared.clone() };
|
||||
api.stream_process(&log.program, args, cwd.as_deref(), cancel, on_line).map_err(|e| match e {
|
||||
HostError::Cancelled => IdeError::cancelled(),
|
||||
e @ HostError::Denied(_) => IdeError::new(ide_core::error::ErrorKind::PermissionDenied, e.to_string()),
|
||||
HostError::NotFound(m) => IdeError::not_found(m),
|
||||
HostError::Invalid(m) => IdeError::invalid(m),
|
||||
e => IdeError::unavailable(e.to_string()),
|
||||
})
|
||||
}
|
||||
|
||||
fn declared_view(&self, id: &str, view: &str) -> IdeResult<()> {
|
||||
let declared = [ui_points::VIEWS, ui_points::CUSTOM_EDITORS]
|
||||
.iter()
|
||||
@@ -1077,6 +1168,19 @@ impl PluginHost {
|
||||
if declared { Ok(()) } else { Err(IdeError::not_found(format!("plugin {id:?} declares no view {view:?}"))) }
|
||||
}
|
||||
|
||||
fn detail_view(&self, id: &str, view: &str) -> IdeResult<()> {
|
||||
let detail = self.ui.items(ui_points::VIEWS, Some(id)).iter().any(|i| {
|
||||
i.key == view
|
||||
&& (i.decl["location"].as_str() == Some(ui_points::SERVICES_LOCATION)
|
||||
|| i.decl["detail"].as_bool() == Some(true))
|
||||
});
|
||||
if detail {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(IdeError::not_found(format!("plugin {id:?} declares no detail view {view:?}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// One call into a plugin's code for the UI: checks it may run (asking
|
||||
/// for missing consent), activates it, retries once when the instance was
|
||||
/// reclaimed meanwhile, and reports crashes.
|
||||
@@ -1256,11 +1360,96 @@ impl PluginHost {
|
||||
self.shared.status_items()
|
||||
}
|
||||
|
||||
/// Plugin context keys in effect for window `client`: global keys overlaid with its own.
|
||||
pub fn context_keys(&self, client: Option<&str>) -> Vec<PluginContextKey> {
|
||||
self.shared.context_keys(client)
|
||||
}
|
||||
|
||||
/// A window labelled `label` is about to exist again (labels are reused).
|
||||
pub fn reopen_client(&self, label: &str) {
|
||||
self.shared.reopen_client(label);
|
||||
}
|
||||
|
||||
/// Window `label` closed: cancels its prompts, drops its context keys and queued
|
||||
/// events, and ignores context writes of commands still running for it.
|
||||
pub fn forget_client(&self, label: &str) {
|
||||
self.queues.lock().retain(|(_, client), _| client.as_deref() != Some(label));
|
||||
self.shared.forget_client(label);
|
||||
self.forget_web_ptys(label);
|
||||
}
|
||||
|
||||
/// The user cancelled a plugin task (`task_id` from `TaskStarted`).
|
||||
pub fn cancel_task(&self, task_id: &str) -> bool {
|
||||
task_id.parse().is_ok_and(|id| self.shared.cancel_task(id))
|
||||
}
|
||||
|
||||
/// The user answered (`Some`) or dismissed (`None`) a prompt
|
||||
/// (`PromptRequested`); false when it is no longer waiting.
|
||||
pub fn answer_prompt(&self, prompt_id: &str, answer: Option<Vec<String>>) -> bool {
|
||||
prompt_id.parse().is_ok_and(|id| self.shared.answer_prompt(id, answer))
|
||||
}
|
||||
|
||||
/// A window answered a plugin's `CommitRequested`; false when the call no
|
||||
/// longer waits.
|
||||
pub fn answer_commit(&self, request_id: &str, answer: CommitAnswer) -> bool {
|
||||
request_id.parse().is_ok_and(|id| self.shared.answer_commit(id, answer))
|
||||
}
|
||||
|
||||
/// Runs the plugins' before-commit checks `checks` (`(plugin, check)`) on
|
||||
/// what `selection` commits. A check that fails or isn't available is
|
||||
/// reported with `error`, so the commit still stops for it.
|
||||
pub fn commit_checks(
|
||||
&self,
|
||||
invocation: Invocation,
|
||||
selection: CommitSelection,
|
||||
checks: Vec<PluginCommitCheckRef>,
|
||||
cancel: &ide_core::CancellationToken,
|
||||
) -> IdeResult<Vec<PluginCommitCheckResult>> {
|
||||
let declared = self.ui.items(ui_points::COMMIT_CHECKS, None);
|
||||
let wanted: Vec<_> = checks
|
||||
.into_iter()
|
||||
.filter_map(|c| {
|
||||
let item = declared.iter().find(|i| i.plugin_id == c.plugin_id && i.key == c.check)?;
|
||||
Some((c, item.decl["title"].as_str().unwrap_or_default().to_owned()))
|
||||
})
|
||||
.collect();
|
||||
if wanted.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let workspace = self.shared.workspace().ok_or_else(|| IdeError::unavailable("no workspace"))?;
|
||||
let draft = api::commit_draft(&*workspace, selection, cancel).map_err(|e| match e {
|
||||
HostError::Cancelled => IdeError::cancelled(),
|
||||
HostError::Invalid(m) => IdeError::invalid(m),
|
||||
e => IdeError::unavailable(e.to_string()),
|
||||
})?;
|
||||
let mut out = Vec::new();
|
||||
for (c, title) in wanted {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let granted = self
|
||||
.plugins
|
||||
.read()
|
||||
.get(&c.plugin_id)
|
||||
.is_some_and(|p| p.meta.lock().granted.contains(&Capability::VcsRead));
|
||||
let result = if granted {
|
||||
let (check, draft) = (c.check.clone(), draft.clone());
|
||||
self.code_call(&c.plugin_id, invocation.clone(), "checking the commit", move |rt, inv| {
|
||||
rt.commit_check(&check, draft.clone(), inv)
|
||||
})
|
||||
.map_err(|e| e.message)
|
||||
} else {
|
||||
Err(HostError::Denied(Capability::VcsRead.to_string()).to_string())
|
||||
};
|
||||
let (problems, error) = match result {
|
||||
Ok(problems) => (problems, None),
|
||||
Err(e) => (Vec::new(), Some(e)),
|
||||
};
|
||||
out.push(PluginCommitCheckResult { plugin_id: c.plugin_id, check: c.check, title, problems, error });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Kinds of workbench events some running or activatable plugin wants;
|
||||
/// the UI reports only these.
|
||||
pub fn event_kinds(&self) -> BTreeSet<EventKind> {
|
||||
@@ -1268,7 +1457,7 @@ impl PluginHost {
|
||||
let mut out = BTreeSet::new();
|
||||
for p in self.plugins.read().values() {
|
||||
for kind in EventKind::ALL {
|
||||
if self.wants(p, kind, subs.get(p.id())) {
|
||||
if self.wants(p, kind, subs.kinds.get(p.id())) {
|
||||
out.insert(kind);
|
||||
}
|
||||
}
|
||||
@@ -1301,7 +1490,8 @@ impl PluginHost {
|
||||
let mut queues = self.queues.lock();
|
||||
for p in plugins {
|
||||
let wanted: Vec<WorkbenchEvent> =
|
||||
events.iter().filter(|e| self.wants(&p, e.kind(), subs.get(p.id()))).cloned().collect();
|
||||
events.iter().filter(|e| self.wants(&p, e.kind(), subs.kinds.get(p.id()))).cloned().collect();
|
||||
let wanted = self.filter_path_events(&p, client, &wanted, &subs);
|
||||
if wanted.is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -1381,6 +1571,18 @@ impl PluginHost {
|
||||
/// Returns whether the plugin was activated.
|
||||
fn deliver(&self, id: &str, client: Option<String>, events: Vec<WorkbenchEvent>) -> bool {
|
||||
let Ok(plugin) = self.get(id) else { return false };
|
||||
let subs = self.shared.subscriptions.lock().clone();
|
||||
let events: Vec<_> = self
|
||||
.filter_path_events(&plugin, client.as_deref(), &events, &subs)
|
||||
.into_iter()
|
||||
.filter(|event| {
|
||||
!matches!(event, WorkbenchEvent::FileOpened(_) | WorkbenchEvent::FileSaved(_))
|
||||
|| self.wants(&plugin, event.kind(), subs.kinds.get(id))
|
||||
})
|
||||
.collect();
|
||||
if events.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if !plugin.meta.lock().pending.is_empty() {
|
||||
return false;
|
||||
}
|
||||
@@ -1389,6 +1591,7 @@ impl PluginHost {
|
||||
workspace_root: client.as_deref().and_then(|c| self.shared.project_of(c)),
|
||||
client: client.clone(),
|
||||
editor: None,
|
||||
selected_paths: Vec::new(),
|
||||
};
|
||||
let kinds: BTreeSet<EventKind> = events.iter().map(WorkbenchEvent::kind).collect();
|
||||
{
|
||||
@@ -1528,7 +1731,7 @@ impl PluginHost {
|
||||
continue;
|
||||
}
|
||||
let pkg = Package::new(m.clone(), dir.clone());
|
||||
let problem = match self.registry.prepare(&pkg) {
|
||||
let problem = match self.prepare(&pkg) {
|
||||
Err(e) => Some(e),
|
||||
Ok(_) => m
|
||||
.wasm
|
||||
@@ -1551,6 +1754,7 @@ impl PluginHost {
|
||||
authors: m.authors,
|
||||
homepage: m.homepage,
|
||||
change_notes: m.change_notes,
|
||||
icon: plugin_icon(&pkg).ok().flatten(),
|
||||
path: dir.into(),
|
||||
problem,
|
||||
});
|
||||
@@ -1562,12 +1766,17 @@ impl PluginHost {
|
||||
/// Deactivates every plugin (also done on drop).
|
||||
pub fn shutdown(&self) {
|
||||
let actors: Vec<_> = self.plugins.read().values().filter_map(|p| p.runtime.lock().take()).collect();
|
||||
for id in self.plugins.read().keys() {
|
||||
self.shared.block_prompts(id);
|
||||
self.stop_web_ptys(id);
|
||||
}
|
||||
for a in &actors {
|
||||
a.stop(false);
|
||||
}
|
||||
for a in actors {
|
||||
a.stop(true);
|
||||
}
|
||||
self.shared.finish_process_shutdowns();
|
||||
}
|
||||
|
||||
/// Periodic upkeep (every few seconds): reports crashes nobody waited
|
||||
@@ -1645,11 +1854,24 @@ impl PluginHost {
|
||||
self.plugins.read().values().any(|p| p.dir() == dir)
|
||||
}
|
||||
|
||||
/// Validates the manifest's icon and every declaration of `pkg`; the
|
||||
/// icon files join the package files the declarations reference.
|
||||
fn prepare(&self, pkg: &Package) -> Result<ide_extension::PreparedSet, String> {
|
||||
plugin_icon(pkg)?;
|
||||
let mut set = self.registry.prepare(pkg)?;
|
||||
for icon in [&pkg.manifest.icon, &pkg.manifest.icon_dark].into_iter().flatten() {
|
||||
if !set.files.contains(icon) {
|
||||
set.files.push(icon.clone());
|
||||
}
|
||||
}
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
/// Parses and validates a package directory; nothing takes effect.
|
||||
fn validate_package(&self, src: &Path) -> IdeResult<(Package, ide_extension::PreparedSet)> {
|
||||
let manifest = Manifest::load(src).map_err(IdeError::invalid)?;
|
||||
let pkg = Package::new(manifest, src.to_path_buf());
|
||||
let set = self.registry.prepare(&pkg).map_err(IdeError::invalid)?;
|
||||
let set = self.prepare(&pkg).map_err(IdeError::invalid)?;
|
||||
if let Some(wasm) = &pkg.manifest.wasm {
|
||||
if !src.join(wasm).is_file() {
|
||||
return Err(IdeError::invalid(format!(
|
||||
@@ -1682,6 +1904,7 @@ impl PluginHost {
|
||||
pkg = pkg.with_digest(digest.trim());
|
||||
}
|
||||
let plugin = Arc::new(LoadedPlugin {
|
||||
icon: plugin_icon(&pkg).ok().flatten(),
|
||||
pkg,
|
||||
invalid,
|
||||
source,
|
||||
@@ -1722,6 +1945,7 @@ impl PluginHost {
|
||||
/// whose activation event already fired.
|
||||
fn start(&self, plugin: &Arc<LoadedPlugin>) {
|
||||
self.registry.dispose_plugin(plugin.id());
|
||||
self.clear_provider_diagnostics(plugin.id());
|
||||
if plugin.source == PluginSource::Installed
|
||||
&& let Some(reason) = self.revoked_reason(plugin.id(), &plugin.manifest().version, plugin.dir())
|
||||
{
|
||||
@@ -1731,7 +1955,7 @@ impl PluginHost {
|
||||
let publisher = self.verified_publisher(plugin.dir());
|
||||
plugin.meta.lock().publisher = publisher;
|
||||
}
|
||||
let set = match self.registry.prepare(&plugin.pkg) {
|
||||
let set = match self.prepare(&plugin.pkg) {
|
||||
Ok(set) => set,
|
||||
Err(e) => return self.set_failed(plugin, e),
|
||||
};
|
||||
@@ -1861,6 +2085,7 @@ impl PluginHost {
|
||||
Err(e) => return Err(IdeError::internal(format!("plugin {:?}: {e}", plugin.id()))),
|
||||
};
|
||||
*runtime = Some(actor.clone());
|
||||
self.shared.allow_prompts(plugin.id());
|
||||
let mut meta = plugin.meta.lock();
|
||||
meta.status = PluginStatus::Active;
|
||||
meta.has_syntax = has_syntax;
|
||||
@@ -1886,6 +2111,7 @@ impl PluginHost {
|
||||
}
|
||||
let Some(error) = actor.take_crash() else { return };
|
||||
self.clear_plugin_navigation(plugin.id());
|
||||
self.clear_plugin_endpoints(plugin.id());
|
||||
if error.starts_with(CANCELLED) {
|
||||
// Cancelled on request: restart on next use, no backoff.
|
||||
let mut meta = plugin.meta.lock();
|
||||
@@ -1902,6 +2128,7 @@ impl PluginHost {
|
||||
/// A trap dropped the plugin's instance: restart it on next use after a
|
||||
/// backoff, or stop it for the session after too many crashes in a row.
|
||||
fn crashed(&self, plugin: &LoadedPlugin, error: &str, client: Option<&str>) {
|
||||
self.clear_provider_diagnostics(plugin.id());
|
||||
let failures = {
|
||||
let mut meta = plugin.meta.lock();
|
||||
meta.failures += 1;
|
||||
@@ -1931,6 +2158,7 @@ impl PluginHost {
|
||||
level: NotificationLevel::Warning,
|
||||
title: format!("Plugin \u{201c}{}\u{201d} crashed", plugin.manifest().name),
|
||||
body: format!("{error}\nIt restarts the next time it is needed."),
|
||||
actions: Vec::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1947,6 +2175,8 @@ impl PluginHost {
|
||||
*runtime = None;
|
||||
}
|
||||
actor.stop(false);
|
||||
// Its handles go with its instance; an idle reclaim is one.
|
||||
self.shared.kill_processes(plugin.id());
|
||||
let mut meta = plugin.meta.lock();
|
||||
if meta.status == PluginStatus::Active {
|
||||
meta.status = PluginStatus::Inactive;
|
||||
@@ -1957,26 +2187,36 @@ impl PluginHost {
|
||||
}
|
||||
|
||||
fn stop(&self, plugin: &LoadedPlugin) {
|
||||
self.stop_web_ptys(plugin.id());
|
||||
self.clear_plugin_navigation(plugin.id());
|
||||
self.clear_plugin_endpoints(plugin.id());
|
||||
// A call waiting on the user would keep the join below waiting.
|
||||
self.shared.block_prompts(plugin.id());
|
||||
if let Some(actor) = plugin.runtime.lock().take() {
|
||||
actor.stop(true);
|
||||
}
|
||||
self.registry.dispose_plugin(plugin.id());
|
||||
self.clear_provider_diagnostics(plugin.id());
|
||||
self.shared.clear_plugin(plugin.id(), true);
|
||||
self.queues.lock().retain(|(id, _), _| id != plugin.id());
|
||||
}
|
||||
|
||||
fn set_failed(&self, plugin: &LoadedPlugin, error: String) {
|
||||
self.clear_plugin_navigation(plugin.id());
|
||||
self.clear_plugin_endpoints(plugin.id());
|
||||
tracing::warn!(plugin = %plugin.id(), "{error}");
|
||||
self.registry.dispose_plugin(plugin.id());
|
||||
self.clear_provider_diagnostics(plugin.id());
|
||||
let mut meta = plugin.meta.lock();
|
||||
meta.status = PluginStatus::Failed;
|
||||
meta.error = Some(error);
|
||||
drop(meta);
|
||||
self.stop_web_ptys(plugin.id());
|
||||
}
|
||||
|
||||
fn fail(&self, plugin: &LoadedPlugin, error: &str, client: Option<&str>) {
|
||||
self.clear_plugin_navigation(plugin.id());
|
||||
self.clear_plugin_endpoints(plugin.id());
|
||||
tracing::warn!(plugin = %plugin.id(), "disabled after failure: {error}");
|
||||
if let Some(actor) = plugin.runtime.lock().take() {
|
||||
actor.stop(false);
|
||||
@@ -1990,6 +2230,7 @@ impl PluginHost {
|
||||
level: NotificationLevel::Error,
|
||||
title: format!("Plugin \u{201c}{}\u{201d} was disabled", plugin.manifest().name),
|
||||
body: error.to_owned(),
|
||||
actions: Vec::new(),
|
||||
},
|
||||
);
|
||||
self.changed();
|
||||
@@ -2086,7 +2327,7 @@ impl PluginHost {
|
||||
return h.trim().to_owned();
|
||||
}
|
||||
// Installed before hashes were recorded: hash once and remember.
|
||||
let files = self.registry.prepare(&plugin.pkg).map(|s| s.files).unwrap_or_default();
|
||||
let files = self.prepare(&plugin.pkg).map(|s| s.files).unwrap_or_default();
|
||||
let files: Vec<PathBuf> = files.into_iter().chain(plugin.manifest().wasm.clone()).collect();
|
||||
let hash = ledger::package_hash(plugin.dir(), &files).unwrap_or_default();
|
||||
let _ = std::fs::write(&file, &hash);
|
||||
@@ -2153,6 +2394,7 @@ impl PluginHost {
|
||||
authors: m.authors.clone(),
|
||||
homepage: m.homepage.clone(),
|
||||
change_notes: m.change_notes.clone(),
|
||||
icon: p.icon.clone(),
|
||||
source: p.source,
|
||||
path: p.dir().to_path_buf().into(),
|
||||
enabled: !self.state.lock().disabled.contains(&m.id),
|
||||
@@ -2262,6 +2504,8 @@ fn placeholder_manifest(dir: &Path) -> Manifest {
|
||||
license: None,
|
||||
change_notes: None,
|
||||
declared_categories: Vec::new(),
|
||||
icon: None,
|
||||
icon_dark: None,
|
||||
engine: ide_extension::ENGINE_VERSION.into(),
|
||||
legacy: false,
|
||||
wasm: None,
|
||||
@@ -2331,6 +2575,70 @@ impl ide_language::ExternalSyntax for PluginSyntax {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn host_panics_stop_actor_and_reply_on_every_call_path() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host =
|
||||
PluginHost::new(tmp.path().join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap();
|
||||
let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/diagnostics");
|
||||
host.install_from_dir(&fixture, &Consent::all()).unwrap();
|
||||
let plugin = host.get("test.diagnostics").unwrap();
|
||||
for mode in 0..5 {
|
||||
let (actor, _) = host.ensure_active(&plugin, None).unwrap();
|
||||
let cancel = ide_core::CancellationToken::new();
|
||||
let next_actor = actor.clone();
|
||||
let (queued_tx, queued_rx) = std::sync::mpsc::channel();
|
||||
let panic = move |_: &mut Runtime| -> Result<(), CallError> {
|
||||
let pending = next_actor.submit(None, |_| Ok("must not run")).unwrap();
|
||||
queued_tx.send(pending).unwrap();
|
||||
panic!("host call panic")
|
||||
};
|
||||
let result = match mode {
|
||||
0 => actor.call(None, panic),
|
||||
1 => actor.call_cancellable(&cancel, Duration::ZERO, panic),
|
||||
2 => actor.call_edit_cancellable(&cancel, Duration::ZERO, Duration::from_secs(5), panic),
|
||||
_ => {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
if mode == 3 {
|
||||
actor.post(panic, move |result| {
|
||||
let _ = tx.send(result);
|
||||
});
|
||||
} else {
|
||||
actor.post(
|
||||
|_| Ok(()),
|
||||
move |result| {
|
||||
let _ = tx.send(result);
|
||||
panic!("completion callback panic");
|
||||
},
|
||||
);
|
||||
}
|
||||
rx.recv_timeout(Duration::from_secs(5)).expect("actor must reply")
|
||||
}
|
||||
};
|
||||
if mode < 4 {
|
||||
let queued = queued_rx.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
assert!(matches!(queued.wait(), Err(ActorError::Stopped)), "poisoned runtime must not run queued work");
|
||||
}
|
||||
actor.stop(true);
|
||||
if mode < 4 {
|
||||
assert!(
|
||||
matches!(result, Err(ActorError::Call(CallError::Trap(ref message))) if message.contains("host call panic")),
|
||||
"{result:?}"
|
||||
);
|
||||
}
|
||||
assert!(!actor.is_alive());
|
||||
assert!(!actor.is_busy());
|
||||
assert!(matches!(actor.call(None, |_| Ok(())), Err(ActorError::Stopped)));
|
||||
let crash = actor.take_crash().expect("supervisor must see the panic");
|
||||
assert!(crash.contains(if mode == 4 { "completion callback panic" } else { "host call panic" }));
|
||||
assert!(actor.take_crash().is_none());
|
||||
cancel.cancel();
|
||||
// Re-enable to reset the supervisor before testing the next call path.
|
||||
host.set_enabled("test.diagnostics", false).unwrap();
|
||||
host.set_enabled("test.diagnostics", true).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn globs() {
|
||||
assert!(glob_match("**/*Mapper.xml", "src/main/UserMapper.xml"));
|
||||
|
||||
@@ -59,6 +59,7 @@ pub fn register_builtin_points(
|
||||
registry.register(Arc::new(super::navigation::IndexersPoint))?;
|
||||
registry.register(Arc::new(super::providers::ProvidersPoint::new(providers.clone())))?;
|
||||
registry.register(Arc::new(UiPoint::new(super::providers::SECRETS_POINT, ui.clone(), super::providers::secret)))?;
|
||||
registry.register(Arc::new(UiPoint::new(super::endpoints::POINT, ui.clone(), super::endpoints::declaration)))?;
|
||||
use super::ui_points as p;
|
||||
registry.register(Arc::new(UiPoint::new(p::MENUS, ui.clone(), p::menu)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::KEYMAPS, ui.clone(), p::keymap)))?;
|
||||
@@ -66,7 +67,10 @@ pub fn register_builtin_points(
|
||||
registry.register(Arc::new(UiPoint::new(p::SETTINGS, ui.clone(), p::settings)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::VIEWS, ui.clone(), p::view)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::CUSTOM_EDITORS, ui.clone(), p::custom_editor)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::MARKER_ICONS, ui.clone(), p::marker_icon)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::FILE_ICONS, ui.clone(), p::file_icon)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::FILE_TEMPLATES, ui.clone(), p::file_template)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::COMMIT_CHECKS, ui.clone(), p::commit_check)))?;
|
||||
registry.register(Arc::new(UiPoint::new(ide_extension::LOCALES_POINT, ui.clone(), p::locales)))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -22,6 +22,7 @@
|
||||
use ide_extension::{Disposable, ExtensionPoint, Package, Placement, Prepared, UiDecl, decode, validate_item_id};
|
||||
use parking_lot::RwLock;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
@@ -37,6 +38,10 @@ pub enum ProviderKind {
|
||||
CodeActions,
|
||||
Definition,
|
||||
LineMarkers,
|
||||
SemanticTokens,
|
||||
Hover,
|
||||
InlayHints,
|
||||
Diagnostics,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
@@ -70,13 +75,26 @@ impl Providers {
|
||||
|
||||
/// Plugins providing `kind` for `language`, in declaration order.
|
||||
pub fn plugins_for(&self, kind: ProviderKind, language: &str) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for (_, plugin, kinds, languages) in self.items.read().iter() {
|
||||
if kinds.contains(&kind) && languages.iter().any(|l| l == "*" || l == language) && !out.contains(plugin) {
|
||||
out.push(plugin.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
self.matching::<Vec<_>>(kind, language).into_iter().map(|(plugin, _)| plugin).collect()
|
||||
}
|
||||
|
||||
/// One coherent declaration snapshot, preserving the first match per plugin.
|
||||
fn matching<T: FromIterator<(String, u64)>>(&self, kind: ProviderKind, language: &str) -> T {
|
||||
let items = self.items.read();
|
||||
let mut seen = HashSet::new();
|
||||
items
|
||||
.iter()
|
||||
.filter(|(_, plugin, kinds, languages)| {
|
||||
kinds.contains(&kind)
|
||||
&& languages.iter().any(|l| l == "*" || l == language)
|
||||
&& seen.insert(plugin.as_str())
|
||||
})
|
||||
.map(|(seq, plugin, ..)| (plugin.clone(), *seq))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn diagnostic_generations(&self, language: &str) -> HashMap<String, u64> {
|
||||
self.matching(ProviderKind::Diagnostics, language)
|
||||
}
|
||||
|
||||
/// Whether any plugin provides `kind` (for any language).
|
||||
@@ -112,6 +130,18 @@ impl ExtensionPoint for ProvidersPoint {
|
||||
if d.kinds.is_empty() || d.languages.is_empty() || d.languages.len() > 64 {
|
||||
return Err("contributes.providers: give `kinds` and 1–64 `languages`".into());
|
||||
}
|
||||
if d.kinds.contains(&ProviderKind::SemanticTokens) {
|
||||
pkg.manifest.needs_api("contributes.providers: semantic-tokens", 3)?;
|
||||
}
|
||||
if d.kinds.contains(&ProviderKind::Diagnostics) {
|
||||
pkg.manifest.needs_api("contributes.providers: diagnostics", 3)?;
|
||||
}
|
||||
if d.kinds.contains(&ProviderKind::Hover) {
|
||||
pkg.manifest.needs_api("contributes.providers: hover", 3)?;
|
||||
}
|
||||
if d.kinds.contains(&ProviderKind::InlayHints) {
|
||||
pkg.manifest.needs_api("contributes.providers: inlay-hints", 3)?;
|
||||
}
|
||||
for l in &d.languages {
|
||||
if l != "*"
|
||||
&& (l.is_empty()
|
||||
@@ -157,11 +187,11 @@ pub(super) fn secret(_pkg: &Package, decl: toml::Value) -> Result<UiDecl, String
|
||||
|
||||
// ---- dispatch ---------------------------------------------------------------
|
||||
|
||||
use super::{LoadedPlugin, PluginHost, PluginStatus};
|
||||
use super::{LoadedPlugin, PluginEvent, PluginHost, PluginStatus};
|
||||
use ide_core::CancellationToken;
|
||||
use ide_plugin::{
|
||||
ActorError, CallError, CodeAction, CompletionItem, InlineSuggestion, LineMarker, Location, Pending,
|
||||
ProviderDocument, Runtime,
|
||||
ActorError, CallError, CodeAction, CompletionItem, InlineSuggestion, LineMarker, Location, Pending, PluginHover,
|
||||
PluginInlayHint, ProviderDocument, Runtime, SemanticToken,
|
||||
};
|
||||
use std::sync::Weak;
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -190,7 +220,7 @@ pub(crate) fn editor_plugin_host() -> Option<Arc<PluginHost>> {
|
||||
|
||||
impl PluginHost {
|
||||
/// Usable plugins declaring `kind` for `language`.
|
||||
fn provider_plugins(&self, kind: ProviderKind, language: &str) -> Vec<Arc<LoadedPlugin>> {
|
||||
pub(super) fn provider_plugins(&self, kind: ProviderKind, language: &str) -> Vec<Arc<LoadedPlugin>> {
|
||||
self.providers
|
||||
.plugins_for(kind, language)
|
||||
.into_iter()
|
||||
@@ -303,14 +333,21 @@ impl PluginHost {
|
||||
plugin_id: &str,
|
||||
doc: &ProviderDocument,
|
||||
action: CodeAction,
|
||||
invocation: ide_plugin::Invocation,
|
||||
) -> ide_core::IdeResult<CodeAction> {
|
||||
let d = Arc::new(doc.clone());
|
||||
let timeout = self.limits.timeout;
|
||||
self.code_call(plugin_id, ide_plugin::Invocation::default(), "resolving the code action", move |rt, _| {
|
||||
rt.resolve_code_action(&d, &action, timeout)
|
||||
self.code_call(plugin_id, invocation, "resolving the code action", move |rt, inv| {
|
||||
rt.resolve_code_action(&d, &action, inv, timeout)
|
||||
})
|
||||
}
|
||||
|
||||
/// Shows `path` in window `client` after a code action of `plugin_id` was applied.
|
||||
pub fn open_file(&self, plugin_id: &str, client: &str, path: ide_core::IpcPath) {
|
||||
let event = PluginEvent::OpenLocation { plugin_id: plugin_id.to_owned(), path, line: 0, column: 0 };
|
||||
self.emit(Some(client), event);
|
||||
}
|
||||
|
||||
pub fn provide_definition(&self, doc: &ProviderDocument, at: ide_core::Pos) -> Vec<Location> {
|
||||
let d = Arc::new(doc.clone());
|
||||
self.edit_calls(ProviderKind::Definition, &doc.language, move |rt, timeout| {
|
||||
@@ -331,6 +368,87 @@ impl PluginHost {
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn provide_semantic_tokens(&self, doc: &ProviderDocument) -> Vec<SemanticToken> {
|
||||
let d = Arc::new(doc.clone());
|
||||
self.edit_calls(ProviderKind::SemanticTokens, &doc.language, move |rt, timeout| {
|
||||
rt.provide_semantic_tokens(&d, timeout)
|
||||
})
|
||||
.into_iter()
|
||||
.flat_map(|(_, tokens)| tokens)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn provide_diagnostics(
|
||||
&self,
|
||||
doc: &ProviderDocument,
|
||||
cancel: &CancellationToken,
|
||||
) -> Vec<(String, Vec<ide_core::Diagnostic>)> {
|
||||
self.provide_project_diagnostics(None, doc, cancel)
|
||||
}
|
||||
|
||||
pub(super) fn diagnostic_plugins(
|
||||
&self,
|
||||
project: Option<&std::path::Path>,
|
||||
language: &str,
|
||||
) -> Vec<Arc<LoadedPlugin>> {
|
||||
self.provider_plugins(ProviderKind::Diagnostics, language)
|
||||
.into_iter()
|
||||
.filter(|p| p.dev_root.is_none() || p.dev_root.as_deref() == project)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn provide_project_diagnostics(
|
||||
&self,
|
||||
project: Option<&std::path::Path>,
|
||||
doc: &ProviderDocument,
|
||||
cancel: &CancellationToken,
|
||||
) -> Vec<(String, Vec<ide_core::Diagnostic>)> {
|
||||
std::thread::scope(|scope| {
|
||||
let calls: Vec<_> = self
|
||||
.diagnostic_plugins(project, &doc.language)
|
||||
.into_iter()
|
||||
.map(|p| {
|
||||
scope.spawn(move || {
|
||||
if cancel.is_cancelled() {
|
||||
return None;
|
||||
}
|
||||
let (actor, activated) = self.ensure_active(&p, None).ok()?;
|
||||
if activated {
|
||||
self.changed();
|
||||
}
|
||||
let (d, timeout) = (doc.clone(), self.limits.edit_hard);
|
||||
let started = Instant::now();
|
||||
let result =
|
||||
actor.call_edit_cancellable(cancel, CANCEL_GRACE, self.limits.edit_soft, move |rt| {
|
||||
rt.provide_diagnostics(&d, timeout)
|
||||
});
|
||||
let items = self.finish_provider_call(&p, &actor, started, result)?;
|
||||
(!cancel.is_cancelled()).then(|| (p.id().to_owned(), items))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
calls.into_iter().filter_map(|call| call.join().ok().flatten()).collect()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn provide_hover(&self, doc: &ProviderDocument, at: ide_core::Pos) -> Vec<PluginHover> {
|
||||
let d = Arc::new(doc.clone());
|
||||
self.edit_calls(ProviderKind::Hover, &doc.language, move |rt, timeout| rt.provide_hover(&d, at, timeout))
|
||||
.into_iter()
|
||||
.filter_map(|(_, hover)| hover)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn provide_inlay_hints(&self, doc: &ProviderDocument, range: ide_core::Range) -> Vec<PluginInlayHint> {
|
||||
let d = Arc::new(doc.clone());
|
||||
self.edit_calls(ProviderKind::InlayHints, &doc.language, move |rt, timeout| {
|
||||
rt.provide_inlay_hints(&d, range, timeout)
|
||||
})
|
||||
.into_iter()
|
||||
.flat_map(|(_, hints)| hints)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Ghost text from the first plugin that has some. Not bound by the
|
||||
/// edit-path soft deadline (it may need the network) but by `cancel`:
|
||||
/// the editor cancels a request as soon as the user types on.
|
||||
@@ -359,3 +477,41 @@ impl PluginHost {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn provider_snapshots_preserve_order_first_generation_and_language_matching() {
|
||||
let providers = Arc::new(Providers::default());
|
||||
let declare = |plugin: &str, kind, language: &str| {
|
||||
providers.add(plugin.into(), Decl { kinds: vec![kind], languages: vec![language.into()] })
|
||||
};
|
||||
let mut declarations = Vec::new();
|
||||
declarations.push(declare("unrelated", ProviderKind::Hover, "*"));
|
||||
declarations.push(declare("other-language", ProviderKind::Diagnostics, "rust"));
|
||||
for i in 0..256 {
|
||||
let plugin = format!("plugin-{i}");
|
||||
declarations.push(declare(&plugin, ProviderKind::Diagnostics, "text"));
|
||||
declarations.push(declare(&plugin, ProviderKind::Diagnostics, "*"));
|
||||
}
|
||||
let expected: Vec<_> = (0..256).map(|i| format!("plugin-{i}")).collect();
|
||||
assert_eq!(providers.plugins_for(ProviderKind::Diagnostics, "text"), expected);
|
||||
let before = providers.diagnostic_generations("text");
|
||||
assert_eq!(before.len(), 256);
|
||||
assert_eq!(before["plugin-0"], 2);
|
||||
assert_eq!(providers.diagnostic_generations("rust").len(), 257);
|
||||
assert_eq!(providers.plugins_for(ProviderKind::Hover, "text"), ["unrelated"]);
|
||||
// Removing the first matching declaration must invalidate its generation,
|
||||
// even while a second declaration still provides the same language.
|
||||
drop(declarations.remove(2));
|
||||
let after = providers.diagnostic_generations("text");
|
||||
assert_eq!(after["plugin-0"], 3);
|
||||
assert_ne!(before["plugin-0"], after["plugin-0"]);
|
||||
drop(declarations);
|
||||
assert!(providers.diagnostic_generations("text").is_empty());
|
||||
let _reloaded = declare("plugin-0", ProviderKind::Diagnostics, "text");
|
||||
assert_ne!(providers.diagnostic_generations("text")["plugin-0"], after["plugin-0"]);
|
||||
}
|
||||
}
|
||||
@@ -13,8 +13,9 @@
|
||||
//!
|
||||
//! The commands a window needs at run time (`plugin_run_command`,
|
||||
//! `plugin_post_events`, `plugin_event_kinds`, `plugin_status_items`,
|
||||
//! `plugin_cancel_task`, `plugin_set_active_file`, `plugin_line_markers`,
|
||||
//! `plugin_view_render`, `plugin_view_event`)
|
||||
//! `plugin_context_keys`, `plugin_cancel_task`, `plugin_answer_prompt`, `plugin_set_active_file`,
|
||||
//! `plugin_line_markers`, `plugin_set_ui_locale`, `plugin_view_render`, `plugin_view_event`,
|
||||
//! `plugin_service_detail`, `plugin_service_log`, `plugin_answer_commit`, `plugin_commit_checks`)
|
||||
//! carry the desktop commands' names and arguments, so a remote window's UI
|
||||
//! routes them here unchanged. Plugin results come back as `plugin`
|
||||
//! notifications ([`PluginEventMessage`]); secrets stay in the desktop's
|
||||
@@ -107,6 +108,7 @@ pub fn forwarded(event: &PluginEvent) -> bool {
|
||||
event,
|
||||
PluginEvent::Notification { .. }
|
||||
| PluginEvent::StatusItemChanged { .. }
|
||||
| PluginEvent::ContextChanged { .. }
|
||||
| PluginEvent::TaskStarted { .. }
|
||||
| PluginEvent::TaskProgress { .. }
|
||||
| PluginEvent::TaskEnded { .. }
|
||||
@@ -117,6 +119,12 @@ pub fn forwarded(event: &PluginEvent) -> bool {
|
||||
| PluginEvent::OpenLocation { .. }
|
||||
| PluginEvent::CopyToClipboard { .. }
|
||||
| PluginEvent::OpenUrl { .. }
|
||||
| PluginEvent::OpenProject { .. }
|
||||
| PluginEvent::PromptRequested { .. }
|
||||
| PluginEvent::PromptClosed { .. }
|
||||
| PluginEvent::RevealView { .. }
|
||||
| PluginEvent::CommitRequested { .. }
|
||||
| PluginEvent::EndpointsChanged { .. }
|
||||
)
|
||||
}
|
||||
|
||||
@@ -124,7 +132,7 @@ pub fn forwarded(event: &PluginEvent) -> bool {
|
||||
|
||||
impl PluginHost {
|
||||
fn package_files(&self, plugin: &super::LoadedPlugin) -> IdeResult<Vec<PathBuf>> {
|
||||
let set = self.registry.prepare(&plugin.pkg).map_err(IdeError::invalid)?;
|
||||
let set = self.prepare(&plugin.pkg).map_err(IdeError::invalid)?;
|
||||
Ok(set.files.into_iter().chain(plugin.manifest().wasm.clone()).collect())
|
||||
}
|
||||
|
||||
@@ -367,15 +375,25 @@ impl RemotePlugins {
|
||||
let command_id: String = c.arg("commandId")?;
|
||||
let arg: Option<String> = c.arg("arg")?;
|
||||
let editor: Option<PluginEditor> = c.arg("editor")?;
|
||||
let paths: Option<Vec<PathBuf>> = c.arg("paths")?;
|
||||
let invocation = Invocation {
|
||||
client: Some(c.window.clone()),
|
||||
workspace_root: c.host.project(&c.window).ok().map(|p| p.root.clone()),
|
||||
editor: editor.map(PluginEditor::context),
|
||||
selected_paths: paths.unwrap_or_default(),
|
||||
};
|
||||
blocking(move || host.run_command(&plugin_id, &command_id, arg.as_deref(), invocation)).await
|
||||
}
|
||||
});
|
||||
let h = host.clone();
|
||||
d.add("plugin_set_ui_locale", move |c| {
|
||||
let h = h.clone();
|
||||
async move {
|
||||
alive(&h)?.set_ui_locale(&c.arg::<String>("tag")?);
|
||||
Ok(())
|
||||
}
|
||||
});
|
||||
let h = host.clone();
|
||||
d.add("plugin_post_events", move |c| {
|
||||
let h = h.clone();
|
||||
async move {
|
||||
@@ -400,11 +418,41 @@ impl RemotePlugins {
|
||||
}
|
||||
});
|
||||
let h = host.clone();
|
||||
d.add("plugin_context_keys", move |c| {
|
||||
let h = h.clone();
|
||||
async move { Ok(alive(&h)?.context_keys(Some(&c.window))) }
|
||||
});
|
||||
let h = host.clone();
|
||||
d.add("plugin_cancel_task", move |c| {
|
||||
let h = h.clone();
|
||||
async move { Ok(alive(&h)?.cancel_task(&c.arg::<String>("taskId")?)) }
|
||||
});
|
||||
let h = host.clone();
|
||||
d.add("plugin_answer_prompt", move |c| {
|
||||
let h = h.clone();
|
||||
async move { Ok(alive(&h)?.answer_prompt(&c.arg::<String>("promptId")?, c.arg("answer")?)) }
|
||||
});
|
||||
let h = host.clone();
|
||||
d.add("plugin_answer_commit", move |c| {
|
||||
let h = h.clone();
|
||||
async move { Ok(alive(&h)?.answer_commit(&c.arg::<String>("requestId")?, c.arg("answer")?)) }
|
||||
});
|
||||
let h = host.clone();
|
||||
d.add("plugin_commit_checks", move |c| {
|
||||
let h = h.clone();
|
||||
async move {
|
||||
super::commit::commit_checks(
|
||||
&c.host,
|
||||
alive(&h)?,
|
||||
&c.window,
|
||||
c.arg("selection")?,
|
||||
c.arg("checks")?,
|
||||
c.arg("request")?,
|
||||
)
|
||||
.await
|
||||
}
|
||||
});
|
||||
let h = host.clone();
|
||||
d.add("plugin_set_active_file", move |c| {
|
||||
let h = h.clone();
|
||||
async move {
|
||||
@@ -449,6 +497,40 @@ impl RemotePlugins {
|
||||
}
|
||||
});
|
||||
let h = host.clone();
|
||||
d.add("plugin_service_detail", move |c| {
|
||||
let h = h.clone();
|
||||
async move {
|
||||
super::views::service_detail(
|
||||
&c.host,
|
||||
alive(&h)?,
|
||||
&c.window,
|
||||
c.arg("pluginId")?,
|
||||
c.arg("view")?,
|
||||
c.arg("key")?,
|
||||
)
|
||||
.await
|
||||
}
|
||||
});
|
||||
let h = host.clone();
|
||||
d.add("plugin_service_log", move |c| {
|
||||
let h = h.clone();
|
||||
async move {
|
||||
super::views::service_log(
|
||||
&c.host,
|
||||
alive(&h)?,
|
||||
&c.window,
|
||||
c.arg("pluginId")?,
|
||||
c.arg("view")?,
|
||||
c.arg("key")?,
|
||||
c.arg("tab")?,
|
||||
c.arg("on")?,
|
||||
c.arg("request")?,
|
||||
c.sender("onLine")?,
|
||||
)
|
||||
.await
|
||||
}
|
||||
});
|
||||
let h = host.clone();
|
||||
d.add("plugin_navigation_files", move |c| {
|
||||
let h = h.clone();
|
||||
async move { super::index_ops::plugin_navigation_files(&c.host, alive(&h)?, &c.window).await }
|
||||
@@ -486,6 +568,11 @@ impl RemotePlugins {
|
||||
super::index_ops::plugin_navigation_markers(&c.host, alive(&h)?, &c.window, c.arg("paths")?).await
|
||||
}
|
||||
});
|
||||
let h = host.clone();
|
||||
d.add("plugin_endpoints", move |c| {
|
||||
let h = h.clone();
|
||||
async move { super::index_ops::plugin_endpoints(&c.host, alive(&h)?, &c.window, c.arg("pluginId")?).await }
|
||||
});
|
||||
d.add("plugin_line_markers", |c| async move {
|
||||
crate::ops::lsp::plugin_line_markers(&c.host, &c.window, c.arg("doc")?).await
|
||||
});
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
use ide_lsp::types::SemanticTokens;
|
||||
use ide_plugin::SemanticToken;
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub(crate) fn merge(server: Option<SemanticTokens>, plugin: Vec<SemanticToken>) -> SemanticTokens {
|
||||
let mut out = server.unwrap_or_else(|| SemanticTokens {
|
||||
data: Vec::new(),
|
||||
token_types: Vec::new(),
|
||||
token_modifiers: Vec::new(),
|
||||
});
|
||||
let mut added: Vec<[u32; 5]> = Vec::with_capacity(plugin.len());
|
||||
let mut lines: HashMap<u32, Vec<(u32, u32)>> = HashMap::new();
|
||||
for token in plugin {
|
||||
let (start, end) = (token.range.start, token.range.end);
|
||||
if start.line != end.line || end.col <= start.col {
|
||||
continue;
|
||||
}
|
||||
let kind = camel_case(&token.kind);
|
||||
let kind = match out.token_types.iter().position(|t| *t == kind) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
out.token_types.push(kind);
|
||||
out.token_types.len() - 1
|
||||
}
|
||||
};
|
||||
let mut bits = 0u32;
|
||||
for modifier in &token.modifiers {
|
||||
let modifier = camel_case(modifier);
|
||||
let i = match out.token_modifiers.iter().position(|m| *m == modifier) {
|
||||
Some(i) => i,
|
||||
None if out.token_modifiers.len() < 32 => {
|
||||
out.token_modifiers.push(modifier);
|
||||
out.token_modifiers.len() - 1
|
||||
}
|
||||
None => continue,
|
||||
};
|
||||
bits |= 1 << i;
|
||||
}
|
||||
lines.entry(start.line).or_default().push((start.col, end.col));
|
||||
added.push([start.line, start.col, end.col - start.col, kind as u32, bits]);
|
||||
}
|
||||
let covered = |t: &[u32; 5]| {
|
||||
lines.get(&t[0]).is_some_and(|ranges| ranges.iter().any(|&(from, to)| t[1] < to && from < t[1] + t[2]))
|
||||
};
|
||||
let mut data: Vec<[u32; 5]> = out.data.as_chunks::<5>().0.iter().filter(|t| !covered(t)).copied().collect();
|
||||
data.extend(added);
|
||||
data.sort_by_key(|t| (t[0], t[1]));
|
||||
out.data = data.into_iter().flatten().collect();
|
||||
out
|
||||
}
|
||||
|
||||
fn camel_case(name: &str) -> String {
|
||||
let mut out = String::with_capacity(name.len());
|
||||
let mut upper = false;
|
||||
for c in name.chars() {
|
||||
if c == '-' {
|
||||
upper = true;
|
||||
} else if upper {
|
||||
out.extend(c.to_uppercase());
|
||||
upper = false;
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::{Pos, Range};
|
||||
|
||||
fn token(line: u32, from: u32, to: u32, kind: &str, modifiers: &[&str]) -> SemanticToken {
|
||||
SemanticToken {
|
||||
range: Range::new(Pos::new(line, from), Pos::new(line, to)),
|
||||
kind: kind.into(),
|
||||
modifiers: modifiers.iter().map(|m| (*m).into()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn server() -> SemanticTokens {
|
||||
SemanticTokens {
|
||||
data: vec![0, 0, 6, 0, 0, 1, 4, 5, 1, 1, 1, 12, 3, 1, 0],
|
||||
token_types: vec!["variable".into(), "property".into()],
|
||||
token_modifiers: vec!["readonly".into()],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_tokens_replace_the_server_tokens_they_overlap() {
|
||||
let merged = merge(Some(server()), vec![token(1, 6, 10, "method", &[])]);
|
||||
assert_eq!(merged.token_types, ["variable", "property", "method"]);
|
||||
assert_eq!(merged.data, [0, 0, 6, 0, 0, 1, 6, 4, 2, 0, 1, 12, 3, 1, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kinds_and_modifiers_use_the_lsp_names() {
|
||||
let merged = merge(None, vec![token(2, 0, 3, "type-parameter", &["default-library", "readonly"])]);
|
||||
assert_eq!(merged.token_types, ["typeParameter"]);
|
||||
assert_eq!(merged.token_modifiers, ["defaultLibrary", "readonly"]);
|
||||
assert_eq!(merged.data, [2, 0, 3, 0, 0b11]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_names_reuse_the_server_legend() {
|
||||
let merged = merge(Some(server()), vec![token(3, 1, 2, "property", &["readonly"])]);
|
||||
assert_eq!(merged.token_types.len(), 2);
|
||||
assert_eq!(merged.token_modifiers.len(), 1);
|
||||
assert_eq!(merged.data[15..], [3, 1, 1, 1, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_spanning_lines_or_empty_are_ignored() {
|
||||
let multi = SemanticToken {
|
||||
range: Range::new(Pos::new(0, 4), Pos::new(1, 2)),
|
||||
kind: "method".into(),
|
||||
modifiers: Vec::new(),
|
||||
};
|
||||
let merged = merge(Some(server()), vec![multi, token(0, 3, 3, "method", &[])]);
|
||||
assert_eq!(merged.data, server().data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modifiers_past_thirty_two_are_dropped() {
|
||||
let names: Vec<String> = (0..40).map(|i| format!("m{i}")).collect();
|
||||
let refs: Vec<&str> = names.iter().map(String::as_str).collect();
|
||||
let merged = merge(None, vec![token(0, 0, 1, "type", &refs)]);
|
||||
assert_eq!(merged.token_modifiers.len(), 32);
|
||||
assert_eq!(merged.data[4], u32::MAX);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,22 @@
|
||||
//! UI-facing plugin types and the event stream.
|
||||
|
||||
use super::theme::ThemeDef;
|
||||
use ide_extension::package::PluginIcon;
|
||||
use ide_extension::{CapabilityInfo, ContributionInfo, UiContribution};
|
||||
pub use ide_plugin::{ActionPerformed, ActionSource, EventKind, NotificationLevel, StatusItem, WorkbenchEvent};
|
||||
pub use ide_plugin::{
|
||||
ActionPerformed, ActionSource, EventKind, NotificationLevel, PickItem, Prompt, StatusItem, WorkbenchEvent,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// A line a view's `process` body printed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginOutputLine {
|
||||
pub stderr: bool,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PluginSource {
|
||||
@@ -50,6 +61,7 @@ pub struct PluginInfo {
|
||||
pub authors: Vec<String>,
|
||||
pub homepage: Option<String>,
|
||||
pub change_notes: Option<String>,
|
||||
pub icon: Option<PluginIcon>,
|
||||
pub source: PluginSource,
|
||||
/// Package directory.
|
||||
pub path: ide_core::IpcPath,
|
||||
@@ -113,6 +125,7 @@ pub struct CatalogPlugin {
|
||||
pub authors: Vec<String>,
|
||||
pub homepage: Option<String>,
|
||||
pub change_notes: Option<String>,
|
||||
pub icon: Option<PluginIcon>,
|
||||
/// Package directory; install with `install_from_dir(path)`.
|
||||
pub path: ide_core::IpcPath,
|
||||
pub has_code: bool,
|
||||
@@ -155,14 +168,29 @@ pub enum PluginEvent {
|
||||
CommandsChanged,
|
||||
/// Cached document associations were disposed (reload, disable or failure).
|
||||
DocumentIndexesChanged,
|
||||
/// The routes `plugin_id` reports for the project `root` may have changed:
|
||||
/// ask `plugin_endpoints` again.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
EndpointsChanged { plugin_id: String, root: ide_core::IpcPath },
|
||||
/// The marketplace offers newer versions of installed plugins (announced
|
||||
/// once per set of versions).
|
||||
UpdatesAvailable { updates: Vec<PluginUpdate> },
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Notification { plugin_id: String, level: NotificationLevel, title: String, body: String },
|
||||
Notification {
|
||||
plugin_id: String,
|
||||
level: NotificationLevel,
|
||||
title: String,
|
||||
body: String,
|
||||
/// Buttons running the plugin's own commands (`ui.notify`).
|
||||
actions: Vec<ide_plugin::NotificationAction>,
|
||||
},
|
||||
/// A plugin's status bar item was set (`item`) or removed.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
StatusItemChanged { plugin_id: String, id: String, item: Option<StatusItem> },
|
||||
/// A plugin's context key was set (`value`: JSON text) or removed, in the
|
||||
/// emitted window (every window when the client is `None`).
|
||||
#[serde(rename_all = "camelCase")]
|
||||
ContextChanged { plugin_id: String, key: String, value: Option<String> },
|
||||
/// A plugin began a task: show it with the background tasks.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
TaskStarted { plugin_id: String, task_id: String, title: String, cancellable: bool },
|
||||
@@ -205,6 +233,68 @@ pub enum PluginEvent {
|
||||
/// Open `url` (`http(s)://`) in the system browser.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
OpenUrl { plugin_id: String, url: String },
|
||||
/// A window command/event requests the normal File > Open flow.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
OpenProject { plugin_id: String, path: String, new_window: bool },
|
||||
/// A command waits for the user's answer: show `prompt`, then report it with
|
||||
/// `plugin_answer_prompt(prompt_id, …)`.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
PromptRequested { plugin_id: String, prompt_id: String, prompt: Prompt },
|
||||
/// The call that asked gave up (cancelled, or its plugin stopped): close the prompt.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
PromptClosed { prompt_id: String },
|
||||
/// Bring the tool window of the plugin's view `view` to the front.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
RevealView { plugin_id: String, view: String },
|
||||
/// A command needs the window's Commit view: answer with
|
||||
/// `plugin_answer_commit(request_id, …)`. Closed like a prompt (`PromptClosed`).
|
||||
#[serde(rename_all = "camelCase")]
|
||||
CommitRequested { plugin_id: String, request_id: String, request: CommitRequest },
|
||||
}
|
||||
|
||||
/// What a plugin asks of a window's Commit view.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum CommitRequest {
|
||||
/// What Commit would commit now ([`CommitAnswer::Selection`]); unsaved
|
||||
/// editors of the included files are saved first.
|
||||
Selection,
|
||||
/// Replace the message if the draft is still at `revision`.
|
||||
SetMessage { revision: u64, message: String },
|
||||
}
|
||||
|
||||
/// A window's answer to a [`CommitRequest`].
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum CommitAnswer {
|
||||
/// The window's project has no repository.
|
||||
NoRepository,
|
||||
Selection {
|
||||
selection: CommitSelection,
|
||||
},
|
||||
/// The message was replaced.
|
||||
Done,
|
||||
/// The draft is no longer at the revision.
|
||||
Stale,
|
||||
}
|
||||
|
||||
/// What a window's Commit view would commit: per repository, the options
|
||||
/// `vcs_commit` would get.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CommitSelection {
|
||||
/// Changes whenever the message, the included changes or Amend do.
|
||||
pub revision: u64,
|
||||
pub message: String,
|
||||
pub amend: bool,
|
||||
pub repositories: Vec<CommitSelectionRepo>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CommitSelectionRepo {
|
||||
pub root: ide_core::IpcPath,
|
||||
pub options: ide_vcs::CommitOptions,
|
||||
}
|
||||
|
||||
/// Delivers events to the UI. `client` is the window that invoked the plugin
|
||||
@@ -251,6 +341,15 @@ pub struct PluginStatusItem {
|
||||
pub item: StatusItem,
|
||||
}
|
||||
|
||||
/// A plugin's context key for `when` clauses (`value` is JSON text).
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginContextKey {
|
||||
pub plugin_id: String,
|
||||
pub key: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
/// A gutter marker from a plugin's `line-markers` provider.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -264,3 +363,24 @@ pub struct LineMarkerInfo {
|
||||
/// Opened on click.
|
||||
pub target: Option<ide_core::Location>,
|
||||
}
|
||||
|
||||
/// A plugin's before-commit check to run (`[[contributes.commitChecks]]`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginCommitCheckRef {
|
||||
pub plugin_id: String,
|
||||
pub check: String,
|
||||
}
|
||||
|
||||
/// What a plugin's before-commit check found.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginCommitCheckResult {
|
||||
pub plugin_id: String,
|
||||
pub check: String,
|
||||
/// The check's declared title.
|
||||
pub title: String,
|
||||
pub problems: Vec<ide_plugin::CommitProblem>,
|
||||
/// The check could not run (the plugin failed, timed out or lacks `vcs.read`).
|
||||
pub error: Option<String>,
|
||||
}
|
||||
@@ -5,9 +5,10 @@
|
||||
//!
|
||||
//! ```toml
|
||||
//! [[contributes.menus]]
|
||||
//! menu = "editor.context" # projectView.context, editorTab.context, tools
|
||||
//! menu = "editor.context" # projectView.context, editorTab.context, tools, viewItem.context, commit.message
|
||||
//! command = "check"
|
||||
//! when = "editorLang == java"
|
||||
//! # view = "<view id>" # required for (only allowed on) viewItem.context
|
||||
//!
|
||||
//! [[contributes.keymaps]]
|
||||
//! command = "check"
|
||||
@@ -25,7 +26,7 @@
|
||||
//! id = "jobs"
|
||||
//! title = "Jobs"
|
||||
//! icon = "server"
|
||||
//! location = "right" # left, right, bottom
|
||||
//! location = "right" # left, right, bottom, services (nodes of the Services tool window)
|
||||
//!
|
||||
//! [[contributes.customEditors]]
|
||||
//! id = "table"
|
||||
@@ -41,6 +42,10 @@
|
||||
//! icon = "icons/drawing.svg"
|
||||
//! iconDark = "icons/drawing_dark.svg"
|
||||
//!
|
||||
//! [[contributes.commitChecks]]
|
||||
//! id = "conventional"
|
||||
//! title = "Conventional Commits" # Commit Options › Before Commit; `commit-checker.check` runs it
|
||||
//!
|
||||
//! [[contributes.fileTemplates]]
|
||||
//! id = "drawing"
|
||||
//! name = "Excalidraw Drawing"
|
||||
@@ -48,12 +53,15 @@
|
||||
//! path = "templates/drawing.excalidraw"
|
||||
//! ```
|
||||
|
||||
use ide_extension::{Package, UiDecl, decode, validate_item_id, validate_when};
|
||||
use ide_extension::{LOCALES_DIR, Package, UiDecl, decode, validate_item_id, validate_when};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::PathBuf;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// A view whose tree shows in the Services tool window; the plugin's
|
||||
/// `detail-provider` renders the selected node's pane.
|
||||
pub const SERVICES_LOCATION: &str = "services";
|
||||
pub const MENUS: &str = "menus";
|
||||
pub const KEYMAPS: &str = "keymaps";
|
||||
pub const STATUS_BAR: &str = "statusBar";
|
||||
@@ -61,9 +69,15 @@ pub const SETTINGS: &str = "settings";
|
||||
pub const VIEWS: &str = "views";
|
||||
pub const CUSTOM_EDITORS: &str = "customEditors";
|
||||
pub const FILE_ICONS: &str = "fileIcons";
|
||||
pub const MARKER_ICONS: &str = "markerIcons";
|
||||
pub const FILE_TEMPLATES: &str = "fileTemplates";
|
||||
pub const COMMIT_CHECKS: &str = "commitChecks";
|
||||
|
||||
const MENU_IDS: [&str; 4] = ["editor.context", "projectView.context", "editorTab.context", "tools"];
|
||||
const VIEW_ITEM_MENU: &str = "viewItem.context";
|
||||
/// The toolbar above the commit message (Commit tool window and dialog).
|
||||
const COMMIT_MESSAGE_MENU: &str = "commit.message";
|
||||
const MENU_IDS: [&str; 6] =
|
||||
["editor.context", "projectView.context", "editorTab.context", "tools", VIEW_ITEM_MENU, COMMIT_MESSAGE_MENU];
|
||||
const MAX_TITLE: usize = 256;
|
||||
const MAX_SETTINGS: usize = 200;
|
||||
const MAX_PATTERNS: usize = 16;
|
||||
@@ -77,6 +91,10 @@ fn commands(pkg: &Package) -> BTreeSet<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn declared_view(pkg: &Package, id: &str) -> Option<toml::Value> {
|
||||
pkg.manifest.declarations(VIEWS).into_iter().find(|d| d.get("id").and_then(|v| v.as_str()) == Some(id))
|
||||
}
|
||||
|
||||
fn declared_command(pkg: &Package, point: &str, command: &str) -> Result<(), String> {
|
||||
if commands(pkg).contains(command) {
|
||||
Ok(())
|
||||
@@ -103,6 +121,12 @@ struct MenuDecl {
|
||||
command: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
when: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
view: Option<String>,
|
||||
/// Groups the plugin's entries of one context menu that name the same
|
||||
/// submenu under it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
submenu: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
@@ -111,10 +135,37 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
return Err(format!("contributes.menus: unknown menu {:?} (one of {})", d.menu, MENU_IDS.join(", ")));
|
||||
}
|
||||
declared_command(pkg, MENUS, &d.command)?;
|
||||
if d.menu == COMMIT_MESSAGE_MENU {
|
||||
pkg.manifest.needs_api(&format!("contributes.menus: {COMMIT_MESSAGE_MENU}"), 3)?;
|
||||
}
|
||||
if let Some(w) = &d.when {
|
||||
validate_when(w).map_err(|e| format!("contributes.menus: {e}"))?;
|
||||
}
|
||||
Ok(UiDecl::new(format!("{}/{}", d.menu, d.command), d.command.clone(), json(&d)?))
|
||||
if let Some(submenu) = &d.submenu {
|
||||
if !d.menu.ends_with(".context") {
|
||||
return Err(format!("contributes.menus: `submenu` is only for context menus, not {:?}", d.menu));
|
||||
}
|
||||
title(MENUS, submenu)?;
|
||||
pkg.manifest.needs_api("contributes.menus: submenu", 3)?;
|
||||
}
|
||||
let key = match (d.menu == VIEW_ITEM_MENU, &d.view) {
|
||||
(true, None) => return Err(format!("contributes.menus: {VIEW_ITEM_MENU} needs `view`")),
|
||||
(true, Some(v)) => {
|
||||
pkg.manifest.needs_api(&format!("contributes.menus: {VIEW_ITEM_MENU}"), 2)?;
|
||||
let Some(view) = declared_view(pkg, v) else {
|
||||
return Err(format!("contributes.menus: view {v:?} is not declared under [[contributes.views]]"));
|
||||
};
|
||||
if view.get("web").is_some() {
|
||||
return Err(format!(
|
||||
"contributes.menus: view {v:?} is a web view (viewItem.context needs a tree or list the plugin renders)"
|
||||
));
|
||||
}
|
||||
format!("{VIEW_ITEM_MENU}/{v}/{}", d.command)
|
||||
}
|
||||
(false, Some(_)) => return Err(format!("contributes.menus: `view` is only for {VIEW_ITEM_MENU}")),
|
||||
(false, None) => format!("{}/{}", d.menu, d.command),
|
||||
};
|
||||
Ok(UiDecl::new(key, d.command.clone(), json(&d)?))
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
@@ -349,6 +400,13 @@ struct ViewDecl {
|
||||
icon: Option<String>,
|
||||
#[serde(default = "right")]
|
||||
location: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
group: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
when: Option<String>,
|
||||
/// Show the selected tree/list item's detail-provider tabs beside it.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
detail: bool,
|
||||
/// A web page of the package (`web/index.html`) instead of content the code renders.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
web: Option<String>,
|
||||
@@ -369,9 +427,30 @@ pub(super) fn view(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
let d: ViewDecl = decode(VIEWS, decl)?;
|
||||
validate_item_id(&d.id, "view id")?;
|
||||
title(VIEWS, &d.title)?;
|
||||
if let Some(group) = &d.group {
|
||||
pkg.manifest.needs_api("contributes.views.group", 3)?;
|
||||
validate_item_id(group, "view group")?;
|
||||
}
|
||||
if let Some(when) = &d.when {
|
||||
pkg.manifest.needs_api("contributes.views.when", 3)?;
|
||||
validate_when(when).map_err(|e| format!("contributes.views: {e}"))?;
|
||||
}
|
||||
|
||||
let files = web_or_code(pkg, d.web.as_deref(), &format!("view {:?}", d.id))?;
|
||||
if !["left", "right", "bottom"].contains(&d.location.as_str()) {
|
||||
return Err(format!("view {:?}: `location` is left, right or bottom", d.id));
|
||||
if !["left", "right", "bottom", SERVICES_LOCATION].contains(&d.location.as_str()) {
|
||||
return Err(format!("view {:?}: `location` is left, right, bottom or services", d.id));
|
||||
}
|
||||
if d.location == SERVICES_LOCATION {
|
||||
pkg.manifest.needs_api(&format!("view {:?}: `location = \"services\"`", d.id), 3)?;
|
||||
if d.web.is_some() {
|
||||
return Err(format!("view {:?}: a services view is rendered by the plugin's code (no `web`)", d.id));
|
||||
}
|
||||
}
|
||||
if d.detail {
|
||||
pkg.manifest.needs_api(&format!("view {:?}: `detail`", d.id), 3)?;
|
||||
if d.web.is_some() {
|
||||
return Err(format!("view {:?}: `detail` needs a tree or list rendered by the plugin (no `web`)", d.id));
|
||||
}
|
||||
}
|
||||
if d.icon.as_ref().is_some_and(|i| i.len() > 64) {
|
||||
return Err(format!("view {:?}: icon names are up to 64 bytes", d.id));
|
||||
@@ -380,7 +459,7 @@ pub(super) fn view(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
out.files = files;
|
||||
if let Some(icon) = d.icon.as_deref().filter(|i| i.ends_with(".svg")) {
|
||||
let path = std::path::PathBuf::from(icon);
|
||||
let svg = super::icons::read_icon(pkg, &path)?;
|
||||
let svg = super::icons::read_icon(pkg, &path, super::icons::MAX_SVG)?;
|
||||
out.assets.push((view_icon_asset(&d.id), svg));
|
||||
out.files.push(path);
|
||||
}
|
||||
@@ -473,7 +552,7 @@ pub(super) fn file_icon(pkg: &Package, decl: toml::Value) -> Result<UiDecl, Stri
|
||||
let mut assets = Vec::new();
|
||||
for (path, dark) in [(Some(&d.icon), false), (d.icon_dark.as_ref(), true)] {
|
||||
let Some(path) = path else { continue };
|
||||
let svg = super::icons::read_icon(pkg, path)?;
|
||||
let svg = super::icons::read_icon(pkg, path, super::icons::MAX_SVG)?;
|
||||
assets.push((file_icon_asset(&d.id, dark), svg));
|
||||
files.push(path.clone());
|
||||
}
|
||||
@@ -484,17 +563,56 @@ pub(super) fn file_icon(pkg: &Package, decl: toml::Value) -> Result<UiDecl, Stri
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct MarkerIconDecl {
|
||||
id: String,
|
||||
icon: PathBuf,
|
||||
#[serde(default)]
|
||||
icon_dark: Option<PathBuf>,
|
||||
}
|
||||
|
||||
pub(super) fn marker_icon(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
pkg.manifest.needs_api("contributes.markerIcons", 3)?;
|
||||
let d: MarkerIconDecl = decode(MARKER_ICONS, decl)?;
|
||||
validate_item_id(&d.id, "marker icon id")?;
|
||||
if d.icon.to_string_lossy().len() > 256 {
|
||||
return Err("marker icon paths are up to 256 bytes".into());
|
||||
}
|
||||
let mut out = UiDecl::new(d.id.clone(), d.id.clone(), serde_json::json!({ "id": d.id, "icon": d.icon }));
|
||||
for (path, variant) in [(Some(&d.icon), "light"), (d.icon_dark.as_ref(), "dark")] {
|
||||
let Some(path) = path else { continue };
|
||||
let svg = super::icons::read_icon(pkg, path, super::icons::MAX_SVG)?;
|
||||
out.assets.push((format!("markerIcon/{}/{variant}", d.id), svg));
|
||||
out.files.push(path.clone());
|
||||
}
|
||||
// A changed SVG must reproject even when its declared path stays the same.
|
||||
let bytes = serde_json::to_vec(&out.assets).map_err(|e| e.to_string())?;
|
||||
out.json["revision"] = Value::String(blake3::hash(&bytes).to_hex().to_string());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct FileTemplateDecl {
|
||||
id: String,
|
||||
name: String,
|
||||
/// Without the dot.
|
||||
#[serde(default)]
|
||||
extension: String,
|
||||
file_name: Option<String>,
|
||||
variables: Option<Vec<FileTemplateVariable>>,
|
||||
/// The new file's content (`$NAME$`, `$END$` and the other template variables work).
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct FileTemplateVariable {
|
||||
name: String,
|
||||
prompt: String,
|
||||
}
|
||||
|
||||
const MAX_TEMPLATE: usize = 256 << 10;
|
||||
|
||||
/// `[[contributes.fileTemplates]]`: an entry of the New menu.
|
||||
@@ -503,8 +621,59 @@ pub(super) fn file_template(pkg: &Package, decl: toml::Value) -> Result<UiDecl,
|
||||
validate_item_id(&d.id, "file template id")?;
|
||||
title(FILE_TEMPLATES, &d.name)?;
|
||||
let what = format!("file template {:?}", d.id);
|
||||
if d.file_name.is_some() || d.variables.is_some() {
|
||||
pkg.manifest.needs_api("contributes.fileTemplates: fileName / variables", 3)?;
|
||||
}
|
||||
if let Some(name) = &d.file_name {
|
||||
let stem = name.split('.').next().unwrap_or("").trim_end().to_ascii_uppercase();
|
||||
if name.is_empty()
|
||||
|| name.len() > 255
|
||||
|| name.trim() != name
|
||||
|| name.ends_with('.')
|
||||
|| matches!(name.as_str(), "." | "..")
|
||||
|| name.chars().any(|c| c.is_control() || "/\\<>:\"|?*".contains(c))
|
||||
|| matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|
||||
|| ((stem.starts_with("COM") || stem.starts_with("LPT"))
|
||||
&& matches!(stem.as_bytes().get(3), Some(b'1'..=b'9'))
|
||||
&& stem.len() == 4)
|
||||
{
|
||||
return Err(format!("{what}: `fileName` must be a safe single file name"));
|
||||
}
|
||||
}
|
||||
let mut names = std::collections::HashSet::new();
|
||||
let variables = d.variables.unwrap_or_default();
|
||||
if variables.len() > 32 {
|
||||
return Err(format!("{what}: at most 32 variables are allowed"));
|
||||
}
|
||||
for variable in &variables {
|
||||
let name = &variable.name;
|
||||
if name.is_empty()
|
||||
|| name.len() > 64
|
||||
|| !name
|
||||
.bytes()
|
||||
.enumerate()
|
||||
.all(|(i, c)| c.is_ascii_alphabetic() || c == b'_' || i > 0 && c.is_ascii_digit())
|
||||
|| matches!(
|
||||
name.as_str(),
|
||||
"NAME"
|
||||
| "FILE_NAME"
|
||||
| "PACKAGE"
|
||||
| "PACKAGE_NAME"
|
||||
| "PROJECT_NAME"
|
||||
| "USER"
|
||||
| "DATE"
|
||||
| "TIME"
|
||||
| "YEAR"
|
||||
| "END"
|
||||
)
|
||||
|| !names.insert(name)
|
||||
{
|
||||
return Err(format!("{what}: invalid, reserved or duplicate variable name {name:?}"));
|
||||
}
|
||||
title("file template variable prompt", &variable.prompt)?;
|
||||
}
|
||||
let ext = d.extension.trim_start_matches('.');
|
||||
if ext.is_empty()
|
||||
if (ext.is_empty() && d.file_name.is_none())
|
||||
|| ext.len() > 32
|
||||
|| !ext.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'))
|
||||
{
|
||||
@@ -514,12 +683,86 @@ pub(super) fn file_template(pkg: &Package, decl: toml::Value) -> Result<UiDecl,
|
||||
if body.len() > MAX_TEMPLATE {
|
||||
return Err(format!("{what}: {} is larger than {} KiB", d.path.display(), MAX_TEMPLATE >> 10));
|
||||
}
|
||||
let json = serde_json::json!({ "id": d.id, "name": d.name, "extension": ext, "body": body });
|
||||
let json = serde_json::json!({ "id": d.id, "name": d.name, "extension": ext, "body": body, "fileName": d.file_name, "variables": variables });
|
||||
let mut out = UiDecl::new(d.id.clone(), d.name.clone(), json);
|
||||
out.files = vec![d.path.clone()];
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CommitCheckDecl {
|
||||
id: String,
|
||||
title: String,
|
||||
}
|
||||
|
||||
/// `[[contributes.commitChecks]]`: a before-commit check run by the plugin's
|
||||
/// `commit-checker` export, listed in Commit Options.
|
||||
pub(super) fn commit_check(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
let d: CommitCheckDecl = decode(COMMIT_CHECKS, decl)?;
|
||||
pkg.manifest.needs_api(&format!("contributes.{COMMIT_CHECKS}"), 3)?;
|
||||
validate_item_id(&d.id, "commit check id")?;
|
||||
title(COMMIT_CHECKS, &d.title)?;
|
||||
if pkg.manifest.wasm.is_none() {
|
||||
return Err(format!("contributes.{COMMIT_CHECKS}: needs `wasm` (the checks run in the plugin's code)"));
|
||||
}
|
||||
if !pkg.manifest.capabilities.all().any(|c| *c == ide_extension::Capability::VcsRead) {
|
||||
return Err(format!("contributes.{COMMIT_CHECKS}: needs the `vcs.read` capability (checks read the commit)"));
|
||||
}
|
||||
Ok(UiDecl::new(d.id.clone(), d.title.clone(), json(&d)?))
|
||||
}
|
||||
|
||||
const MAX_CATALOG_ENTRIES: usize = 20_000;
|
||||
|
||||
pub fn locale_asset(tag: &str) -> String {
|
||||
format!("locale/{tag}")
|
||||
}
|
||||
|
||||
fn locale_tag_ok(tag: &str) -> bool {
|
||||
let mut parts = tag.split('-');
|
||||
let language = parts.next().unwrap_or_default();
|
||||
(2..=3).contains(&language.len())
|
||||
&& language.chars().all(|c| c.is_ascii_alphabetic())
|
||||
&& parts.all(|p| (1..=8).contains(&p.len()) && p.chars().all(|c| c.is_ascii_alphanumeric()))
|
||||
}
|
||||
|
||||
/// `locales/<tag>.json`: English source text → translation, for the plugin's own strings.
|
||||
pub(super) fn locales(pkg: &Package, _decl: toml::Value) -> Result<UiDecl, String> {
|
||||
let dir = Path::new(LOCALES_DIR);
|
||||
let mut names: Vec<String> = std::fs::read_dir(pkg.dir.join(dir))
|
||||
.map_err(|e| format!("{LOCALES_DIR}: {e}"))?
|
||||
.filter_map(|entry| entry.ok()?.file_name().into_string().ok())
|
||||
.filter(|name| name.ends_with(".json"))
|
||||
.collect();
|
||||
names.sort();
|
||||
let mut tags = Vec::new();
|
||||
let mut files = Vec::new();
|
||||
let mut assets = Vec::new();
|
||||
for name in names {
|
||||
let tag = name.trim_end_matches(".json");
|
||||
if !locale_tag_ok(tag) {
|
||||
return Err(format!("{LOCALES_DIR}/{name}: the file name must be a language tag such as fr or zh-CN"));
|
||||
}
|
||||
let file = dir.join(&name);
|
||||
let text = pkg.read_text(&file)?;
|
||||
let catalog: BTreeMap<String, Value> = serde_json::from_str(&text)
|
||||
.map_err(|e| format!("{}: not a JSON object of strings ({e})", file.display()))?;
|
||||
if catalog.len() > MAX_CATALOG_ENTRIES {
|
||||
return Err(format!("{}: more than {MAX_CATALOG_ENTRIES} entries", file.display()));
|
||||
}
|
||||
if let Some((key, _)) = catalog.iter().find(|(_, v)| !v.is_string()) {
|
||||
return Err(format!("{}: the value of {key:?} is not a string", file.display()));
|
||||
}
|
||||
assets.push((locale_asset(tag), text));
|
||||
tags.push(tag.to_owned());
|
||||
files.push(file);
|
||||
}
|
||||
let mut out = UiDecl::new("locales", tags.join(", "), serde_json::json!({ "tags": tags }));
|
||||
out.files = files;
|
||||
out.assets = assets;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -551,4 +794,41 @@ mod tests {
|
||||
assert!(parse_settings_schema(r#"{"properties": {"x": {"type": "string", "default": 3}}}"#).is_err());
|
||||
assert!(parse_settings_schema(r#"{"properties": {"x": {"type": "object"}}}"#).is_err());
|
||||
}
|
||||
|
||||
fn package_with_catalogs(files: &[(&str, &str)]) -> (tempfile::TempDir, Package) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(dir.path().join(LOCALES_DIR)).unwrap();
|
||||
for (name, text) in files {
|
||||
std::fs::write(dir.path().join(LOCALES_DIR).join(name), text).unwrap();
|
||||
}
|
||||
let src = "id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"";
|
||||
let pkg = Package::new(ide_extension::Manifest::parse(src).unwrap(), dir.path().to_path_buf());
|
||||
(dir, pkg)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalogs_become_assets_by_language_tag() {
|
||||
let (_dir, pkg) = package_with_catalogs(&[
|
||||
("fr.json", r#"{"Refresh": "Actualiser"}"#),
|
||||
("zh-CN.json", r#"{"Refresh": "刷新"}"#),
|
||||
("notes.txt", "ignored"),
|
||||
]);
|
||||
let decl = locales(&pkg, toml::Value::Table(Default::default())).unwrap();
|
||||
assert_eq!(decl.json["tags"], serde_json::json!(["fr", "zh-CN"]));
|
||||
assert_eq!(decl.assets.iter().map(|(id, _)| id.as_str()).collect::<Vec<_>>(), ["locale/fr", "locale/zh-CN"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_catalogs_are_refused() {
|
||||
for (name, text) in [
|
||||
("fr.json", "{"),
|
||||
("fr.json", r#"["Refresh"]"#),
|
||||
("fr.json", r#"{"Refresh": 3}"#),
|
||||
("fr.json", r#"{"Refresh": {"a": "b"}}"#),
|
||||
("french!.json", "{}"),
|
||||
] {
|
||||
let (_dir, pkg) = package_with_catalogs(&[(name, text)]);
|
||||
assert!(locales(&pkg, toml::Value::Table(Default::default())).is_err(), "{name}: {text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
//! Declarative views and custom editors as the
|
||||
//! window commands `plugin_view_render` / `plugin_view_event` serve them —
|
||||
//! window commands `plugin_view_render` / `plugin_view_event` (and, for services views,
|
||||
//! `plugin_service_detail` / `plugin_service_log`) serve them —
|
||||
//! the desktop for local projects, `openidea-server` for remote ones.
|
||||
|
||||
use super::{PluginEditor, PluginHost};
|
||||
use super::{PluginEditor, PluginHost, PluginOutputLine};
|
||||
use ide_core::{DocId, IdeError, IdeResult};
|
||||
use ide_plugin::{EditorContext, Invocation, View, ViewEvent, Viewport};
|
||||
use ide_plugin::{EditorContext, Invocation, ServiceTab, View, ViewEvent, Viewport};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The window's project, plus the editor the call is about: the document a
|
||||
@@ -25,7 +26,12 @@ pub fn view_invocation(
|
||||
Some(EditorContext { path: info.path.0, language: info.language.0, selections: Vec::new() })
|
||||
}
|
||||
};
|
||||
Ok(Invocation { client: Some(window.to_owned()), workspace_root: project.as_ref().map(|p| p.root.clone()), editor })
|
||||
Ok(Invocation {
|
||||
client: Some(window.to_owned()),
|
||||
workspace_root: project.as_ref().map(|p| p.root.clone()),
|
||||
editor,
|
||||
..Invocation::default()
|
||||
})
|
||||
}
|
||||
|
||||
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
@@ -62,6 +68,47 @@ pub async fn event(
|
||||
blocking(move || plugins.view_event(&plugin_id, &view, event, invocation)).await
|
||||
}
|
||||
|
||||
/// The Services pane of node `key` of a plugin's services view.
|
||||
pub async fn service_detail(
|
||||
host: &crate::Host,
|
||||
plugins: Arc<PluginHost>,
|
||||
window: &str,
|
||||
plugin_id: String,
|
||||
view: String,
|
||||
key: String,
|
||||
) -> IdeResult<Vec<ServiceTab>> {
|
||||
let invocation = view_invocation(host, window, None, None)?;
|
||||
blocking(move || plugins.service_detail(&plugin_id, &view, &key, invocation)).await
|
||||
}
|
||||
|
||||
/// Runs the program of the log tab `tab` of node `key`'s pane in the window's
|
||||
/// project root, streaming its lines until it exits or request `request` is
|
||||
/// cancelled; returns its exit code.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn service_log(
|
||||
host: &crate::Host,
|
||||
plugins: Arc<PluginHost>,
|
||||
window: &str,
|
||||
plugin_id: String,
|
||||
view: String,
|
||||
key: String,
|
||||
tab: String,
|
||||
on: Vec<String>,
|
||||
request: ide_core::RequestId,
|
||||
on_line: crate::ops::Channel<PluginOutputLine>,
|
||||
) -> IdeResult<Option<i32>> {
|
||||
let invocation = view_invocation(host, window, None, None)?;
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = blocking(move || {
|
||||
plugins.stream_service_log(&plugin_id, &view, &key, &tab, &on, invocation, &cancel, &|line| {
|
||||
let _ = on_line.send(line);
|
||||
})
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -100,6 +100,23 @@ pub struct WebPage {
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// A web frame's API 1.3 PTY request. The frame never supplies an executable path or cwd.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WebPtyCommand {
|
||||
pub program: String,
|
||||
pub args: Vec<String>,
|
||||
pub env: std::collections::BTreeMap<String, String>,
|
||||
pub cols: u16,
|
||||
pub rows: u16,
|
||||
}
|
||||
|
||||
pub(super) struct WebPtySession {
|
||||
id: ide_core::TerminalId,
|
||||
host: std::sync::Weak<crate::Host>,
|
||||
window: String,
|
||||
}
|
||||
|
||||
/// A file of a web view.
|
||||
pub struct WebFile {
|
||||
pub bytes: Vec<u8>,
|
||||
@@ -107,6 +124,138 @@ pub struct WebFile {
|
||||
}
|
||||
|
||||
impl PluginHost {
|
||||
/// Uses the normal PTY backend, without user shell fallback or startup commands.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn spawn_web_pty(
|
||||
&self,
|
||||
host: &std::sync::Arc<crate::Host>,
|
||||
plugin_id: &str,
|
||||
view: &str,
|
||||
window: &str,
|
||||
command: WebPtyCommand,
|
||||
output: crate::ops::Emit<String>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
let _guard = self.lifecycle.lock();
|
||||
let mut sessions = self.web_ptys.lock();
|
||||
if self.shared.client_closed(window) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let options = self.web_pty_options(plugin_id, view, window, command)?;
|
||||
let entries = sessions.entry(plugin_id.to_owned()).or_default();
|
||||
entries.retain(|s| s.host.upgrade().is_some_and(|h| h.terminals.contains(s.id)));
|
||||
if entries.len() >= 8 {
|
||||
return Err(IdeError::invalid("a plugin may own at most 8 PTYs"));
|
||||
}
|
||||
let cwd = options.cwd.0.clone();
|
||||
let info = host.terminals.spawn_program(
|
||||
options,
|
||||
host.owner_window(window).to_owned(),
|
||||
host.window_sink(window),
|
||||
Box::new(move |data| output(data)),
|
||||
)?;
|
||||
if !self
|
||||
.shared
|
||||
.workspace()
|
||||
.is_some_and(|workspace| workspace.project_of(window).as_ref() == Some(&cwd) && workspace.trusted(&cwd))
|
||||
{
|
||||
let _ = host.terminals.kill(info.id);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
entries.push(WebPtySession { id: info.id, host: std::sync::Arc::downgrade(host), window: window.to_owned() });
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
pub(super) fn forget_web_ptys(&self, window: &str) {
|
||||
for sessions in self.web_ptys.lock().values_mut() {
|
||||
sessions.retain(|session| {
|
||||
if session.window != window {
|
||||
return true;
|
||||
}
|
||||
if let Some(host) = session.host.upgrade() {
|
||||
let _ = host.terminals.kill(session.id);
|
||||
}
|
||||
false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn stop_web_ptys(&self, plugin: &str) {
|
||||
if let Some(sessions) = self.web_ptys.lock().remove(plugin) {
|
||||
for session in sessions {
|
||||
if let Some(host) = session.host.upgrade() {
|
||||
let _ = host.terminals.kill(session.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Authorizes a PTY immediately before spawning through the existing terminal backend.
|
||||
pub fn web_pty_options(
|
||||
&self,
|
||||
plugin_id: &str,
|
||||
view: &str,
|
||||
window: &str,
|
||||
command: WebPtyCommand,
|
||||
) -> IdeResult<ide_terminal::TerminalOptions> {
|
||||
self.web_page(plugin_id, view)?;
|
||||
let plugin = self.get(plugin_id)?;
|
||||
plugin.pkg.manifest.needs_api("web view PTYs", 3).map_err(IdeError::invalid)?;
|
||||
let cap = ide_extension::Capability::Process(command.program.clone());
|
||||
if !plugin.meta.lock().granted.contains(&cap) {
|
||||
return Err(IdeError::new(
|
||||
ide_core::error::ErrorKind::PermissionDenied,
|
||||
format!("{cap} capability not granted"),
|
||||
));
|
||||
}
|
||||
if command.program.is_empty()
|
||||
|| command.program.len() > 256
|
||||
|| command.program.trim() != command.program
|
||||
|| command.program.contains(['\0', '\r', '\n'])
|
||||
|| command.args.len() > 256
|
||||
|| command.args.iter().any(|a| a.len() > 4096 || a.contains('\0'))
|
||||
|| !(2..=500).contains(&command.cols)
|
||||
|| !(1..=500).contains(&command.rows)
|
||||
{
|
||||
return Err(IdeError::invalid("invalid PTY program, arguments or dimensions"));
|
||||
}
|
||||
if command.env.len() > 64
|
||||
|| command.env.iter().any(|(k, v)| {
|
||||
k.is_empty()
|
||||
|| k.len() > 256
|
||||
|| k.contains(['=', '\0'])
|
||||
|| v.len() > 4096
|
||||
|| v.contains('\0')
|
||||
|| std::env::vars_os().any(|(inherited, _)| {
|
||||
if cfg!(windows) {
|
||||
inherited.to_string_lossy().eq_ignore_ascii_case(k)
|
||||
} else {
|
||||
inherited == k.as_str()
|
||||
}
|
||||
})
|
||||
})
|
||||
{
|
||||
return Err(IdeError::invalid("PTY environment may only add variables, within the size limits"));
|
||||
}
|
||||
let workspace = self.shared.workspace().ok_or_else(|| IdeError::unavailable("no workspace"))?;
|
||||
let cwd = workspace.project_of(window).ok_or_else(|| IdeError::invalid("no project in this window"))?;
|
||||
if !cwd.is_absolute() || !cwd.is_dir() {
|
||||
return Err(IdeError::invalid("the project directory no longer exists"));
|
||||
}
|
||||
if !workspace.trusted(&cwd) {
|
||||
return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, "project is not trusted"));
|
||||
}
|
||||
let program = self.program_for(plugin_id, &command.program)?;
|
||||
Ok(ide_terminal::TerminalOptions {
|
||||
cwd: cwd.into(),
|
||||
shell: Some(program.to_string_lossy().into_owned()),
|
||||
args: command.args,
|
||||
env: command.env,
|
||||
cols: command.cols,
|
||||
rows: command.rows,
|
||||
shell_integration: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The web roots `plugin` declares (entry directories, package-relative, `/`-terminated).
|
||||
fn web_dirs(&self, plugin: &str) -> Vec<String> {
|
||||
[super::ui_points::VIEWS, super::ui_points::CUSTOM_EDITORS]
|
||||
|
||||
@@ -27,6 +27,7 @@ pub struct Project {
|
||||
pub languages: Arc<LanguageRegistry>,
|
||||
pub settings: Arc<SettingsStore>,
|
||||
pub documents: Arc<Documents>,
|
||||
pub(crate) plugin_diagnostics: Arc<crate::plugins::diagnostics::Diagnostics>,
|
||||
pub history: Arc<LocalHistory>,
|
||||
/// Undo stack of file move / rename refactorings.
|
||||
pub moves: FileMoves,
|
||||
@@ -56,7 +57,7 @@ pub struct Project {
|
||||
pub notebooks: Arc<crate::notebook::NotebookService>,
|
||||
pub(crate) kotlin_bridge: Option<Arc<crate::kotlin_bridge::KotlinBridge>>,
|
||||
pub(crate) phpstan: Option<Arc<crate::phpstan::Phpstan>>,
|
||||
pub(crate) watcher: Watcher,
|
||||
pub(crate) watcher: Arc<Watcher>,
|
||||
/// Watchers of the Project Structure content roots outside the project folder.
|
||||
pub(crate) content_watchers: Mutex<Vec<(PathBuf, Watcher)>>,
|
||||
/// Watchers of folders outside the project that language servers registered file
|
||||
@@ -193,6 +194,7 @@ impl Host {
|
||||
&effective.project_structure,
|
||||
),
|
||||
);
|
||||
ide_lsp::jdtls::configure_project_structure(cfg, root, server_root, &effective.project_structure);
|
||||
let bundles: Vec<PathBuf> = ide_tools::managed_bundle(&data_dir, "java-debug")
|
||||
.into_iter()
|
||||
.chain(ide_sdk::java::usages_bundle(&data_dir))
|
||||
@@ -213,13 +215,19 @@ impl Host {
|
||||
cfg.launch_error = Some(e);
|
||||
None
|
||||
});
|
||||
ide_sdk::apply::configure_java_compiler(cfg, &data_dir, &effective.inspections);
|
||||
let lang_level = ide_sdk::apply::effective_java_language_level(root, server_root, &effective);
|
||||
ide_sdk::apply::configure_java_compiler_with_level(
|
||||
cfg,
|
||||
&data_dir,
|
||||
&effective.inspections,
|
||||
lang_level,
|
||||
);
|
||||
ide_sdk::java::configure_jdtls(
|
||||
cfg,
|
||||
server_root,
|
||||
&data_dir,
|
||||
&jdks,
|
||||
ide_sdk::apply::project_jdk(root, &effective).as_ref(),
|
||||
ide_sdk::apply::module_jdk(root, server_root, &effective).as_ref(),
|
||||
server_jdk.as_ref(),
|
||||
min_java,
|
||||
&bundles,
|
||||
@@ -305,6 +313,12 @@ impl Host {
|
||||
for repo in repos.read().all() {
|
||||
repo.set_execution_allowed(trusted.load(Ordering::Acquire));
|
||||
}
|
||||
// Shared handle: `unwatched_reason` is a live query on the watcher,
|
||||
// filled after `start` returns so the on-change callback can reach it.
|
||||
let watcher_weak = Arc::new(std::sync::OnceLock::<std::sync::Weak<Watcher>>::new());
|
||||
// One-shot latch for the post-start watch-limit warning (#1915): the
|
||||
// synchronous startup walk and a later batch can both observe it.
|
||||
let notify_watch_exhausted = Arc::new(AtomicBool::new(false));
|
||||
let watcher = {
|
||||
let kotlin_bridge = kotlin_bridge.clone();
|
||||
let phpstan = phpstan.clone();
|
||||
@@ -322,6 +336,8 @@ impl Host {
|
||||
let lsp = lsp.clone();
|
||||
let trusted = trusted.clone();
|
||||
let build_cache = build_cache.clone();
|
||||
let notify_watch_exhausted = notify_watch_exhausted.clone();
|
||||
let watcher_weak = watcher_weak.clone();
|
||||
Watcher::start(
|
||||
&root.clone(),
|
||||
excludes.clone(),
|
||||
@@ -339,6 +355,9 @@ impl Host {
|
||||
}
|
||||
// Atomic saves by external tools surface as `created`.
|
||||
documents.on_disk_changed(&[&changed[..], &ignored].concat());
|
||||
if let Some(plugins) = crate::plugins::editor_plugin_host() {
|
||||
plugins.invalidate_endpoints(&root, &[changed.clone(), batch.removed.clone()].concat());
|
||||
}
|
||||
// A framework's root marker (`angular.json`) created or deleted: its
|
||||
// templates gain or lose their mode. Markers in `node_modules` only
|
||||
// count here when the folder isn't excluded (it is by default).
|
||||
@@ -408,9 +427,26 @@ impl Host {
|
||||
if git_dirs || vcs_moved {
|
||||
sink.emit(IdeEvent::VcsChanged { root: root.clone().into() });
|
||||
}
|
||||
// A watch limit hit after startup (per-directory mode, Linux):
|
||||
// folders past the limit never sync — surface it once, like
|
||||
// the polling fallback below (#1915). The check itself is
|
||||
// deferred to here, on a batch that already had events.
|
||||
if !notify_watch_exhausted.load(Ordering::Relaxed)
|
||||
&& let Some(msg) =
|
||||
watcher_weak.get().and_then(std::sync::Weak::upgrade).and_then(|w| w.unwatched_reason())
|
||||
{
|
||||
sink.emit(IdeEvent::Notify {
|
||||
level: ide_core::event::NotifyLevel::Warning,
|
||||
title: "External file changes sync may be slow".into(),
|
||||
body: Some(msg),
|
||||
});
|
||||
notify_watch_exhausted.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}),
|
||||
)?
|
||||
};
|
||||
let watcher = Arc::new(watcher);
|
||||
let _ = watcher_weak.set(Arc::downgrade(&watcher));
|
||||
if let Some(reason) = watcher.polling() {
|
||||
sink.emit(IdeEvent::Notify {
|
||||
level: ide_core::event::NotifyLevel::Warning,
|
||||
@@ -418,6 +454,17 @@ impl Host {
|
||||
body: Some(reason.into()),
|
||||
});
|
||||
}
|
||||
// A watch can also be refused part-way through the synchronous startup
|
||||
// walk (large tree, SYNC_WATCH_BUDGET) — after start() returns, before
|
||||
// any batch. Emit the same warning so the limit isn't silent there either.
|
||||
if let Some(reason) = watcher.unwatched_reason() {
|
||||
sink.emit(IdeEvent::Notify {
|
||||
level: ide_core::event::NotifyLevel::Warning,
|
||||
title: "External file changes sync may be slow".into(),
|
||||
body: Some(reason),
|
||||
});
|
||||
notify_watch_exhausted.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
// Scratch files live outside the project; watch them too so the
|
||||
// Project view and open editors follow changes made there.
|
||||
@@ -473,7 +520,11 @@ impl Host {
|
||||
sink.clone(),
|
||||
);
|
||||
ide_agent::registry::maintain(crate::ops::agent::registry_paths(self));
|
||||
let plugin_diagnostics =
|
||||
crate::plugins::diagnostics::Diagnostics::new(sink.clone(), self.runtime.clone(), &documents, &root);
|
||||
documents.add_observer(plugin_diagnostics.clone());
|
||||
let project = Arc::new(Project {
|
||||
plugin_diagnostics,
|
||||
trusted,
|
||||
root,
|
||||
sink,
|
||||
@@ -619,7 +670,11 @@ impl Host {
|
||||
self.local_data_dir.join("notebook-runtime").join(uuid::Uuid::new_v4().to_string()),
|
||||
sink.clone(),
|
||||
);
|
||||
let plugin_diagnostics =
|
||||
crate::plugins::diagnostics::Diagnostics::new(sink.clone(), self.runtime.clone(), &documents, &dir);
|
||||
documents.add_observer(plugin_diagnostics.clone());
|
||||
let project = Arc::new(Project {
|
||||
plugin_diagnostics,
|
||||
trusted: Arc::new(AtomicBool::new(false)),
|
||||
sink,
|
||||
languages,
|
||||
@@ -644,7 +699,7 @@ impl Host {
|
||||
notebooks,
|
||||
kotlin_bridge: None,
|
||||
phpstan: None,
|
||||
watcher,
|
||||
watcher: Arc::new(watcher),
|
||||
content_watchers: Mutex::new(Vec::new()),
|
||||
lsp_watchers: Mutex::new(Vec::new()),
|
||||
_scratch_watcher: None,
|
||||
|
||||
@@ -16,8 +16,14 @@ pub struct TrustDecisions {
|
||||
pub struct TrustStore {
|
||||
file: PathBuf,
|
||||
state: Mutex<IdeResult<TrustDecisions>>,
|
||||
/// Folders trusted for this process only, by the client that started it ([`TRUSTED_ROOT_ENV`]).
|
||||
inherited: Mutex<Vec<PathBuf>>,
|
||||
}
|
||||
|
||||
/// Set by the desktop when it starts the server in a dev container of a folder the user trusts
|
||||
/// there: the project folder in the container, trusted without asking again. Never persisted.
|
||||
pub const TRUSTED_ROOT_ENV: &str = "OPENIDEA_TRUSTED_ROOT";
|
||||
|
||||
impl TrustStore {
|
||||
pub fn load(config: &Path, data: &Path) -> Self {
|
||||
let file = data.join("project-trust.json");
|
||||
@@ -34,7 +40,7 @@ impl TrustStore {
|
||||
}
|
||||
Err(e) => Err(e.into()),
|
||||
};
|
||||
Self { file, state: Mutex::new(state) }
|
||||
Self { file, state: Mutex::new(state), inherited: Mutex::default() }
|
||||
}
|
||||
|
||||
pub fn decisions(&self) -> IdeResult<TrustDecisions> {
|
||||
@@ -45,7 +51,19 @@ impl TrustStore {
|
||||
let root = dunce::canonicalize(path)?;
|
||||
let decisions = self.decisions()?;
|
||||
Ok(!decisions.restricted.contains(&root)
|
||||
&& (decisions.projects.contains(&root) || decisions.locations.iter().any(|p| root.starts_with(p))))
|
||||
&& (decisions.projects.contains(&root)
|
||||
|| decisions.locations.iter().any(|p| root.starts_with(p))
|
||||
|| self.inherited.lock().contains(&root)))
|
||||
}
|
||||
|
||||
/// Trusts `path` for this process without recording a decision (see [`TRUSTED_ROOT_ENV`]).
|
||||
pub fn inherit(&self, path: &Path) -> IdeResult<()> {
|
||||
let root = dunce::canonicalize(path)?;
|
||||
let mut inherited = self.inherited.lock();
|
||||
if !inherited.contains(&root) {
|
||||
inherited.push(root);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn decide(&self, path: &Path, trusted: bool, folder: bool) -> IdeResult<()> {
|
||||
@@ -74,6 +92,21 @@ impl TrustStore {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn add_location(&self, path: &Path) -> IdeResult<()> {
|
||||
let root = dunce::canonicalize(path)?;
|
||||
if !root.is_dir() {
|
||||
return Err(IdeError::invalid("trusted location must be an existing directory"));
|
||||
}
|
||||
let mut state = self.state.lock();
|
||||
let mut next = state.clone()?;
|
||||
if !next.locations.contains(&root) {
|
||||
next.locations.push(root);
|
||||
persist(&self.file, &next)?;
|
||||
*state = Ok(next);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_location(&self, path: &Path) -> IdeResult<()> {
|
||||
let mut state = self.state.lock();
|
||||
let mut next = state.clone()?;
|
||||
@@ -269,6 +302,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
| "agent_commands"
|
||||
| "agent_unqueue"
|
||||
| "agent_cancel"
|
||||
| "agent_stop_background"
|
||||
| "agent_archive"
|
||||
| "agent_unarchive"
|
||||
| "agent_registry_list"
|
||||
@@ -284,6 +318,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
| "plugin_set_theme_frame"
|
||||
| "plugin_catalog"
|
||||
| "plugin_assets"
|
||||
| "plugin_set_ui_locale"
|
||||
| "plugin_market"
|
||||
| "plugin_market_url"
|
||||
| "plugin_set_market_url"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Versioned installs with automatic rollback, signed packages from
|
||||
//! a static marketplace index, and revocation.
|
||||
|
||||
use ide_extension::package::{self, Index, IndexEntry, KeyEntry, Publisher, PublisherKey, Revocation};
|
||||
use ide_extension::package::{self, Index, IndexEntry, KeyEntry, PluginIcon, Publisher, PublisherKey, Revocation};
|
||||
use ide_host::plugins::*;
|
||||
use ide_plugin::{Invocation, Limits};
|
||||
use parking_lot::Mutex;
|
||||
@@ -58,7 +58,7 @@ fn fixture() -> Fixture {
|
||||
}
|
||||
|
||||
fn inv() -> Invocation {
|
||||
Invocation { client: Some("main".into()), workspace_root: None, editor: None }
|
||||
Invocation { client: Some("main".into()), workspace_root: None, editor: None, selected_paths: Vec::new() }
|
||||
}
|
||||
|
||||
fn misbehave() -> PathBuf {
|
||||
@@ -169,6 +169,7 @@ fn signed(
|
||||
capabilities: vec![],
|
||||
engine: "^1.0".into(),
|
||||
categories: vec!["tools".into()],
|
||||
icon: None,
|
||||
};
|
||||
(out, entry)
|
||||
}
|
||||
@@ -509,3 +510,25 @@ fn official_plugins_need_the_key_this_ide_was_built_with() {
|
||||
let dir = f.host.download_market_plugin("openidea.hello").unwrap();
|
||||
assert_eq!(f.host.preview_install(&dir).unwrap().publisher.as_deref(), Some(OFFICIAL_PUBLISHER));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marketplace_icons_are_sanitised_or_dropped() {
|
||||
let f = fixture();
|
||||
let market = f.work.join("market");
|
||||
std::fs::create_dir_all(&market).unwrap();
|
||||
let key = PublisherKey::from_seed([3; 32]);
|
||||
let (_, entry) = signed_hello(&market, "1.0.0", &key, &f.host);
|
||||
let icon = |light: &str| Some(PluginIcon { light: light.into(), dark: None });
|
||||
let good =
|
||||
IndexEntry { icon: icon(r#"<svg viewBox="0 0 16 16"><rect width="16" height="16"/></svg>"#), ..entry.clone() };
|
||||
let hostile = IndexEntry { id: "acme.hostile".into(), icon: icon(r#"<svg onload="x()"><rect/></svg>"#), ..entry };
|
||||
let padded = format!("<svg viewBox=\"0 0 16 16\"><!--{}--><rect/></svg>", " ".repeat(20 << 10));
|
||||
let padded = IndexEntry { id: "acme.padded".into(), icon: icon(&padded), ..hostile.clone() };
|
||||
f.host.set_market_url(Some(write_index(&market, &key, vec![good, hostile, padded], vec![], false)));
|
||||
|
||||
let listed = f.host.refresh_market().unwrap();
|
||||
let by_id = |id: &str| listed.iter().find(|p| p.entry.id == id).unwrap_or_else(|| panic!("{id} not listed"));
|
||||
assert!(by_id("acme.hello").entry.icon.as_ref().unwrap().light.contains("<rect"));
|
||||
assert!(by_id("acme.hostile").entry.icon.is_none(), "an unsafe icon is dropped, the entry stays");
|
||||
assert!(by_id("acme.padded").entry.icon.is_none(), "an icon over 16 KiB is dropped before it is sanitised");
|
||||
}
|
||||
@@ -117,6 +117,41 @@ async fn docker_targets_run_through_the_docker_cli() {
|
||||
assert!(out.contains("DATA=/workspaces/proj/data"), "{out}");
|
||||
assert!(!args.iter().any(|a| a.contains("/workspaces/proj/data")), "values stay out of the command line");
|
||||
|
||||
// Debug: the program starts under the bootstrap, which waits for the debugger on a
|
||||
// port published on the loopback interface, with the IDE's debugpy mounted.
|
||||
let lib = host.data_dir.join("tools/debugpy/lib");
|
||||
std::fs::create_dir_all(lib.join("debugpy")).unwrap();
|
||||
std::fs::write(lib.join("debugpy/__init__.py"), "").unwrap();
|
||||
let mut debug = config("py", &root);
|
||||
debug.debug_adapter = Some("debugpy".into());
|
||||
debug.extras.params.insert("containerDebug".into(), "true".into());
|
||||
let out = output_of(&host, debug.clone()).await;
|
||||
let args: Vec<&str> = out.lines().filter_map(|l| l.strip_prefix("arg:")).collect();
|
||||
let publish = args[args.iter().position(|a| *a == "--publish").unwrap() + 1];
|
||||
let port = publish.strip_prefix("127.0.0.1:").and_then(|p| p.split_once(':')).unwrap();
|
||||
assert_eq!(port.0, port.1, "{out}");
|
||||
let bootstrap = host.data_dir.join("container-debug");
|
||||
assert!(args.contains(&format!("{}:/opt/openidea/debug:ro", bootstrap.display()).as_str()), "{out}");
|
||||
assert!(args.contains(&format!("{}:/opt/openidea/debugpy-lib:ro", lib.display()).as_str()), "{out}");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(bootstrap.join("openidea_debug.py")).unwrap(),
|
||||
ide_remote::docker::DEBUG_BOOTSTRAP
|
||||
);
|
||||
assert!(
|
||||
args.ends_with(&[
|
||||
"python:3.12",
|
||||
"python3",
|
||||
"/opt/openidea/debug/openidea_debug.py",
|
||||
port.0,
|
||||
"/workspaces/proj",
|
||||
"/workspaces/proj/main.py"
|
||||
]),
|
||||
"{out}"
|
||||
);
|
||||
debug.debug_adapter = Some("delve".into());
|
||||
let err = ops::run::start(&host, "main", debug, Arc::new(|_| {})).await.unwrap_err();
|
||||
assert!(err.message.contains("only Python"), "{}", err.message);
|
||||
|
||||
let err = ops::run::start(&host, "main", config("far", &root), Arc::new(|_| {})).await.unwrap_err();
|
||||
assert!(err.message.contains("another machine"), "{}", err.message);
|
||||
}
|
||||
@@ -157,3 +157,150 @@ async fn runs_in_docker_and_compose_containers() {
|
||||
assert_eq!(containers("label=openidea.run=sleep"), "", "{out}");
|
||||
Command::new("docker").args(["compose", "down"]).current_dir(&root).status().unwrap();
|
||||
}
|
||||
|
||||
/// A debug adapter connection: just enough DAP to drive debugpy.
|
||||
struct Dap {
|
||||
reader: std::io::BufReader<std::net::TcpStream>,
|
||||
writer: std::net::TcpStream,
|
||||
seq: i64,
|
||||
}
|
||||
|
||||
impl Dap {
|
||||
fn connect(address: &str) -> Self {
|
||||
let stream = std::net::TcpStream::connect(address).unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(60))).unwrap();
|
||||
Self { reader: std::io::BufReader::new(stream.try_clone().unwrap()), writer: stream, seq: 0 }
|
||||
}
|
||||
|
||||
fn send(&mut self, command: &str, arguments: serde_json::Value) {
|
||||
use std::io::Write;
|
||||
self.seq += 1;
|
||||
let body = serde_json::json!({"seq": self.seq, "type": "request", "command": command, "arguments": arguments})
|
||||
.to_string();
|
||||
write!(self.writer, "Content-Length: {}\r\n\r\n{body}", body.len()).unwrap();
|
||||
}
|
||||
|
||||
fn read(&mut self) -> serde_json::Value {
|
||||
use std::io::{BufRead, Read};
|
||||
let mut length = 0;
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
assert!(self.reader.read_line(&mut line).unwrap() > 0, "the adapter closed the connection");
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
break;
|
||||
}
|
||||
if let Some(n) = line.strip_prefix("Content-Length:") {
|
||||
length = n.trim().parse().unwrap();
|
||||
}
|
||||
}
|
||||
let mut body = vec![0; length];
|
||||
self.reader.read_exact(&mut body).unwrap();
|
||||
serde_json::from_slice(&body).unwrap()
|
||||
}
|
||||
|
||||
/// Reads until a message of `kind` (`"response"` / `"event"`) named `name`.
|
||||
fn wait(&mut self, kind: &str, name: &str) -> serde_json::Value {
|
||||
loop {
|
||||
let m = self.read();
|
||||
let key = if kind == "event" { "event" } else { "command" };
|
||||
if m["type"] == kind && m[key] == name {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "requires a Docker daemon, OPENIDEA_DOCKER_TEST_DIR, and pip to fetch debugpy"]
|
||||
async fn debugs_python_in_a_container() {
|
||||
let root = PathBuf::from(std::env::var("OPENIDEA_DOCKER_TEST_DIR").expect("OPENIDEA_DOCKER_TEST_DIR"));
|
||||
// A project of its own: the other test may run at the same time.
|
||||
let root = dunce::canonicalize(root).unwrap().join("debug");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let name = "debug";
|
||||
let main = root.join("main.py");
|
||||
std::fs::write(&main, "import os\nvalue = os.environ['GREETING']\nprint('value=' + value)\n").unwrap();
|
||||
// The IDE's state must be where the daemon can mount it (the bootstrap, the debugpy copy).
|
||||
let state = root.join(".state");
|
||||
let host = host(&state);
|
||||
// The IDE's copy, installed like the Tools page does (`ide_tools` `PipTarget`): the image has no debugpy.
|
||||
let lib = host.data_dir.join("tools/debugpy/lib");
|
||||
let pip = Command::new("python3")
|
||||
.args(["-m", "pip", "install", "--quiet", "--no-deps", "--target"])
|
||||
.arg(&lib)
|
||||
.args(["--only-binary=:all:", "--platform", "any", "--implementation", "py", "debugpy"])
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(pip.success());
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
let targets =
|
||||
serde_json::json!([{ "kind": "docker", "id": "py", "name": "Python", "image": "python:3.12-alpine" }]);
|
||||
ops::project::set_settings(
|
||||
&host,
|
||||
"main",
|
||||
ide_workspace::settings::SettingsScope::Project,
|
||||
"runTargets",
|
||||
&targets.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut debug = config("debug-main", "py", &root, &[&main.to_string_lossy()]);
|
||||
debug.debug_adapter = Some("debugpy".into());
|
||||
debug.extras.params.insert("containerDebug".into(), "true".into());
|
||||
let (_, out) = start(&host, debug).await;
|
||||
let mut ready = None;
|
||||
for _ in 0..1200 {
|
||||
ready = out
|
||||
.lock()
|
||||
.lines()
|
||||
.find_map(|l| l.trim().strip_prefix(ide_remote::docker::DEBUG_READY).map(|rest| rest.to_owned()));
|
||||
if ready.is_some() || out.lock().contains("Process finished") {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
let ready = ready.unwrap_or_else(|| panic!("{}", out.lock()));
|
||||
let (port, folder) = ready.split_once(", project folder ").unwrap();
|
||||
assert_eq!(folder, format!("/workspaces/{name}"));
|
||||
let address = format!("{}:{port}", std::env::var("OPENIDEA_DOCKER_TEST_HOST").unwrap_or("127.0.0.1".into()));
|
||||
|
||||
// Attach with the project mapped, stop at a breakpoint set on the local file, continue.
|
||||
let local = main.to_string_lossy().into_owned();
|
||||
let root_str = root.to_string_lossy().into_owned();
|
||||
let folder = folder.to_owned();
|
||||
let stopped_at = tokio::task::spawn_blocking(move || {
|
||||
let mut dap = Dap::connect(&address);
|
||||
dap.send(
|
||||
"initialize",
|
||||
serde_json::json!({"adapterID": "debugpy", "pathFormat": "path", "linesStartAt1": true}),
|
||||
);
|
||||
dap.wait("response", "initialize");
|
||||
dap.send(
|
||||
"attach",
|
||||
serde_json::json!({"justMyCode": true, "pathMappings": [{"localRoot": root_str, "remoteRoot": folder}]}),
|
||||
);
|
||||
dap.wait("event", "initialized");
|
||||
dap.send("setBreakpoints", serde_json::json!({"source": {"path": local}, "breakpoints": [{"line": 3}]}));
|
||||
let set = dap.wait("response", "setBreakpoints");
|
||||
assert_eq!(set["body"]["breakpoints"][0]["verified"], true, "{set}");
|
||||
dap.send("configurationDone", serde_json::json!({}));
|
||||
let stopped = dap.wait("event", "stopped");
|
||||
let thread = stopped["body"]["threadId"].clone();
|
||||
dap.send("stackTrace", serde_json::json!({"threadId": thread}));
|
||||
let frame = dap.wait("response", "stackTrace")["body"]["stackFrames"][0].clone();
|
||||
dap.send("continue", serde_json::json!({"threadId": thread}));
|
||||
dap.wait("response", "continue");
|
||||
(stopped["body"]["reason"].clone(), frame["source"]["path"].clone(), frame["line"].clone())
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(stopped_at.0, "breakpoint");
|
||||
assert_eq!(stopped_at.1, main.to_string_lossy().as_ref(), "the container's path maps back to the project");
|
||||
assert_eq!(stopped_at.2, 3);
|
||||
let out = finished(&out, 60).await;
|
||||
assert!(out.contains("value=hello") && out.contains("exit code 0"), "{out}");
|
||||
assert_eq!(containers("label=openidea.run=debug-main"), "", "removed when the run ends");
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
@@ -303,7 +303,18 @@ impl Smoke {
|
||||
let (doc, pos) = self.locate(of).await;
|
||||
let want: BTreeSet<String> = files.iter().map(|f| f.to_string()).collect();
|
||||
self.retry("find usages", self.warm_up, || async {
|
||||
let found = ops::lsp::lsp_references(&self.host, WINDOW, RequestId(1), doc, pos, true, true).await;
|
||||
let found = ops::lsp::lsp_references(
|
||||
&self.host,
|
||||
WINDOW,
|
||||
RequestId(1),
|
||||
doc,
|
||||
pos,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
ops::Channel::new(|_| {}),
|
||||
)
|
||||
.await;
|
||||
match &found {
|
||||
Ok(r) if want.is_subset(&self.files(r.locations.iter().map(|l| l.path.clone()))) => Ok(()),
|
||||
_ => Err(found.map(|r| self.files(r.locations.into_iter().map(|l| l.path)))),
|
||||
|
||||
@@ -160,7 +160,7 @@ async fn light_notebooks_open_without_interpreter_detection_or_execution() {
|
||||
assert!(ops::notebook::save(&host, "main", notebook.id.clone()).await.is_ok());
|
||||
let error = ops::sdk::sdk_detect(&host, "main", ide_sdk::SdkKind::Python).await.unwrap_err();
|
||||
assert!(error.message.contains("Restricted Mode"));
|
||||
assert!(ops::sdk::sdk_python_effective(&host, "main").is_err());
|
||||
assert!(ops::sdk::sdk_python_effective(&host, "main", None).is_err());
|
||||
assert!(ops::sdk::sdk_locate_tools(&host, "main", vec!["prettier".into()], Some(root)).await.is_err());
|
||||
let error = ops::notebook::restart(&host, "main", notebook.id.clone()).await.unwrap_err();
|
||||
assert!(error.message.contains("Restricted Mode"));
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
//! The `commit` interface and the `commit-checker` export, through the
|
||||
//! `test.commit` fixture and a scripted window answering `CommitRequested`.
|
||||
|
||||
use ide_core::ipc_path::to_ipc;
|
||||
use ide_host::plugins::*;
|
||||
use ide_plugin::{HostError, Invocation, Limits};
|
||||
use parking_lot::Mutex;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
fn fixture_dir() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/commit")
|
||||
}
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) {
|
||||
let out = Command::new("git")
|
||||
.current_dir(dir)
|
||||
.args(["-c", "init.defaultBranch=main", "-c", "user.name=T", "-c", "[email protected]"])
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
struct Workspace {
|
||||
root: PathBuf,
|
||||
trusted: AtomicBool,
|
||||
}
|
||||
|
||||
impl PluginWorkspace for Workspace {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
vec![self.root.clone()]
|
||||
}
|
||||
fn buffer_text(&self, _: &Path) -> Option<String> {
|
||||
None
|
||||
}
|
||||
fn document(&self, _: &Path) -> Option<(u64, String)> {
|
||||
None
|
||||
}
|
||||
fn apply_edits(&self, _: &Path, _: u64, _: &[ide_core::TextEdit]) -> Result<u64, HostError> {
|
||||
Err(HostError::NotFound("not open".into()))
|
||||
}
|
||||
fn trusted(&self, _: &Path) -> bool {
|
||||
self.trusted.load(Ordering::Relaxed)
|
||||
}
|
||||
fn project_of(&self, _: &str) -> Option<PathBuf> {
|
||||
Some(self.root.clone())
|
||||
}
|
||||
fn publish_diagnostics(&self, _: &str, _: &Path, _: Vec<ide_core::Diagnostic>) -> Result<(), HostError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The window's Commit view: its draft, and whether the user types between
|
||||
/// the plugin reading it and writing the message.
|
||||
#[derive(Default)]
|
||||
struct Window {
|
||||
revision: u64,
|
||||
message: String,
|
||||
selection: Option<CommitSelection>,
|
||||
type_after_reading: bool,
|
||||
requests: Vec<CommitRequest>,
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
host: Arc<PluginHost>,
|
||||
window: Arc<Mutex<Window>>,
|
||||
workspace: Arc<Workspace>,
|
||||
project: PathBuf,
|
||||
_tmp: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let project = tmp.path().join("project");
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
git(&project, &["init", "-q"]);
|
||||
std::fs::write(project.join("a.txt"), "one\ntwo\nthree\n").unwrap();
|
||||
git(&project, &["add", "."]);
|
||||
git(&project, &["commit", "-qm", "base"]);
|
||||
std::fs::write(project.join("a.txt"), "one\nDO NOT COMMIT\nthree\n").unwrap();
|
||||
|
||||
let window = Arc::new(Mutex::new(Window { revision: 7, ..Window::default() }));
|
||||
let host_slot: Arc<Mutex<Option<std::sync::Weak<PluginHost>>>> = Arc::default();
|
||||
let (w, slot) = (window.clone(), host_slot.clone());
|
||||
// Answers on another thread, as the UI does through `plugin_answer_commit`.
|
||||
let sink = Arc::new(move |_: Option<&str>, e: PluginEvent| {
|
||||
let PluginEvent::CommitRequested { request_id, request, .. } = e else { return };
|
||||
let (w, slot) = (w.clone(), slot.clone());
|
||||
std::thread::spawn(move || {
|
||||
let answer = {
|
||||
let mut w = w.lock();
|
||||
w.requests.push(request.clone());
|
||||
match request {
|
||||
CommitRequest::Selection => {
|
||||
let selection = w.selection.clone();
|
||||
if w.type_after_reading {
|
||||
w.revision += 1;
|
||||
}
|
||||
match selection {
|
||||
Some(s) => CommitAnswer::Selection { selection: s },
|
||||
None => CommitAnswer::NoRepository,
|
||||
}
|
||||
}
|
||||
CommitRequest::SetMessage { revision, message } if revision == w.revision => {
|
||||
w.message = message;
|
||||
w.revision += 1;
|
||||
CommitAnswer::Done
|
||||
}
|
||||
CommitRequest::SetMessage { .. } => CommitAnswer::Stale,
|
||||
}
|
||||
};
|
||||
let host = slot.lock().as_ref().and_then(std::sync::Weak::upgrade);
|
||||
assert!(host.unwrap().answer_commit(&request_id, answer));
|
||||
});
|
||||
});
|
||||
let host = Arc::new(PluginHost::new(tmp.path().join("plugins"), sink, Limits::default()).unwrap());
|
||||
*host_slot.lock() = Some(Arc::downgrade(&host));
|
||||
let workspace = Arc::new(Workspace { root: project.clone(), trusted: AtomicBool::new(true) });
|
||||
host.set_workspace(Some(workspace.clone()));
|
||||
host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap();
|
||||
Self { host, window, workspace, project, _tmp: tmp }
|
||||
}
|
||||
|
||||
fn inv(&self) -> Invocation {
|
||||
Invocation { client: Some("main".into()), workspace_root: Some(self.project.clone()), ..Invocation::default() }
|
||||
}
|
||||
|
||||
/// `a.txt` included whole, with `message`.
|
||||
fn selection(&self, message: &str) -> CommitSelection {
|
||||
let revision = self.window.lock().revision;
|
||||
CommitSelection {
|
||||
revision,
|
||||
message: message.into(),
|
||||
amend: false,
|
||||
repositories: vec![CommitSelectionRepo {
|
||||
root: self.project.clone().into(),
|
||||
options: ide_vcs::CommitOptions {
|
||||
stage: vec![self.project.join("a.txt").into()],
|
||||
run_hooks: true,
|
||||
..Default::default()
|
||||
},
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn markers(&self, message: &str) -> Vec<PluginCommitCheckResult> {
|
||||
let check = PluginCommitCheckRef { plugin_id: "test.commit".into(), check: "markers".into() };
|
||||
let cancel = ide_core::CancellationToken::new();
|
||||
self.host.commit_checks(self.inv(), self.selection(message), vec![check], &cancel).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_reads_the_pending_commit_and_writes_its_message() {
|
||||
let f = Fixture::new();
|
||||
let selection = f.selection("");
|
||||
f.window.lock().selection = Some(selection);
|
||||
let out = f.host.run_command("test.commit", "describe", None, f.inv()).unwrap();
|
||||
assert_eq!(out.as_deref(), Some("chore: modified a.txt"));
|
||||
let w = f.window.lock();
|
||||
assert_eq!(w.message, "chore: modified a.txt");
|
||||
assert_eq!(w.revision, 8);
|
||||
// Reading the draft left the index alone: nothing is staged.
|
||||
let staged = Command::new("git").current_dir(&f.project).args(["diff", "--cached", "--name-only"]).output();
|
||||
assert!(staged.unwrap().stdout.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_meanwhile_makes_the_write_stale() {
|
||||
let f = Fixture::new();
|
||||
let selection = f.selection("");
|
||||
{
|
||||
let mut w = f.window.lock();
|
||||
w.selection = Some(selection);
|
||||
w.type_after_reading = true;
|
||||
}
|
||||
let err = f.host.run_command("test.commit", "describe", None, f.inv()).unwrap_err();
|
||||
assert!(err.message.contains("stale") || err.message.contains("changed"), "{}", err.message);
|
||||
assert_eq!(f.window.lock().message, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_repository_and_restricted_mode() {
|
||||
let f = Fixture::new();
|
||||
let err = f.host.run_command("test.commit", "describe", None, f.inv()).unwrap_err();
|
||||
assert!(err.message.contains("no repository"), "{}", err.message);
|
||||
|
||||
f.workspace.trusted.store(false, Ordering::Relaxed);
|
||||
f.window.lock().requests.clear();
|
||||
let err = f.host.run_command("test.commit", "describe", None, f.inv()).unwrap_err();
|
||||
assert!(err.message.contains("Restricted Mode"), "{}", err.message);
|
||||
assert!(f.window.lock().requests.is_empty(), "the window is not asked");
|
||||
|
||||
// Outside a window's command there is no Commit view to ask.
|
||||
let headless = Invocation { client: None, ..f.inv() };
|
||||
let err = f.host.run_command("test.commit", "describe", None, headless).unwrap_err();
|
||||
assert!(err.message.contains("from a command"), "{}", err.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checks_report_the_message_and_markers_in_the_included_changes() {
|
||||
let f = Fixture::new();
|
||||
let results = f.markers("wip");
|
||||
assert_eq!(results.len(), 1);
|
||||
let r = &results[0];
|
||||
assert_eq!((r.title.as_str(), r.error.as_deref()), ("Commit Markers", None));
|
||||
let found: Vec<_> =
|
||||
r.problems.iter().map(|p| (p.message.as_str(), p.path.clone(), p.range.map(|r| r.start.line))).collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
[
|
||||
("The message does not start with `type: `.", None, None),
|
||||
("Remove the DO NOT COMMIT marker.", Some(to_ipc(&f.project.join("a.txt"))), Some(1)),
|
||||
]
|
||||
);
|
||||
assert_eq!(f.markers("fix: drop marker")[0].problems.len(), 1);
|
||||
|
||||
// Unknown checks are not run, nor those of a plugin that lost `vcs.read`.
|
||||
let other = PluginCommitCheckRef { plugin_id: "test.commit".into(), check: "other".into() };
|
||||
let cancel = ide_core::CancellationToken::new();
|
||||
assert!(f.host.commit_checks(f.inv(), f.selection("x"), vec![other], &cancel).unwrap().is_empty());
|
||||
f.host.set_capability("test.commit", "vcs.read", false).unwrap();
|
||||
assert!(f.markers("wip").iter().all(|r| r.problems.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_commit_points_need_plugin_api_1_3() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host =
|
||||
PluginHost::new(tmp.path().join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap();
|
||||
// The manifest surgery below matches on `\n`; normalize so a CRLF checkout (Windows) behaves the same.
|
||||
let manifest = std::fs::read_to_string(fixture_dir().join("plugin.toml")).unwrap().replace("\r\n", "\n");
|
||||
for (what, manifest) in [
|
||||
(
|
||||
"commit.message",
|
||||
manifest.replace("[[contributes.commitChecks]]\nid = \"markers\"\ntitle = \"Commit Markers\"\n", ""),
|
||||
),
|
||||
(
|
||||
"commitChecks",
|
||||
manifest.replace("[[contributes.menus]]\nmenu = \"commit.message\"\ncommand = \"describe\"\n", ""),
|
||||
),
|
||||
] {
|
||||
let pkg = tmp.path().join(what);
|
||||
std::fs::create_dir_all(pkg.join("dist")).unwrap();
|
||||
std::fs::copy(fixture_dir().join("dist/plugin.wasm"), pkg.join("dist/plugin.wasm")).unwrap();
|
||||
std::fs::write(pkg.join("plugin.toml"), manifest.replace("\"^1.3\"", "\"^1.2\"")).unwrap();
|
||||
let err = host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
|
||||
assert!(err.message.contains("new in plugin API 1.3") && err.message.contains(what), "{what}: {}", err.message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
//! Real Wasm provider dispatch and the document-edit path used locally and over RPC.
|
||||
use ide_core::{CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, TextChange};
|
||||
use ide_host::plugins::{Consent, HostWorkspace, PluginHost, set_editor_providers};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use ide_plugin::{Invocation, Limits, ProviderDocument};
|
||||
use parking_lot::Mutex;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const ID: &str = "test.diagnostics";
|
||||
const SOURCE: &str = "plugin-provider:test.diagnostics";
|
||||
|
||||
fn fixture() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/diagnostics")
|
||||
}
|
||||
|
||||
fn plugins(dir: &Path, limits: Limits) -> Arc<PluginHost> {
|
||||
let host = Arc::new(PluginHost::new(dir.join("plugins"), Arc::new(|_: Option<&str>, _| {}), limits).unwrap());
|
||||
host.install_from_dir(&fixture(), &Consent::all()).unwrap();
|
||||
host
|
||||
}
|
||||
|
||||
fn generous() -> Limits {
|
||||
Limits { edit_soft: Duration::from_secs(5), edit_hard: Duration::from_secs(10), ..Limits::default() }
|
||||
}
|
||||
|
||||
fn doc(root: &Path, language: &str, text: &str) -> ProviderDocument {
|
||||
ProviderDocument { path: root.join("a.txt"), language: language.into(), version: 42, text: text.into() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declared_languages_receive_versioned_text_and_utf16_ranges() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = plugins(tmp.path(), generous());
|
||||
let result = host.provide_diagnostics(&doc(tmp.path(), "text", "😀BAD\nBAD"), &CancellationToken::new());
|
||||
assert_eq!(result.len(), 1);
|
||||
assert_eq!(result[0].0, ID);
|
||||
let items = &result[0].1;
|
||||
assert_eq!(items.len(), 2);
|
||||
assert_eq!(items[0].range, Range::new(Pos::new(0, 2), Pos::new(0, 5)));
|
||||
assert_eq!(items[1].range, Range::new(Pos::new(1, 0), Pos::new(1, 3)));
|
||||
assert_eq!(items[0].message, "BAD in text at version 42");
|
||||
assert_eq!(items[0].code.as_deref(), Some("bad-word"));
|
||||
assert_eq!(items[0].server.as_deref(), Some(ID));
|
||||
assert!(host.provide_diagnostics(&doc(tmp.path(), "rust", "BAD"), &CancellationToken::new()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_diagnostics_have_the_same_bounds_and_tags_as_manual_publish() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = plugins(tmp.path(), generous());
|
||||
let result = host.provide_diagnostics(&doc(tmp.path(), "text", "limits"), &CancellationToken::new());
|
||||
let items = &result[0].1;
|
||||
assert_eq!(items.len(), 5000);
|
||||
assert_eq!(items[0].message.len(), 4096);
|
||||
assert_eq!(items[0].source.as_ref().unwrap().len(), 128);
|
||||
assert_eq!(items[0].code.as_ref().unwrap().len(), 128);
|
||||
assert!(items[0].unnecessary && items[0].deprecated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_export_does_not_need_project_read_permission() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let package = tmp.path().join("no-capability");
|
||||
std::fs::create_dir_all(package.join("dist")).unwrap();
|
||||
std::fs::copy(fixture().join("dist/plugin.wasm"), package.join("dist/plugin.wasm")).unwrap();
|
||||
let manifest = std::fs::read_to_string(fixture().join("plugin.toml")).unwrap();
|
||||
std::fs::write(package.join("plugin.toml"), manifest.replace("[capabilities]\nrequired = [\"project.read\"]", ""))
|
||||
.unwrap();
|
||||
let host = PluginHost::new(tmp.path().join("plugins"), Arc::new(|_: Option<&str>, _| {}), generous()).unwrap();
|
||||
host.install_from_dir(&package, &Consent::default()).unwrap();
|
||||
assert_eq!(host.provide_diagnostics(&doc(tmp.path(), "text", "BAD"), &CancellationToken::new()).len(), 1);
|
||||
assert!(host.run_command(ID, "publish", Some("/project/a.txt"), Invocation::default()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostics_is_an_api_1_3_addition() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let package = tmp.path().join("old");
|
||||
std::fs::create_dir_all(package.join("dist")).unwrap();
|
||||
std::fs::copy(fixture().join("dist/plugin.wasm"), package.join("dist/plugin.wasm")).unwrap();
|
||||
let manifest = std::fs::read_to_string(fixture().join("plugin.toml")).unwrap();
|
||||
std::fs::write(package.join("plugin.toml"), manifest.replace("^1.3", "^1.0")).unwrap();
|
||||
let host = PluginHost::new(tmp.path().join("plugins"), Arc::new(|_: Option<&str>, _| {}), generous()).unwrap();
|
||||
assert!(host.install_from_dir(&package, &Consent::all()).unwrap_err().message.contains("new in plugin API 1.3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn late_and_cancelled_answers_are_dropped_without_disabling_the_plugin() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = plugins(tmp.path(), Limits { edit_soft: Duration::from_millis(10), ..generous() });
|
||||
assert!(host.provide_diagnostics(&doc(tmp.path(), "text", "slow BAD"), &CancellationToken::new()).is_empty());
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
assert!(host.provide_diagnostics(&doc(tmp.path(), "text", "BAD"), &cancel).is_empty());
|
||||
assert_eq!(host.run_command(ID, "calls", None, Invocation::default()).unwrap().as_deref(), Some("1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelling_a_queued_provider_does_not_interrupt_another_windows_command() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = plugins(tmp.path(), generous());
|
||||
host.run_command(ID, "calls", None, Invocation::default()).unwrap();
|
||||
let waiter = {
|
||||
let host = host.clone();
|
||||
std::thread::spawn(move || host.run_command(ID, "wait", None, Invocation::default()))
|
||||
};
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
let cancel = CancellationToken::new();
|
||||
let canceller = {
|
||||
let cancel = cancel.clone();
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(30));
|
||||
cancel.cancel();
|
||||
})
|
||||
};
|
||||
assert!(host.provide_diagnostics(&doc(tmp.path(), "text", "BAD"), &cancel).is_empty());
|
||||
canceller.join().unwrap();
|
||||
assert_eq!(waiter.join().unwrap().unwrap().as_deref(), Some("finished"));
|
||||
assert_eq!(host.run_command(ID, "calls", None, Invocation::default()).unwrap().as_deref(), Some("0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editor_requests_expire_in_the_queue_without_running_after_a_command() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = plugins(tmp.path(), Limits { edit_soft: Duration::from_millis(10), ..generous() });
|
||||
host.run_command(ID, "calls", None, Invocation::default()).unwrap();
|
||||
let waiter = {
|
||||
let host = host.clone();
|
||||
std::thread::spawn(move || host.run_command(ID, "wait", None, Invocation::default()))
|
||||
};
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
assert!(host.provide_diagnostics(&doc(tmp.path(), "text", "BAD"), &CancellationToken::new()).is_empty());
|
||||
assert_eq!(waiter.join().unwrap().unwrap().as_deref(), Some("finished"));
|
||||
assert_eq!(host.run_command(ID, "calls", None, Invocation::default()).unwrap().as_deref(), Some("0"));
|
||||
assert_eq!(host.info_of(ID).unwrap().stats.slow_calls, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_on_cancels_a_running_provider_before_its_hard_deadline() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = plugins(tmp.path(), Limits { fuel: u64::MAX, ..generous() });
|
||||
host.run_command(ID, "calls", None, Invocation::default()).unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let canceller = {
|
||||
let cancel = cancel.clone();
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(30));
|
||||
cancel.cancel();
|
||||
})
|
||||
};
|
||||
let started = Instant::now();
|
||||
assert!(host.provide_diagnostics(&doc(tmp.path(), "text", "spin BAD"), &cancel).is_empty());
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
canceller.join().unwrap();
|
||||
}
|
||||
|
||||
// This executable has one edit-path test because editor providers are installed once per process.
|
||||
type Events = Arc<Mutex<Vec<(String, IdeEvent)>>>;
|
||||
|
||||
fn runtime_host(base: &Path, events: Events) -> Arc<Host> {
|
||||
Arc::new(Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(move |window| {
|
||||
let (events, window) = (events.clone(), window.to_owned());
|
||||
Arc::new(move |event: IdeEvent| events.lock().push((window.clone(), event)))
|
||||
}),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
}))
|
||||
}
|
||||
|
||||
fn latest(events: &Events, window: &str, source: &str) -> Option<Vec<Diagnostic>> {
|
||||
events.lock().iter().rev().find_map(|(w, e)| match e {
|
||||
IdeEvent::Diagnostics { source: s, items, .. } if w == window && s == source => Some(items.clone()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
async fn wait_for(events: &Events, window: &str, predicate: impl Fn(&[Diagnostic]) -> bool) {
|
||||
wait_for_source(events, window, SOURCE, predicate).await;
|
||||
}
|
||||
|
||||
async fn wait_for_source(events: &Events, window: &str, source: &str, predicate: impl Fn(&[Diagnostic]) -> bool) {
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
if latest(events, window, source).is_some_and(|items| predicate(&items)) {
|
||||
return;
|
||||
}
|
||||
assert!(start.elapsed() < Duration::from_secs(5), "missing diagnostics for {window}");
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn replace(host: &Host, window: &str, info: &ide_workspace::DocumentInfo, text: &str) -> u32 {
|
||||
let project = host.project(window).unwrap();
|
||||
let snapshot = project.documents.snapshot(info.id).unwrap();
|
||||
let len = snapshot.text.encode_utf16().count() as u32;
|
||||
ops::doc::edit(
|
||||
host,
|
||||
window,
|
||||
info.id,
|
||||
snapshot.version,
|
||||
ChangeSet { changes: vec![TextChange { from: 0, to: len, insert: text.into() }] },
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn typing_is_debounced_versioned_and_scoped_to_document_project_and_window_lifetimes() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let path = root.join("a.txt");
|
||||
std::fs::write(&path, "clean").unwrap();
|
||||
let events: Events = Arc::default();
|
||||
let host = runtime_host(&root.join("app"), events.clone());
|
||||
let plugins = plugins(&root, generous());
|
||||
plugins.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host)))));
|
||||
set_editor_providers(Some(&plugins));
|
||||
let left = host.open_light("left", &path).unwrap();
|
||||
host.open_light("right", &path).unwrap();
|
||||
let a = ops::doc::open(&host, "left", path.clone()).await.unwrap();
|
||||
let b = ops::doc::open(&host, "right", path.clone()).await.unwrap();
|
||||
let second_tab = ops::doc::open(&host, "right", path.clone()).await.unwrap();
|
||||
assert_eq!(b.id, second_tab.id);
|
||||
wait_for(&events, "left", |items| items.is_empty()).await;
|
||||
wait_for(&events, "right", |items| items.is_empty()).await;
|
||||
|
||||
let calls: u64 = plugins.run_command(ID, "calls", None, Invocation::default()).unwrap().unwrap().parse().unwrap();
|
||||
events.lock().clear();
|
||||
replace(&host, "left", &a, "BAD");
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
let version = replace(&host, "left", &a, "😀BAD");
|
||||
tokio::time::sleep(Duration::from_millis(150)).await;
|
||||
assert!(latest(&events, "left", SOURCE).is_none(), "300ms after the latest edit");
|
||||
wait_for(&events, "left", |items| !items.is_empty()).await;
|
||||
assert_eq!(
|
||||
latest(&events, "left", SOURCE).unwrap()[0].message,
|
||||
format!("BAD in {} at version {version}", a.language)
|
||||
);
|
||||
assert!(latest(&events, "right", SOURCE).is_none(), "other window has its own buffer");
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "clean", "no save required");
|
||||
let after: u64 = plugins.run_command(ID, "calls", None, Invocation::default()).unwrap().unwrap().parse().unwrap();
|
||||
assert_eq!(after, calls + 1, "the edit burst was coalesced");
|
||||
|
||||
plugins.run_command(ID, "publish", path.to_str(), Invocation::default()).unwrap();
|
||||
let manual_window = events.lock().iter().find_map(|(window, event)| matches!(event, IdeEvent::Diagnostics { source, items, .. } if source == "plugin:test.diagnostics" && !items.is_empty()).then(|| window.clone())).unwrap();
|
||||
assert_eq!(latest(&events, &manual_window, "plugin:test.diagnostics").unwrap()[0].message, "Manual problem");
|
||||
replace(&host, "left", &a, "clean again");
|
||||
wait_for(&events, "left", |items| items.is_empty()).await;
|
||||
assert_eq!(latest(&events, &manual_window, "plugin:test.diagnostics").unwrap()[0].message, "Manual problem");
|
||||
|
||||
events.lock().clear();
|
||||
replace(&host, "left", &a, "slow BAD");
|
||||
tokio::time::sleep(Duration::from_millis(350)).await;
|
||||
replace(&host, "left", &a, "latest clean");
|
||||
wait_for(&events, "left", |items| items.is_empty()).await;
|
||||
assert!(
|
||||
!events.lock().iter().any(|(_, e)| matches!(e, IdeEvent::Diagnostics { items, .. } if !items.is_empty())),
|
||||
"superseded in-flight answers never publish"
|
||||
);
|
||||
|
||||
replace(&host, "right", &b, "BAD right");
|
||||
wait_for(&events, "right", |items| !items.is_empty()).await;
|
||||
ops::doc::close(&host, "right", b.id).unwrap();
|
||||
assert!(!latest(&events, "right", SOURCE).unwrap().is_empty(), "another pane still owns this document");
|
||||
ops::doc::close(&host, "right", second_tab.id).unwrap();
|
||||
wait_for(&events, "right", |items| items.is_empty()).await;
|
||||
replace(&host, "left", &a, "BAD left");
|
||||
wait_for(&events, "left", |items| !items.is_empty()).await;
|
||||
plugins.set_enabled(ID, false).unwrap();
|
||||
wait_for(&events, "left", |items| items.is_empty()).await;
|
||||
plugins.set_enabled(ID, true).unwrap();
|
||||
|
||||
events.lock().clear();
|
||||
replace(&host, "left", &a, "slow BAD closing");
|
||||
tokio::time::sleep(Duration::from_millis(350)).await;
|
||||
host.close_project("left");
|
||||
// Keep the old Project alive deliberately: window reuse must still cancel it.
|
||||
assert_eq!(left.documents.snapshot(a.id).unwrap().text, "slow BAD closing");
|
||||
host.open_light("left", &path).unwrap();
|
||||
let reopened = ops::doc::open(&host, "left", path.clone()).await.unwrap();
|
||||
wait_for(&events, "left", |items| items.is_empty()).await;
|
||||
assert!(!events.lock().iter().any(|(_, e)| matches!(e, IdeEvent::Diagnostics { items, .. } if !items.is_empty())));
|
||||
// Project plugins receive only snapshots from the project that owns their declaration.
|
||||
let project_package = root.join(ide_host::plugins::DEV_PLUGINS_DIR).join("diagnostics");
|
||||
std::fs::create_dir_all(project_package.join("dist")).unwrap();
|
||||
std::fs::copy(fixture().join("dist/plugin.wasm"), project_package.join("dist/plugin.wasm")).unwrap();
|
||||
let manifest = std::fs::read_to_string(fixture().join("plugin.toml")).unwrap();
|
||||
std::fs::write(project_package.join("plugin.toml"), manifest.replace(ID, "project.diagnostics")).unwrap();
|
||||
plugins.set_project_policy(Arc::new(|_| true));
|
||||
plugins.sync_project(&root);
|
||||
plugins.grant("project.diagnostics", &Consent::all()).unwrap();
|
||||
replace(&host, "left", &reopened, "BAD in project");
|
||||
wait_for(&events, "left", |items| !items.is_empty()).await;
|
||||
let project_source = "plugin-provider:project.diagnostics";
|
||||
wait_for_source(&events, "left", project_source, |items| !items.is_empty()).await;
|
||||
let elsewhere = root.join("other");
|
||||
std::fs::create_dir_all(&elsewhere).unwrap();
|
||||
let other_path = elsewhere.join("other.txt");
|
||||
std::fs::write(&other_path, "BAD outside").unwrap();
|
||||
host.open_light("elsewhere", &other_path).unwrap();
|
||||
ops::doc::open(&host, "elsewhere", other_path).await.unwrap();
|
||||
wait_for(&events, "elsewhere", |items| !items.is_empty()).await;
|
||||
assert!(latest(&events, "elsewhere", project_source).is_none());
|
||||
plugins.restrict_project(&root);
|
||||
assert!(latest(&events, "left", project_source).unwrap().is_empty());
|
||||
// A completed answer may still be waiting for a sibling when its plugin crashes.
|
||||
let sibling = root.join("slow-sibling");
|
||||
std::fs::create_dir_all(sibling.join("dist")).unwrap();
|
||||
std::fs::copy(fixture().join("dist/plugin.wasm"), sibling.join("dist/plugin.wasm")).unwrap();
|
||||
let manifest = std::fs::read_to_string(fixture().join("plugin.toml")).unwrap();
|
||||
std::fs::write(
|
||||
sibling.join("plugin.toml"),
|
||||
manifest.replace(ID, "test.slow").replace("[\"text\", \"plaintext\"]", "[\"plaintext\"]"),
|
||||
)
|
||||
.unwrap();
|
||||
plugins.install_from_dir(&sibling, &Consent::all()).unwrap();
|
||||
plugins.run_command("test.slow", "calls", None, Invocation::default()).unwrap();
|
||||
let calls = plugins.run_command(ID, "calls", None, Invocation::default()).unwrap();
|
||||
events.lock().clear();
|
||||
replace(&host, "left", &reopened, "BAD completed before crash");
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let waiter = {
|
||||
let plugins = plugins.clone();
|
||||
std::thread::spawn(move || plugins.run_command("test.slow", "wait", None, Invocation::default()))
|
||||
};
|
||||
let started = Instant::now();
|
||||
while plugins.run_command(ID, "calls", None, Invocation::default()).unwrap() == calls {
|
||||
assert!(started.elapsed() < Duration::from_secs(5));
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
assert!(
|
||||
latest(&events, "left", SOURCE).is_none_or(|items| items.is_empty()),
|
||||
"the sibling still holds the result: {:?}",
|
||||
latest(&events, "left", SOURCE)
|
||||
);
|
||||
assert!(plugins.provide_diagnostics(&doc(&root, "text", "panic"), &CancellationToken::new()).is_empty());
|
||||
waiter.join().unwrap().unwrap();
|
||||
wait_for_source(&events, "left", "plugin-provider:test.slow", |items| !items.is_empty()).await;
|
||||
assert!(
|
||||
latest(&events, "left", SOURCE).is_none_or(|items| items.is_empty()),
|
||||
"a crash invalidates completed answers"
|
||||
);
|
||||
ops::doc::close(&host, "left", reopened.id).unwrap();
|
||||
host.shutdown().await;
|
||||
set_editor_providers(None);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
use ide_core::Pos;
|
||||
use ide_host::plugins::{Consent, PluginHost};
|
||||
use ide_plugin::{Limits, ProviderDocument};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
fn fixture_dir() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/hover")
|
||||
}
|
||||
|
||||
fn host(dir: &Path) -> PluginHost {
|
||||
let limits = Limits { edit_soft: Duration::from_secs(5), edit_hard: Duration::from_secs(10), ..Limits::default() };
|
||||
PluginHost::new(dir.join("plugins"), Arc::new(|_: Option<&str>, _| {}), limits).unwrap()
|
||||
}
|
||||
|
||||
fn doc(dir: &Path, language: &str, text: &str) -> ProviderDocument {
|
||||
ProviderDocument { path: dir.join("Order.php"), language: language.into(), version: 1, text: text.into() }
|
||||
}
|
||||
|
||||
const ORDER: &str = "<?php\nclass Order\n{\n public function user() {}\n}\n$order->user;\n$order->total;\n";
|
||||
|
||||
#[test]
|
||||
fn a_declared_name_gets_the_plugins_hover() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = host(tmp.path());
|
||||
host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap();
|
||||
let hovers = host.provide_hover(&doc(tmp.path(), "php", ORDER), Pos::new(5, 10));
|
||||
assert_eq!(hovers.len(), 1);
|
||||
assert_eq!(hovers[0].markdown, "**user** · declared on line 4");
|
||||
let range = hovers[0].range.unwrap();
|
||||
assert_eq!((range.start.line, range.start.col, range.end.line, range.end.col), (5, 8, 5, 12));
|
||||
assert!(host.provide_hover(&doc(tmp.path(), "php", ORDER), Pos::new(6, 10)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_declared_languages_are_asked() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = host(tmp.path());
|
||||
host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap();
|
||||
assert!(host.provide_hover(&doc(tmp.path(), "javascript", ORDER), Pos::new(5, 10)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_kind_needs_plugin_api_1_3() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = host(tmp.path());
|
||||
let pkg = tmp.path().join("old");
|
||||
std::fs::create_dir_all(pkg.join("dist")).unwrap();
|
||||
std::fs::copy(fixture_dir().join("dist/plugin.wasm"), pkg.join("dist/plugin.wasm")).unwrap();
|
||||
let manifest = std::fs::read_to_string(fixture_dir().join("plugin.toml")).unwrap();
|
||||
std::fs::write(pkg.join("plugin.toml"), manifest.replace("\"^1.3\"", "\"^1.0\"")).unwrap();
|
||||
let err = host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
|
||||
assert!(err.message.contains("new in plugin API 1.3"), "{}", err.message);
|
||||
}
|
||||
@@ -171,7 +171,12 @@ fn two_windows_of_same_root_keep_unsaved_snapshots_isolated() {
|
||||
.index_navigation(
|
||||
&f.root,
|
||||
Snapshot { path, version: Some(1), text, symbols: &symbols, scope: "" },
|
||||
Invocation { client: Some(client.into()), workspace_root: Some(f.root.clone()), editor: None },
|
||||
Invocation {
|
||||
client: Some(client.into()),
|
||||
workspace_root: Some(f.root.clone()),
|
||||
editor: None,
|
||||
selected_paths: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
use ide_core::{Pos, Range};
|
||||
use ide_host::plugins::{Consent, PluginHost};
|
||||
use ide_plugin::{Limits, ProviderDocument};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
fn fixture_dir() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/inlay-hints")
|
||||
}
|
||||
|
||||
fn host(dir: &Path) -> PluginHost {
|
||||
let limits = Limits { edit_soft: Duration::from_secs(5), edit_hard: Duration::from_secs(10), ..Limits::default() };
|
||||
PluginHost::new(dir.join("plugins"), Arc::new(|_: Option<&str>, _| {}), limits).unwrap()
|
||||
}
|
||||
|
||||
fn doc(dir: &Path, language: &str, text: &str) -> ProviderDocument {
|
||||
ProviderDocument { path: dir.join("Order.php"), language: language.into(), version: 1, text: text.into() }
|
||||
}
|
||||
|
||||
const ORDER: &str = "<?php\nclass Order\n{\n public function user(): ?User {}\n}\n$order->user();\n$order->total();\n$order->user;\n";
|
||||
|
||||
fn all() -> Range {
|
||||
Range::new(Pos::new(0, 0), Pos::new(100, 0))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calls_of_declared_methods_get_a_type_hint() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = host(tmp.path());
|
||||
host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap();
|
||||
let hints = host.provide_inlay_hints(&doc(tmp.path(), "php", ORDER), all());
|
||||
let found: Vec<_> =
|
||||
hints.iter().map(|h| (h.position.line, h.position.col, h.label.as_str(), h.kind.as_str())).collect();
|
||||
assert_eq!(found, [(5, 14, ": ?User", "type")]);
|
||||
assert_eq!(hints[0].tooltip.as_deref(), Some("user() returns ?User"));
|
||||
assert!(!hints[0].padding_left && !hints[0].padding_right);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_declared_languages_are_asked() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = host(tmp.path());
|
||||
host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap();
|
||||
assert!(host.provide_inlay_hints(&doc(tmp.path(), "javascript", ORDER), all()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_kind_needs_plugin_api_1_3() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = host(tmp.path());
|
||||
let pkg = tmp.path().join("old");
|
||||
std::fs::create_dir_all(pkg.join("dist")).unwrap();
|
||||
std::fs::copy(fixture_dir().join("dist/plugin.wasm"), pkg.join("dist/plugin.wasm")).unwrap();
|
||||
let manifest = std::fs::read_to_string(fixture_dir().join("plugin.toml")).unwrap();
|
||||
std::fs::write(pkg.join("plugin.toml"), manifest.replace("\"^1.3\"", "\"^1.0\"")).unwrap();
|
||||
let err = host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
|
||||
assert!(err.message.contains("new in plugin API 1.3"), "{}", err.message);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
use ide_host::plugins::{Consent, PluginHost};
|
||||
use ide_plugin::{Limits, ProviderDocument};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
fn fixture_dir() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/semantic-tokens")
|
||||
}
|
||||
|
||||
fn host(dir: &Path) -> PluginHost {
|
||||
let limits = Limits { edit_soft: Duration::from_secs(5), edit_hard: Duration::from_secs(10), ..Limits::default() };
|
||||
PluginHost::new(dir.join("plugins"), Arc::new(|_: Option<&str>, _| {}), limits).unwrap()
|
||||
}
|
||||
|
||||
fn doc(dir: &Path, language: &str, text: &str) -> ProviderDocument {
|
||||
ProviderDocument { path: dir.join("Order.php"), language: language.into(), version: 1, text: text.into() }
|
||||
}
|
||||
|
||||
const ORDER: &str =
|
||||
"<?php\nclass Order\n{\n public function user() {}\n}\n$order->user;\n$order->total;\n$order->user();\n";
|
||||
|
||||
#[test]
|
||||
fn relation_accesses_and_columns_get_their_own_kinds() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = host(tmp.path());
|
||||
host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap();
|
||||
let tokens = host.provide_semantic_tokens(&doc(tmp.path(), "php", ORDER));
|
||||
let found: Vec<_> = tokens
|
||||
.iter()
|
||||
.map(|t| (t.range.start.line, t.range.start.col, t.range.end.line, t.range.end.col, t.kind.as_str()))
|
||||
.collect();
|
||||
assert_eq!(found, [(5, 8, 5, 12, "method"), (6, 8, 6, 13, "property")]);
|
||||
assert!(tokens.iter().all(|t| t.modifiers.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_declared_languages_are_asked() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = host(tmp.path());
|
||||
host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap();
|
||||
assert!(host.provide_semantic_tokens(&doc(tmp.path(), "javascript", "a->b")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_kind_needs_plugin_api_1_3() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = host(tmp.path());
|
||||
let pkg = tmp.path().join("old");
|
||||
std::fs::create_dir_all(pkg.join("dist")).unwrap();
|
||||
std::fs::copy(fixture_dir().join("dist/plugin.wasm"), pkg.join("dist/plugin.wasm")).unwrap();
|
||||
let manifest = std::fs::read_to_string(fixture_dir().join("plugin.toml")).unwrap();
|
||||
std::fs::write(pkg.join("plugin.toml"), manifest.replace("\"^1.3\"", "\"^1.0\"")).unwrap();
|
||||
let err = host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
|
||||
assert!(err.message.contains("new in plugin API 1.3"), "{}", err.message);
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
//! The synchronous workspace import uses the real project index, also from a provider.
|
||||
use ide_core::CancellationToken;
|
||||
use ide_core::{NullSink, Pos, Range};
|
||||
use ide_host::plugins::{Consent, HostWorkspace, PluginHost, PluginWorkspace};
|
||||
use ide_host::{Host, HostConfig};
|
||||
use ide_plugin::{Invocation, Limits, ProviderDocument};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const WAIT: Duration = Duration::from_secs(30);
|
||||
|
||||
struct Fixture {
|
||||
_tmp: tempfile::TempDir,
|
||||
_runtime: tokio::runtime::Runtime,
|
||||
host: Arc<Host>,
|
||||
plugins: PluginHost,
|
||||
root: PathBuf,
|
||||
other: PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new(capability: bool) -> Self {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (root, other) = (base.join("project"), base.join("other"));
|
||||
for dir in [&root, &other] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
std::fs::write(root.join("Order.php"), "<?php class OrderController { public function item() {} }\n").unwrap();
|
||||
std::fs::write(root.join("Main.java"), "class OrderService { void serve() {} }\n").unwrap();
|
||||
std::fs::write(other.join("Order.php"), "<?php class OrderElsewhere {}\n").unwrap();
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
|
||||
let syntax = OnceLock::new();
|
||||
syntax.set(Arc::new(ide_language::Syntax::new())).ok().unwrap();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::new(syntax),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: runtime.handle().clone(),
|
||||
project_environment: false,
|
||||
}));
|
||||
// Restricted projects need no LSP/process startup for index queries.
|
||||
{
|
||||
let _guard = runtime.enter();
|
||||
for (window, dir) in [("main", &root), ("other", &other)] {
|
||||
let project = host.open_project(window, dir).unwrap();
|
||||
assert!(project.index.wait_idle(WAIT));
|
||||
}
|
||||
}
|
||||
let plugins = PluginHost::new(
|
||||
base.join("plugins"),
|
||||
Arc::new(|_: Option<&str>, _| {}),
|
||||
Limits { edit_soft: Duration::from_secs(5), edit_hard: Duration::from_secs(10), ..Limits::default() },
|
||||
)
|
||||
.unwrap();
|
||||
plugins.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host)))));
|
||||
plugins.set_project_policy(Arc::new(|_| true));
|
||||
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/symbols");
|
||||
let package = base.join("fixture");
|
||||
std::fs::create_dir_all(package.join("dist")).unwrap();
|
||||
std::fs::copy(source.join("dist/plugin.wasm"), package.join("dist/plugin.wasm")).unwrap();
|
||||
let manifest = std::fs::read_to_string(source.join("plugin.toml")).unwrap();
|
||||
let manifest =
|
||||
if capability { manifest } else { manifest.replace("required = [\"project.read\"]", "required = []") };
|
||||
std::fs::write(package.join("plugin.toml"), manifest).unwrap();
|
||||
plugins.install_from_dir(&package, &Consent::all()).unwrap();
|
||||
Self { _tmp: tmp, _runtime: runtime, host, plugins, root, other }
|
||||
}
|
||||
|
||||
fn invoke(&self, command: &str, root: &Path, query: &str) -> ide_core::IdeResult<Option<String>> {
|
||||
self.plugins.run_command(
|
||||
"test.symbols",
|
||||
command,
|
||||
Some(query),
|
||||
Invocation { workspace_root: Some(root.to_path_buf()), ..Default::default() },
|
||||
)
|
||||
}
|
||||
|
||||
fn search(&self, query: &str) -> String {
|
||||
self.invoke("symbols", &self.root, query).unwrap().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
self.host.close_project("main");
|
||||
self.host.close_project("other");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbols_reach_commands_and_providers_without_a_language_server() {
|
||||
let f = Fixture::new(true);
|
||||
let all = f.search("Order|10");
|
||||
assert!(all.contains("OrderController\tclass\t"), "{all}");
|
||||
assert!(all.contains("OrderService\tclass\t"), "{all}");
|
||||
assert!(!all.contains("OrderElsewhere"));
|
||||
assert_eq!(f.search("OCo|1").lines().count(), 1);
|
||||
assert!(f.search("OrderController.item|1").starts_with("item\tmethod\tOrderController\t"));
|
||||
assert!(f.search("|10").is_empty());
|
||||
assert!(f.search("Order|0").is_empty());
|
||||
assert!(f.search("missing|10").is_empty());
|
||||
assert!(f.search("Order|4294967295").contains("OrderController"));
|
||||
assert!(
|
||||
f.invoke("symbols", &f.root, &format!("{}|1", "é".repeat(129)))
|
||||
.unwrap_err()
|
||||
.message
|
||||
.contains("256 UTF-8 bytes")
|
||||
);
|
||||
let other = f.invoke("symbols", &f.other, "Order|10").unwrap().unwrap();
|
||||
assert!(other.contains("OrderElsewhere") && !other.contains("OrderController"));
|
||||
for language in ["php", "java"] {
|
||||
let targets = f.plugins.provide_definition(
|
||||
&ProviderDocument {
|
||||
path: f.root.join(if language == "php" { "Usage.php" } else { "Usage.java" }),
|
||||
language: language.into(),
|
||||
version: 1,
|
||||
text: "OCo".into(),
|
||||
},
|
||||
Pos::new(0, 3),
|
||||
);
|
||||
assert_eq!(targets.len(), 1);
|
||||
assert_eq!(targets[0].path, f.root.join("Order.php"));
|
||||
let indexed = HostWorkspace(Arc::downgrade(&f.host))
|
||||
.symbols(&f.root, "OCo", 1, &CancellationToken::new(), Instant::now() + WAIT)
|
||||
.unwrap();
|
||||
assert_eq!(targets[0].range, indexed[0].location.range);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reindex_and_closed_project_replace_results_and_invalidate_retained_handles() {
|
||||
let f = Fixture::new(true);
|
||||
f.invoke("remember", &f.root, "").unwrap();
|
||||
let p = f.host.project("main").unwrap();
|
||||
let path = f.root.join("Order.php");
|
||||
std::fs::write(&path, "<?php /*😀*/ class UpdatedController {}\n").unwrap();
|
||||
p.index.update(std::slice::from_ref(&path), &[]);
|
||||
assert!(p.index.wait_idle(WAIT));
|
||||
assert!(!f.search("Order|10").contains("OrderController"));
|
||||
let symbols = HostWorkspace(Arc::downgrade(&f.host))
|
||||
.symbols(&f.root, "UpdatedController", 1, &CancellationToken::new(), Instant::now() + WAIT)
|
||||
.unwrap();
|
||||
assert_eq!(symbols.len(), 1);
|
||||
assert_eq!(symbols[0].location.range, Range::new(Pos::new(0, 19), Pos::new(0, 36)));
|
||||
assert!(f.search("Updated|10").contains("0:19-0:36"));
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
p.index.update(&[], &[path]);
|
||||
assert!(p.index.wait_idle(WAIT));
|
||||
assert!(f.search("Updated|10").is_empty());
|
||||
f.host.close_project("main");
|
||||
let error = f.invoke("remembered", &f.root, "Order|10").unwrap_err();
|
||||
assert!(error.message.contains("no longer open"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_limits_are_capped_before_searching_the_index() {
|
||||
let f = Fixture::new(true);
|
||||
let project = f.host.project("main").unwrap();
|
||||
let path = f.root.join("Bulk.java");
|
||||
let text = (0..1005).map(|i| format!("class BulkSymbol{i} {{}}\n")).collect::<String>();
|
||||
std::fs::write(&path, text).unwrap();
|
||||
project.index.update(&[path], &[]);
|
||||
assert!(project.index.wait_idle(WAIT));
|
||||
assert_eq!(f.search("BulkSymbol|4294967295").lines().count(), 1000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_queries_require_project_read_even_with_an_invocation_project() {
|
||||
let f = Fixture::new(false);
|
||||
let error = f.invoke("symbols", &f.root, "Order|10").unwrap_err();
|
||||
assert!(error.message.contains("project.read"), "{error}");
|
||||
assert!(
|
||||
f.plugins
|
||||
.provide_definition(
|
||||
&ProviderDocument {
|
||||
path: f.root.join("Usage.php"),
|
||||
language: "php".into(),
|
||||
version: 1,
|
||||
text: "OCo".into(),
|
||||
},
|
||||
Pos::new(0, 3)
|
||||
)
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_search_excludes_external_content_roots_before_ranking() {
|
||||
let f = Fixture::new(true);
|
||||
let project = f.host.project("main").unwrap();
|
||||
std::fs::write(f.other.join("Exact.php"), "<?php class Order {}\n").unwrap();
|
||||
project.index.set_scope(vec![f.other.clone()], Vec::new());
|
||||
assert!(project.index.wait_idle(WAIT));
|
||||
assert_eq!(project.index.find_symbols("OrderElsewhere", ide_index::SymbolFilter::All, 1).len(), 1);
|
||||
assert!(f.search("OrderElsewhere|10").is_empty());
|
||||
// A better external match must not displace a readable fuzzy match.
|
||||
let result = f.search("Order|1");
|
||||
assert!(result.contains("OrderController") || result.contains("OrderService"), "{result}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_symbol_search_honours_cancellation_and_deadlines() {
|
||||
let f = Fixture::new(true);
|
||||
let workspace = HostWorkspace(Arc::downgrade(&f.host));
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
assert_eq!(
|
||||
workspace.symbols(&f.root, "Order", 10, &cancel, Instant::now() + WAIT),
|
||||
Err(ide_plugin::HostError::Cancelled)
|
||||
);
|
||||
let error = workspace.symbols(&f.root, "Order", 10, &CancellationToken::new(), Instant::now()).unwrap_err();
|
||||
assert!(error.to_string().contains("timed out"), "{error}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symbol_search_excludes_updates_through_escaping_symlink_ancestors() {
|
||||
let f = Fixture::new(true);
|
||||
let project = f.host.project("main").unwrap();
|
||||
std::fs::write(f.other.join("Secret.php"), "<?php class SecretSymbol {}\n").unwrap();
|
||||
let dir = f.root.join("linked");
|
||||
std::os::unix::fs::symlink(&f.other, &dir).unwrap();
|
||||
project.index.update(&[dir.join("Secret.php")], &[]);
|
||||
assert!(project.index.wait_idle(WAIT));
|
||||
assert!(f.search("Secret|1").is_empty());
|
||||
}
|
||||
+2158
-10
File diff suppressed because it is too large.
Load diff
@@ -276,7 +276,7 @@ async fn python_venv() {
|
||||
// The project's virtualenv: listed first, and the interpreter the project uses.
|
||||
let found = ops::sdk::sdk_detect(&p.host, WINDOW, ide_sdk::SdkKind::Python).await.unwrap();
|
||||
assert_eq!(found.first().map(|s| s.source.as_str()), Some("venv"), "{found:?}");
|
||||
let effective = ops::sdk::sdk_python_effective(&p.host, WINDOW).unwrap().expect("an interpreter");
|
||||
let effective = ops::sdk::sdk_python_effective(&p.host, WINDOW, None).unwrap().expect("an interpreter");
|
||||
assert!(effective.starts_with(p.root.join(".venv")), "{effective:?}");
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 979 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user