дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
Порівняти коміти
121
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
f2869643b7 | ||
|
|
06fab1b237 | ||
|
|
652798bc53 | ||
|
|
85e417001a | ||
|
|
8488eda54e | ||
|
|
d02a3592b0 | ||
|
|
439b7940a8 | ||
|
|
de92f3b367 | ||
|
|
5b904f7896 | ||
|
|
511d3f21bb | ||
|
|
972f18331e | ||
|
|
77e669c189 | ||
|
|
f2641b9697 | ||
|
|
3811dfb512 | ||
|
|
9e2da77162 | ||
|
|
3a89b94624 | ||
|
|
df40f0befe | ||
|
|
f151498e07 | ||
|
|
d959a2a583 | ||
|
|
7ab456b1e7 | ||
|
|
f8a9b204c6 | ||
|
|
be7a0cfa5b | ||
|
|
b95f87e645 | ||
|
|
f40b645c8e | ||
|
|
e4ec1978d8 | ||
|
|
10242d2e58 | ||
|
|
fad9135f7a | ||
|
|
703b19b526 | ||
|
|
c3de09be78 | ||
|
|
6b61b15f00 | ||
|
|
19948c1426 | ||
|
|
36f2855253 | ||
|
|
e30ae3f6b8 | ||
|
|
9ee8f67e9f | ||
|
|
5b486f1588 | ||
|
|
6f8e8501c6 | ||
|
|
27c7323c0b | ||
|
|
41cb8f993e | ||
|
|
6e37a1a977 | ||
|
|
e99fcb0c49 | ||
|
|
2f31544d04 | ||
|
|
cbcd84f1d2 | ||
|
|
a3a56ab10d | ||
|
|
3961f38f46 | ||
|
|
4c5f4fa1e1 | ||
|
|
90734775b9 | ||
|
|
b53915e4b6 | ||
|
|
d361d7239a | ||
|
|
77a03ac197 | ||
|
|
f28a11d043 | ||
|
|
cdb4f9ab15 | ||
|
|
c709844c04 | ||
|
|
2cce84ad2c | ||
|
|
91dcd1b7eb | ||
|
|
3d275d5a3d | ||
|
|
cc49827793 | ||
|
|
7b3813f9e2 | ||
|
|
ebc6dc86f1 | ||
|
|
0ae1628678 | ||
|
|
dc8c45c77c | ||
|
|
e5f93b8526 | ||
|
|
73ba36381c | ||
|
|
3bc75e1de0 | ||
|
|
633bef2e69 | ||
|
|
9aa0718cf9 | ||
|
|
836a4405d6 | ||
|
|
952bd0b24b | ||
|
|
ac5e4b7259 | ||
|
|
2ea7d6c41b | ||
|
|
16e5cb5763 | ||
|
|
611440f77f | ||
|
|
482143769f | ||
|
|
176859987b | ||
|
|
6cdd52d31a | ||
|
|
90a0fd9901 | ||
|
|
9d92f47f94 | ||
|
|
68abd00a7f | ||
|
|
4c01ce4443 | ||
|
|
9da53322bc | ||
|
|
720b18861c | ||
|
|
802d9d26e2 | ||
|
|
fb97cdac03 | ||
|
|
caf909cab3 | ||
|
|
c88a4f403f | ||
|
|
98f163da75 | ||
|
|
5952e36d8b | ||
|
|
ad56613901 | ||
|
|
3fae4c0417 | ||
|
|
99fdea5c9a | ||
|
|
8aeac949b5 | ||
|
|
fa625d8cc7 | ||
|
|
b7b5bd5c50 | ||
|
|
2174a7278a | ||
|
|
7bbc12382e | ||
|
|
4fb1cae917 | ||
|
|
23bbed8bfe | ||
|
|
1880ac541c | ||
|
|
d698b50361 | ||
|
|
d5ba63e333 | ||
|
|
8108b440a6 | ||
|
|
4401ed3119 | ||
|
|
dbbdc4a085 | ||
|
|
85456e6930 | ||
|
|
b4d2859277 | ||
|
|
ba880dac06 | ||
|
|
0b1a675fab | ||
|
|
0b06d3313f | ||
|
|
ddaee1f5ce | ||
|
|
623f1fa4e7 | ||
|
|
79f6476d52 | ||
|
|
bd396485c2 | ||
|
|
c04d9381be | ||
|
|
45f6366b92 | ||
|
|
fb0b2d6a5f | ||
|
|
ddea7e5ec5 | ||
|
|
3747a8a63f | ||
|
|
0a8fea1876 | ||
|
|
ccc0eb1f54 | ||
|
|
54dadc4605 | ||
|
|
6fba4671e6 | ||
|
|
d5058b930b |
No files matched your search
@@ -30,6 +30,7 @@ on:
|
||||
- "src/ui/**"
|
||||
- "src/editor/api.ts"
|
||||
- "src/editor/navigationProviders.ts"
|
||||
- "src/editor/refactorProviders.ts"
|
||||
- "src/editor/relatedProviders.ts"
|
||||
- "src/editor/core/cm/cornerInset.ts"
|
||||
- "src/editor/core/cm/iconArea.ts"
|
||||
@@ -107,7 +108,7 @@ jobs:
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
|
||||
Створено
+67
-49
@@ -4154,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4182,7 +4182,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4194,7 +4194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4205,7 +4205,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4223,7 +4223,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4237,7 +4237,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4248,7 +4248,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4259,7 +4259,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4281,7 +4281,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4294,7 +4294,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4323,7 +4323,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4362,7 +4362,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4375,7 +4375,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4389,7 +4389,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4409,7 +4409,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-flutter"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
@@ -4420,7 +4420,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4432,7 +4432,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4444,7 +4444,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4463,7 +4463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4490,6 +4490,7 @@ dependencies = [
|
||||
"ide-docker",
|
||||
"ide-extension",
|
||||
"ide-flutter",
|
||||
"ide-github",
|
||||
"ide-heap",
|
||||
"ide-http",
|
||||
"ide-index",
|
||||
@@ -4545,11 +4546,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"http",
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
"objc2-cf-network",
|
||||
"objc2-core-foundation",
|
||||
"parking_lot 0.12.5",
|
||||
"reqwest",
|
||||
"rustls",
|
||||
@@ -4564,7 +4569,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4587,7 +4592,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4599,7 +4604,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4615,7 +4620,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4624,7 +4629,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4635,7 +4640,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4694,7 +4699,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4724,7 +4729,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4743,20 +4748,24 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
"ide-http",
|
||||
"ide-vfs",
|
||||
"jupyter-protocol",
|
||||
"jupyter-zmq-client",
|
||||
"libc",
|
||||
"parking_lot 0.12.5",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"specta-typescript",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tokio-tungstenite",
|
||||
"uuid",
|
||||
"windows-sys 0.61.2",
|
||||
"zeromq",
|
||||
@@ -4764,7 +4773,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4786,7 +4795,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4800,7 +4809,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4820,8 +4829,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"ide-build",
|
||||
@@ -4845,7 +4855,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4861,7 +4871,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4887,7 +4897,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4908,7 +4918,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot 0.12.5",
|
||||
@@ -4921,7 +4931,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4946,7 +4956,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4959,7 +4969,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4974,7 +4984,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4988,7 +4998,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -5001,7 +5011,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"flate2",
|
||||
@@ -5025,7 +5035,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5047,7 +5057,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5074,7 +5084,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5090,7 +5100,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6321,6 +6331,15 @@ dependencies = [
|
||||
"objc2-quartz-core 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-cf-network"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b4c9e30e636e2cd7d7414f320af2e0aa86f686adfc6f1bbe50b92366e4309c8"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-cloud-kit"
|
||||
version = "0.2.2"
|
||||
@@ -6729,7 +6748,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -6749,7 +6768,6 @@ dependencies = [
|
||||
"ide-drag-out",
|
||||
"ide-extension",
|
||||
"ide-fonts",
|
||||
"ide-github",
|
||||
"ide-host",
|
||||
"ide-http",
|
||||
"ide-jsonrpc",
|
||||
|
||||
+2
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.54"
|
||||
version = "0.1.55"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -24,6 +24,7 @@ ide-jsonrpc = { path = "crates/ide-jsonrpc" }
|
||||
ide-lsp = { path = "crates/ide-lsp" }
|
||||
ide-dap = { path = "crates/ide-dap" }
|
||||
ide-vcs = { path = "crates/ide-vcs" }
|
||||
ide-github = { path = "crates/ide-github" }
|
||||
ide-terminal = { path = "crates/ide-terminal" }
|
||||
ide-run = { path = "crates/ide-run" }
|
||||
ide-workspace = { path = "crates/ide-workspace" }
|
||||
|
||||
@@ -54,6 +54,21 @@ pub(crate) fn bypass_approvals(config: &[AgentConfigOption]) -> bool {
|
||||
.any(|category| selected(category).zip(bypass_value(category)).is_some_and(|(value, bypass)| bypass(value)))
|
||||
}
|
||||
|
||||
/// Canonical snapshot of approval-bearing config options (`mode`, `permissions`, `approval`)
|
||||
/// so auto-resume can refuse to run silently if permission policy drifted while closed.
|
||||
pub(crate) fn approval_fingerprint(config: &[AgentConfigOption]) -> Option<String> {
|
||||
let mut parts: Vec<String> = config
|
||||
.iter()
|
||||
.filter(|o| matches!(o.category.as_deref(), Some("mode" | "permissions" | "approval")))
|
||||
.filter_map(|o| Some(format!("{}={}", o.id, o.current.as_deref()?)))
|
||||
.collect();
|
||||
if parts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
parts.sort();
|
||||
Some(parts.join(";"))
|
||||
}
|
||||
|
||||
/// For an option of `category` that can approve everything, what tells its approving values.
|
||||
fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
|
||||
match category {
|
||||
|
||||
+1321
-162
File diff suppressed because it is too large.
Load diff
@@ -49,6 +49,74 @@ pub struct AgentCapabilities {
|
||||
pub context_usage: bool,
|
||||
}
|
||||
|
||||
/// Why `AgentManager` is shutting down its live tasks.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum AgentShutdownReason {
|
||||
WindowClose,
|
||||
#[default]
|
||||
Quit,
|
||||
Restart,
|
||||
BackendUpgrade,
|
||||
BackendStop,
|
||||
}
|
||||
|
||||
/// Why an in-flight turn stopped before completing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum InterruptionReason {
|
||||
WindowClose,
|
||||
Quit,
|
||||
Restart,
|
||||
BackendUpgrade,
|
||||
BackendStop,
|
||||
UnexpectedExit,
|
||||
NetworkTimeout,
|
||||
}
|
||||
|
||||
impl From<AgentShutdownReason> for InterruptionReason {
|
||||
fn from(reason: AgentShutdownReason) -> Self {
|
||||
match reason {
|
||||
AgentShutdownReason::WindowClose => Self::WindowClose,
|
||||
AgentShutdownReason::Quit => Self::Quit,
|
||||
AgentShutdownReason::Restart => Self::Restart,
|
||||
AgentShutdownReason::BackendUpgrade => Self::BackendUpgrade,
|
||||
AgentShutdownReason::BackendStop => Self::BackendStop,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Recovery metadata recorded when an active turn was interrupted before finishing.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentInterrupted {
|
||||
pub reason: InterruptionReason,
|
||||
pub at_ms: f64,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub was_waiting_for_input: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub approval_mode: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub auto_resume_once: bool,
|
||||
}
|
||||
|
||||
/// Summary returned when reconciling interrupted tasks for a connected project window.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentRecoveryReport {
|
||||
/// Unique identifier of this `AgentManager` process incarnation.
|
||||
pub instance_id: String,
|
||||
/// `true` on the first reconciliation of this `AgentManager` incarnation.
|
||||
pub first_reconcile: bool,
|
||||
/// Task IDs automatically resumed during this reconciliation.
|
||||
pub auto_resumed: Vec<String>,
|
||||
/// Task IDs remaining in `Interrupted` (`Ask to resume`).
|
||||
pub interrupted: Vec<String>,
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Isolation {
|
||||
@@ -117,6 +185,16 @@ pub struct AgentTask {
|
||||
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
|
||||
#[serde(default)]
|
||||
pub stats: Box<AgentSessionStats>,
|
||||
/// Set when the task's last active turn was interrupted (window close, restart, crash, or
|
||||
/// expired network retry window) and has not been resumed or dismissed yet.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub interrupted: Option<Box<AgentInterrupted>>,
|
||||
/// Persisted unseen reply / input / failure state across window closes and remote reattaches.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub unread: bool,
|
||||
/// Per-session recovery / network auto-retry window override in minutes (`0` = Off; `None` = inherit global).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub recovery_window_mins: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -159,6 +237,9 @@ pub struct AgentRetry {
|
||||
/// When the next attempt starts (ms since the epoch).
|
||||
pub retry_at_ms: f64,
|
||||
pub error: Option<String>,
|
||||
/// Set when OpenIDEA holds an active turn in `Waiting for network` until `deadline_ms`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub deadline_ms: Option<f64>,
|
||||
}
|
||||
|
||||
/// Token pricing (Credits per 1M tokens) and context window capacity for one tier.
|
||||
@@ -528,6 +609,9 @@ pub enum AgentEntry {
|
||||
/// Sent into a running turn rather than starting one.
|
||||
#[serde(default)]
|
||||
steered: bool,
|
||||
/// Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn.
|
||||
#[serde(default)]
|
||||
recovery: Option<InterruptionReason>,
|
||||
},
|
||||
Agent {
|
||||
text: String,
|
||||
|
||||
@@ -67,6 +67,8 @@ struct FakeAgent {
|
||||
forks: Mutex<Vec<Value>>,
|
||||
/// The content blocks of each `session/prompt`.
|
||||
prompts: Mutex<Vec<Value>>,
|
||||
/// Queued errors returned on the next `session/prompt` calls before succeeding.
|
||||
prompt_errors: Mutex<VecDeque<(i64, String)>>,
|
||||
}
|
||||
|
||||
impl FakeAgent {
|
||||
@@ -198,7 +200,11 @@ impl Handler for FakeAgent {
|
||||
}
|
||||
"session/new" => {
|
||||
if self.hold_session_new.load(Ordering::Acquire) {
|
||||
std::thread::sleep(Duration::from_secs(5));
|
||||
let peer = self.latest();
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
while !peer.is_closed() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
if self.empty_config.load(Ordering::Acquire) {
|
||||
return Ok(json!({"sessionId": "s1"}));
|
||||
@@ -267,6 +273,9 @@ impl Handler for FakeAgent {
|
||||
}
|
||||
"session/prompt" => {
|
||||
self.prompts.lock().push(params.get("prompt").cloned().unwrap_or(Value::Null));
|
||||
if let Some(err) = self.prompt_errors.lock().pop_front() {
|
||||
return Err(err);
|
||||
}
|
||||
// `!` commands run since the last message come first; the message follows.
|
||||
let first = match params.pointer("/prompt/0/text").and_then(Value::as_str) {
|
||||
Some(t) if t.starts_with("<bash-input>") => 1,
|
||||
@@ -277,6 +286,10 @@ impl Handler for FakeAgent {
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
if text.starts_with("The previous turn was interrupted because ") {
|
||||
self.say(&session, "resumed cleanly");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text.starts_with("<send_user_message_question_reply>") {
|
||||
self.say(&session, "answer received");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
@@ -457,8 +470,9 @@ impl Handler for FakeAgent {
|
||||
return Ok(json!({ "stopReason": "end_turn" }));
|
||||
}
|
||||
if text == "wait" {
|
||||
// Works until cancelled.
|
||||
while !self.calls.lock().iter().any(|c| c == "session/cancel") {
|
||||
// Works until cancelled or the client closes the connection.
|
||||
let peer = self.latest();
|
||||
while !peer.is_closed() && !self.calls.lock().iter().any(|c| c == "session/cancel") {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
return Ok(json!({"stopReason": "cancelled"}));
|
||||
@@ -699,13 +713,27 @@ async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
|
||||
async fn archiving_a_task_keeps_the_permission_answer_that_is_settling() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let shut_down = ShutDown(&mgr);
|
||||
let (published, mut requests) = tokio::sync::mpsc::unbounded_channel();
|
||||
mgr.subscribe_as(
|
||||
"",
|
||||
Arc::new(move |event| {
|
||||
if let AgentEvent::Entry { task, entry: AgentEntry::Permission { id, chosen: None, .. }, .. } = event {
|
||||
let _ = published.send((task, id));
|
||||
}
|
||||
}),
|
||||
);
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
// The status becomes visible before the request has enqueued its initial delivery.
|
||||
let (owner, permission) = tokio::time::timeout(Duration::from_secs(5), requests.recv())
|
||||
.await
|
||||
.expect("permission request was never published")
|
||||
.unwrap();
|
||||
assert_eq!(owner, task.id);
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
let permission = *handle.permissions.lock().keys().next().unwrap();
|
||||
let answered = |e: &AgentEntry| matches!(e, AgentEntry::Permission { chosen: Some(name), .. } if name == "Allow");
|
||||
|
||||
let status_at_answer = tokio::task::block_in_place(|| {
|
||||
@@ -732,7 +760,7 @@ async fn archiving_a_task_keeps_the_permission_answer_that_is_settling() {
|
||||
})
|
||||
.await
|
||||
.expect("the archived turn did not finish");
|
||||
mgr.shutdown();
|
||||
drop(shut_down);
|
||||
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
assert_eq!(restored.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Archived);
|
||||
@@ -1838,6 +1866,184 @@ async fn shutdown_skips_rewriting_untouched_restored_tasks() {
|
||||
assert_eq!(saved_title(&dirty_path).as_deref(), Some("updated"));
|
||||
}
|
||||
|
||||
/// Closing a project while a turn is in flight must not let the killed turn wake up and
|
||||
/// mark the persisted task as `Failed` with "The agent process exited.".
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn shutdown_during_running_turn_does_not_mark_task_failed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
for _ in 0..500 {
|
||||
if agent.calls.lock().iter().any(|c| c == "session/prompt") {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
assert!(agent.calls.lock().iter().any(|c| c == "session/prompt"));
|
||||
|
||||
mgr.shutdown();
|
||||
// Wait past TURN_GRACE so any unguarded Task::run continuation would have settled and failed.
|
||||
tokio::time::sleep(TURN_GRACE * 3).await;
|
||||
|
||||
let path = task_file(tmp.path(), &task.id);
|
||||
assert_eq!(saved_task(&path).map(|(status, _)| status), Some(serde_json::to_value(AgentStatus::Ready).unwrap()));
|
||||
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let restored_task = restored.task(&task.id).unwrap();
|
||||
assert_eq!(restored_task.state.lock().task.status, AgentStatus::Ready);
|
||||
assert_eq!(restored_task.state.lock().task.error, None);
|
||||
let entries = restored.entries(&task.id, None).unwrap();
|
||||
assert!(
|
||||
!entries.iter().any(|e| matches!(e, AgentEntry::Error { .. })),
|
||||
"shutdown must not append an exit error entry: {entries:?}"
|
||||
);
|
||||
assert!(
|
||||
entries.iter().any(|e| matches!(e, AgentEntry::User { text, done_ms: None, .. } if text == "wait")),
|
||||
"interrupted turn must not stamp a bogus completion timestamp: {entries:?}"
|
||||
);
|
||||
|
||||
restored.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&restored, &task.id, AgentStatus::Ready).await;
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
/// Shutting down while `open_session` is still mid-handshake kills the connecting peer
|
||||
/// immediately and leaves the task `Ready` rather than failing or leaking the process.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn shutdown_during_session_open_kills_connecting_peer_without_failing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
agent.hold_session_new.store(true, Ordering::Release);
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
for _ in 0..500 {
|
||||
if agent.calls.lock().iter().any(|c| c == "session/new") {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
assert!(agent.calls.lock().iter().any(|c| c == "session/new"));
|
||||
|
||||
mgr.shutdown();
|
||||
tokio::time::sleep(TURN_GRACE * 3).await;
|
||||
|
||||
assert!(agent.latest().is_closed(), "shutdown must kill the in-flight connecting peer");
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
assert!(handle.live.lock().is_none(), "opening peer must not be published after shutdown");
|
||||
assert_eq!(handle.state.lock().task.status, AgentStatus::Ready);
|
||||
assert_eq!(handle.state.lock().task.error, None);
|
||||
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let restored_task = restored.task(&task.id).unwrap();
|
||||
assert_eq!(restored_task.state.lock().task.status, AgentStatus::Ready);
|
||||
assert_eq!(restored_task.state.lock().task.error, None);
|
||||
let entries = restored.entries(&task.id, None).unwrap();
|
||||
assert!(
|
||||
!entries.iter().any(|e| matches!(e, AgentEntry::Error { .. })),
|
||||
"shutdown during session open must not record an error: {entries:?}"
|
||||
);
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
/// Shutting down while the agent is blocked on a permission prompt settles the pending
|
||||
/// permission as Cancelled and leaves the task `Ready` without an exit error.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn shutdown_during_permission_request_settles_without_failing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("decide"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
|
||||
mgr.shutdown();
|
||||
tokio::time::sleep(TURN_GRACE * 3).await;
|
||||
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let restored_task = restored.task(&task.id).unwrap();
|
||||
assert_eq!(restored_task.state.lock().task.status, AgentStatus::Ready);
|
||||
assert_eq!(restored_task.state.lock().task.error, None);
|
||||
let entries = restored.entries(&task.id, None).unwrap();
|
||||
assert!(
|
||||
!entries.iter().any(|e| matches!(e, AgentEntry::Error { .. })),
|
||||
"shutdown during permission prompt must not append an exit error: {entries:?}"
|
||||
);
|
||||
assert!(
|
||||
entries.iter().any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c == "Cancelled")),
|
||||
"unanswered permission should be settled as Cancelled: {entries:?}"
|
||||
);
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
/// Revoking and restoring project trust calls `shutdown()` on a manager that stays in use;
|
||||
/// interrupting a running turn must leave the manager ready to accept later prompts.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn manager_can_run_new_turns_after_shutdown_replaces_an_interrupted_turn() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
for _ in 0..500 {
|
||||
if agent.calls.lock().iter().any(|c| c == "session/prompt") {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
|
||||
mgr.shutdown();
|
||||
tokio::time::sleep(TURN_GRACE * 3).await;
|
||||
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
assert_eq!(handle.state.lock().task.status, AgentStatus::Ready);
|
||||
assert!(!handle.state.lock().busy);
|
||||
|
||||
mgr.prompt(&task.id, text("again"), false).await.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 == "second turn")),
|
||||
"follow-up turn on the same manager after shutdown should succeed: {entries:?}"
|
||||
);
|
||||
assert!(
|
||||
!entries.iter().any(|e| matches!(e, AgentEntry::Error { .. })),
|
||||
"no stale shutdown error should appear: {entries:?}"
|
||||
);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// Archiving saves the task as it is, including changes nobody asked to be saved.
|
||||
#[tokio::test]
|
||||
async fn archiving_saves_the_task_before_it_returns() {
|
||||
@@ -2814,7 +3020,7 @@ async fn startup_warnings_survive_replay_and_restart_without_failing_the_task()
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
handle.replaying.store(true, Ordering::Release);
|
||||
handle.turn_started.store(false, Ordering::Release);
|
||||
let client = Client::new(&handle, None);
|
||||
let client = Client::new(&handle, handle.shared.shutdown_epoch(), None);
|
||||
client.on_notification(WARNING_NOTIFICATION, json!({"message": "Project MCP config is disabled until trusted."}));
|
||||
client.on_notification(WARNING_NOTIFICATION, json!({"message": " "}));
|
||||
client.on_notification(WARNING_NOTIFICATION, json!({}));
|
||||
@@ -2850,7 +3056,8 @@ async fn persistent_project_trust_needs_confirmation_even_with_bypass() {
|
||||
let asking = {
|
||||
let handle = handle.clone();
|
||||
let params = params.clone();
|
||||
tokio::task::spawn_blocking(move || handle.ask_permission(¶ms))
|
||||
let epoch = handle.shared.shutdown_epoch();
|
||||
tokio::task::spawn_blocking(move || handle.ask_permission(¶ms, epoch))
|
||||
};
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
assert!(!asking.is_finished());
|
||||
@@ -3418,7 +3625,7 @@ fn retry_updates_become_a_countdown() {
|
||||
json!({"sessionUpdate": RETRY_UPDATE, "attempt": 2, "maxRetries": 10, "retryDelayMs": 1500, "error": ""});
|
||||
assert_eq!(
|
||||
retry_of(&update, 1000.0),
|
||||
Some(AgentRetry { attempt: 2, max_retries: Some(10), retry_at_ms: 2500.0, error: None })
|
||||
Some(AgentRetry { attempt: 2, max_retries: Some(10), retry_at_ms: 2500.0, error: None, deadline_ms: None })
|
||||
);
|
||||
assert_eq!(retry_of(&json!({"sessionUpdate": RETRY_UPDATE}), 0.0), None, "no attempt");
|
||||
}
|
||||
@@ -6102,3 +6309,477 @@ async fn workspace_roots_go_to_agents_that_take_them() {
|
||||
assert_eq!(mgr.shared.additional_directories(&takes, &worktree, Some(&api)), vec![web]);
|
||||
assert!(mgr.shared.additional_directories(&init(json!({})), &api, None).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn shutdown_reasons_mark_only_in_flight_tasks_interrupted_and_keep_idle_tasks_clean() {
|
||||
for (shutdown_reason, expected) in [
|
||||
(AgentShutdownReason::WindowClose, InterruptionReason::WindowClose),
|
||||
(AgentShutdownReason::Quit, InterruptionReason::Quit),
|
||||
(AgentShutdownReason::Restart, InterruptionReason::Restart),
|
||||
(AgentShutdownReason::BackendUpgrade, InterruptionReason::BackendUpgrade),
|
||||
(AgentShutdownReason::BackendStop, InterruptionReason::BackendStop),
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let idle = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &idle.id, AgentStatus::Ready).await;
|
||||
mgr.mark_read(&idle.id).unwrap();
|
||||
|
||||
let active = mgr
|
||||
.create(NewAgentTask { prompt: text("wait"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &active.id, AgentStatus::Running).await;
|
||||
|
||||
mgr.shutdown_with(shutdown_reason);
|
||||
|
||||
let reopened = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let tasks = reopened.subscribe_as("", Arc::new(|_| {}));
|
||||
let restored_idle = tasks.iter().find(|t| t.id == idle.id).unwrap();
|
||||
assert_eq!(restored_idle.status, AgentStatus::Ready);
|
||||
assert!(restored_idle.interrupted.is_none(), "idle keepalive task must not become interrupted");
|
||||
assert!(!restored_idle.unread);
|
||||
|
||||
let restored_active = tasks.iter().find(|t| t.id == active.id).unwrap();
|
||||
assert_eq!(restored_active.status, AgentStatus::Ready);
|
||||
assert!(restored_active.unread);
|
||||
let intr = restored_active.interrupted.as_deref().expect("active task marked interrupted");
|
||||
assert_eq!(intr.reason, expected);
|
||||
assert!(!intr.was_waiting_for_input);
|
||||
reopened.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn unexpected_exit_on_disk_tags_interrupted_lazily_without_rewriting_untouched_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let store = tmp.path().join("store");
|
||||
std::fs::create_dir_all(&store).unwrap();
|
||||
let crashed_running = json!({
|
||||
"task": {
|
||||
"id": "crash-run",
|
||||
"title": "Refactor auth",
|
||||
"provider": "claude",
|
||||
"model": "big",
|
||||
"status": "running",
|
||||
"isolation": "local",
|
||||
"cwd": tmp.path(),
|
||||
"branch": null,
|
||||
"base": null,
|
||||
"baseCommit": null,
|
||||
"error": null,
|
||||
"createdMs": 100.0,
|
||||
"updatedMs": 250.0,
|
||||
"config": [{"id": "mode", "name": "Mode", "category": "mode", "current": "ask", "via": "mode", "values": []}],
|
||||
"commands": [],
|
||||
"usage": null,
|
||||
"queue": [],
|
||||
"capabilities": {},
|
||||
"resetsMs": null,
|
||||
"retry": null
|
||||
},
|
||||
"sessionId": "s1",
|
||||
"entries": [
|
||||
{"type": "user", "text": "refactor", "attachments": [], "sentMs": 100.0, "doneMs": null, "steered": false},
|
||||
{"type": "tool", "id": "t1", "title": "cargo check", "kind": "execute", "status": "running", "locations": [], "output": null, "diffs": []}
|
||||
],
|
||||
"wanted": []
|
||||
});
|
||||
let crashed_input = json!({
|
||||
"task": {
|
||||
"id": "crash-input",
|
||||
"title": "Needs approval",
|
||||
"provider": "claude",
|
||||
"model": "big",
|
||||
"status": "needsInput",
|
||||
"isolation": "local",
|
||||
"cwd": tmp.path(),
|
||||
"branch": null,
|
||||
"base": null,
|
||||
"baseCommit": null,
|
||||
"error": null,
|
||||
"createdMs": 100.0,
|
||||
"updatedMs": 300.0,
|
||||
"config": [],
|
||||
"commands": [],
|
||||
"usage": null,
|
||||
"queue": [],
|
||||
"capabilities": {},
|
||||
"resetsMs": null,
|
||||
"retry": null
|
||||
},
|
||||
"sessionId": "s2",
|
||||
"entries": [],
|
||||
"wanted": []
|
||||
});
|
||||
let run_path = store.join("crash-run.json");
|
||||
let input_path = store.join("crash-input.json");
|
||||
let raw_run = serde_json::to_vec(&crashed_running).unwrap();
|
||||
std::fs::write(&run_path, &raw_run).unwrap();
|
||||
std::fs::write(&input_path, serde_json::to_vec(&crashed_input).unwrap()).unwrap();
|
||||
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
// Conversations stay lazy on disk during startup.
|
||||
assert!(!mgr.task("crash-run").unwrap().state.lock().history.is_loaded());
|
||||
let tasks = mgr.subscribe_as("", Arc::new(|_| {}));
|
||||
let r = tasks.iter().find(|t| t.id == "crash-run").unwrap();
|
||||
assert_eq!(r.status, AgentStatus::Ready);
|
||||
assert!(r.unread);
|
||||
assert_eq!(r.interrupted.as_ref().unwrap().reason, InterruptionReason::UnexpectedExit);
|
||||
assert!(!r.interrupted.as_ref().unwrap().was_waiting_for_input);
|
||||
assert_eq!(r.interrupted.as_ref().unwrap().approval_mode.as_deref(), Some("mode=ask"));
|
||||
|
||||
let inp = tasks.iter().find(|t| t.id == "crash-input").unwrap();
|
||||
assert_eq!(inp.interrupted.as_ref().unwrap().reason, InterruptionReason::UnexpectedExit);
|
||||
assert!(inp.interrupted.as_ref().unwrap().was_waiting_for_input);
|
||||
|
||||
// Shutting down without touching the task does not eagerly load or rewrite its conversation file.
|
||||
mgr.shutdown();
|
||||
assert_eq!(std::fs::read(&run_path).unwrap(), raw_run);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn manual_resume_appends_recovery_turn_drains_queue_and_dismiss_clears_state() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("wait"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
// Queue a follow-up message before window close.
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
mgr.shutdown_with(AgentShutdownReason::WindowClose);
|
||||
|
||||
let agent2 = Arc::new(FakeAgent::default());
|
||||
let mgr2 = manager(tmp.path(), agent2.clone());
|
||||
let resumed = mgr2.resume_all_interrupted().unwrap();
|
||||
assert_eq!(resumed, vec![task.id.clone()]);
|
||||
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let snap = mgr2.task(&task.id).unwrap().state.lock().snapshot();
|
||||
assert!(snap.interrupted.is_none());
|
||||
assert!(snap.queue.is_empty(), "queued message drained after continuation turn");
|
||||
let entries = mgr2.entries(&task.id, None).unwrap();
|
||||
assert!(entries.iter().any(|e| matches!(
|
||||
e,
|
||||
AgentEntry::User { steered: false, recovery: Some(InterruptionReason::WindowClose), .. }
|
||||
)));
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "resumed cleanly")));
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "second turn")));
|
||||
|
||||
// Dismissing an interrupted task clears its interrupted & unread state without sending a prompt.
|
||||
let task2 = mgr2
|
||||
.create(NewAgentTask { prompt: text("wait"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr2, &task2.id, AgentStatus::Running).await;
|
||||
mgr2.shutdown_with(AgentShutdownReason::Quit);
|
||||
|
||||
let mgr3 = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
mgr3.dismiss_interrupted(&task2.id).unwrap();
|
||||
let snap2 = mgr3.task(&task2.id).unwrap().state.lock().snapshot();
|
||||
assert!(snap2.interrupted.is_none());
|
||||
assert!(!snap2.unread);
|
||||
mgr3.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn interrupted_during_starting_before_session_new_resumes_original_prompt_without_duplicate() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let slow_agent = Arc::new(FakeAgent::default());
|
||||
slow_agent.hold_session_new.store(true, Ordering::Release);
|
||||
let mgr = manager(tmp.path(), slow_agent);
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Starting).await;
|
||||
mgr.shutdown_with(AgentShutdownReason::Restart);
|
||||
|
||||
let fast_agent = Arc::new(FakeAgent::default());
|
||||
let mgr2 = manager(tmp.path(), fast_agent.clone());
|
||||
mgr2.resume(&task.id).unwrap();
|
||||
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let entries = mgr2.entries(&task.id, None).unwrap();
|
||||
let user_entries: Vec<_> = entries.iter().filter(|e| matches!(e, AgentEntry::User { .. })).collect();
|
||||
assert_eq!(user_entries.len(), 1, "original unsent prompt replayed without duplicating user entries");
|
||||
assert!(matches!(user_entries[0], AgentEntry::User { text, recovery: None, .. } if text == "again"));
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "second turn")));
|
||||
mgr2.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn explicit_user_cancel_settles_to_plain_ready_without_interrupted_marker() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("wait"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let snap = mgr.task(&task.id).unwrap().state.lock().snapshot();
|
||||
assert!(snap.interrupted.is_none());
|
||||
assert!(!snap.unread);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn reconcile_interrupted_enforces_policies_one_shot_flag_and_all_safety_guardrails() {
|
||||
use ide_core::settings::{NetworkRetryWindow, ResumeInterruptedPolicy};
|
||||
|
||||
// 1. Ask policy leaves regular interrupted tasks waiting, except one-shot auto_resume_once.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// Initialize git repo so worktree isolation works cleanly.
|
||||
std::process::Command::new("git").args(["init", "-b", "main"]).current_dir(tmp.path()).output().unwrap();
|
||||
std::fs::write(tmp.path().join("README.md"), "hi\n").unwrap();
|
||||
std::process::Command::new("git").args(["add", "."]).current_dir(tmp.path()).output().unwrap();
|
||||
std::process::Command::new("git")
|
||||
.args(["-c", "user.name=Test", "-c", "[email protected]", "commit", "-m", "init"])
|
||||
.current_dir(tmp.path())
|
||||
.output()
|
||||
.unwrap();
|
||||
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let wt_one_shot = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Worktree,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let wt_manual = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Worktree,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let needs_perm = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("decide"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Worktree,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &wt_one_shot.id, AgentStatus::Running).await;
|
||||
wait_for(&mgr, &wt_manual.id, AgentStatus::Running).await;
|
||||
wait_for(&mgr, &needs_perm.id, AgentStatus::NeedsInput).await;
|
||||
|
||||
// Arm one-shot auto-resume on BOTH wt_one_shot and needs_perm; needs_perm must STILL refuse auto-resume!
|
||||
mgr.set_auto_resume_once(&[wt_one_shot.id.clone(), needs_perm.id.clone()], true);
|
||||
mgr.shutdown_with(AgentShutdownReason::WindowClose);
|
||||
|
||||
let mgr2 = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
mgr2.set_recovery_settings_hook(Arc::new(|| (NetworkRetryWindow::Hour1, ResumeInterruptedPolicy::Ask)));
|
||||
let report = mgr2.reconcile_interrupted();
|
||||
assert!(report.first_reconcile);
|
||||
assert_eq!(report.auto_resumed, vec![wt_one_shot.id.clone()]);
|
||||
assert!(report.interrupted.contains(&wt_manual.id));
|
||||
assert!(report.interrupted.contains(&needs_perm.id), "NeedsInput task must never auto-resume");
|
||||
// Second call on the same AgentManager instance is idempotent.
|
||||
let second = mgr2.reconcile_interrupted();
|
||||
assert!(!second.first_reconcile);
|
||||
assert!(second.auto_resumed.is_empty());
|
||||
wait_for(&mgr2, &wt_one_shot.id, AgentStatus::Ready).await;
|
||||
mgr2.shutdown();
|
||||
|
||||
// 2. Shared Local checkout contention: two interrupted Local tasks sharing cwd refuse auto-resume
|
||||
// even under Window policy, while isolated Worktree tasks auto-resume.
|
||||
let mgr3 = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let local_a = mgr3
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let local_b = mgr3
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr3, &local_a.id, AgentStatus::Running).await;
|
||||
wait_for(&mgr3, &local_b.id, AgentStatus::Running).await;
|
||||
mgr3.shutdown_with(AgentShutdownReason::Restart);
|
||||
|
||||
let mgr4 = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
mgr4.set_recovery_settings_hook(Arc::new(|| (NetworkRetryWindow::Hour1, ResumeInterruptedPolicy::Restart)));
|
||||
let contention_report = mgr4.reconcile_interrupted();
|
||||
assert!(
|
||||
!contention_report.auto_resumed.contains(&local_a.id) && !contention_report.auto_resumed.contains(&local_b.id),
|
||||
"two local tasks sharing a checkout must not race via auto-resume"
|
||||
);
|
||||
assert!(contention_report.interrupted.contains(&local_a.id));
|
||||
assert!(contention_report.interrupted.contains(&local_b.id));
|
||||
|
||||
// 3. Permission-mode drift exclusion: changing approval config blocks silent auto-resume.
|
||||
mgr4.dismiss_interrupted(&local_b.id).unwrap();
|
||||
{
|
||||
let handle = mgr4.task(&local_a.id).unwrap();
|
||||
{
|
||||
let mut s = handle.state.lock();
|
||||
if let Some(mode) = s.task.config.iter_mut().find(|o| o.category.as_deref() == Some("mode")) {
|
||||
mode.current = Some("bypass".into());
|
||||
} else {
|
||||
s.task.config.push(AgentConfigOption {
|
||||
id: "mode".into(),
|
||||
name: "Mode".into(),
|
||||
description: None,
|
||||
category: Some("mode".into()),
|
||||
current: Some("bypass".into()),
|
||||
default_value: None,
|
||||
via: AgentConfigVia::Mode,
|
||||
values: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
handle.persist();
|
||||
}
|
||||
mgr4.shutdown();
|
||||
|
||||
let mgr5 = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
mgr5.set_recovery_settings_hook(Arc::new(|| (NetworkRetryWindow::Hour1, ResumeInterruptedPolicy::Window)));
|
||||
let drift_report = mgr5.reconcile_interrupted();
|
||||
assert!(!drift_report.auto_resumed.contains(&local_a.id), "drifted approval mode must not auto-resume silently");
|
||||
mgr5.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn transient_network_outage_probes_with_zero_prompts_and_auto_resumes_when_online() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
agent.prompt_errors.lock().push_back((codes::INTERNAL_ERROR, "network error: connection reset by peer".into()));
|
||||
|
||||
let online = Arc::new(AtomicBool::new(false));
|
||||
let probe_calls = Arc::new(AtomicU32::new(0));
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
mgr.set_network_probe_delays(40, 80);
|
||||
mgr.set_network_probe({
|
||||
let online = online.clone();
|
||||
let probe_calls = probe_calls.clone();
|
||||
move |_| {
|
||||
probe_calls.fetch_add(1, Ordering::SeqCst);
|
||||
online.load(Ordering::SeqCst)
|
||||
}
|
||||
});
|
||||
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Wait until the task enters `Waiting for network` (`retry.deadline_ms.is_some()`).
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
let snap = mgr.task(&task.id).unwrap().state.lock().snapshot();
|
||||
if snap.retry.as_ref().is_some_and(|r| r.deadline_ms.is_some()) {
|
||||
assert_eq!(snap.status, AgentStatus::Running);
|
||||
assert!(mgr.has_live_work(), "remote daemon must treat network-retry wait as live work");
|
||||
break;
|
||||
}
|
||||
assert!(tokio::time::Instant::now() < deadline, "did not enter network wait: {snap:?}");
|
||||
tokio::time::sleep(Duration::from_millis(15)).await;
|
||||
}
|
||||
|
||||
// Let several offline probes run: zero extra `session/prompt` calls may happen while offline.
|
||||
while probe_calls.load(Ordering::SeqCst) < 2 {
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert_eq!(agent.prompts.lock().len(), 1, "must not spend tokens or send prompts while offline");
|
||||
|
||||
// Restore connectivity and poke network (simulating browser `online` event).
|
||||
online.store(true, Ordering::SeqCst);
|
||||
mgr.poke_network();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let snap = mgr.task(&task.id).unwrap().state.lock().snapshot();
|
||||
assert!(snap.interrupted.is_none());
|
||||
assert!(snap.retry.is_none());
|
||||
assert_eq!(agent.prompts.lock().len(), 2);
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert!(entries.iter().any(|e| matches!(
|
||||
e,
|
||||
AgentEntry::User { steered: false, recovery: Some(InterruptionReason::NetworkTimeout), .. }
|
||||
)));
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "resumed cleanly")));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn network_outage_window_off_or_expired_degrades_to_interrupted_and_auth_errors_fail_fast() {
|
||||
use ide_core::settings::{NetworkRetryWindow, ResumeInterruptedPolicy};
|
||||
|
||||
// 1. Turning per-session recovery window to Off (`Some(0)`) during a network wait degrades immediately to Interrupted.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
agent.prompt_errors.lock().push_back((codes::INTERNAL_ERROR, "ENOTFOUND api.anthropic.com".into()));
|
||||
let mgr = manager(tmp.path(), agent);
|
||||
mgr.set_network_probe_delays(500, 1000);
|
||||
mgr.set_network_probe(|_| false);
|
||||
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
|
||||
while !mgr.task(&task.id).unwrap().state.lock().snapshot().retry.as_ref().is_some_and(|r| r.deadline_ms.is_some()) {
|
||||
assert!(tokio::time::Instant::now() < deadline);
|
||||
tokio::time::sleep(Duration::from_millis(15)).await;
|
||||
}
|
||||
|
||||
mgr.set_recovery_window(&task.id, Some(0)).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let snap = mgr.task(&task.id).unwrap().state.lock().snapshot();
|
||||
assert_eq!(snap.interrupted.as_ref().unwrap().reason, InterruptionReason::NetworkTimeout);
|
||||
|
||||
// 2. Global `NetworkRetryWindow::Off` skips waiting and immediately marks NetworkTimeout Interrupted.
|
||||
let agent2 = Arc::new(FakeAgent::default());
|
||||
agent2.prompt_errors.lock().push_back((codes::INTERNAL_ERROR, "503 Service Unavailable".into()));
|
||||
let mgr2 = manager(tmp.path(), agent2);
|
||||
mgr2.set_recovery_settings_hook(Arc::new(|| (NetworkRetryWindow::Off, ResumeInterruptedPolicy::Ask)));
|
||||
let task2 = mgr2
|
||||
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr2, &task2.id, AgentStatus::Ready).await;
|
||||
let snap2 = mgr2.task(&task2.id).unwrap().state.lock().snapshot();
|
||||
assert_eq!(snap2.interrupted.as_ref().unwrap().reason, InterruptionReason::NetworkTimeout);
|
||||
|
||||
// 3. Non-network 401/400 errors fail fast to Failed without entering network retry.
|
||||
let agent3 = Arc::new(FakeAgent::default());
|
||||
agent3.prompt_errors.lock().push_back((codes::INTERNAL_ERROR, "400 Bad Request: invalid model parameter".into()));
|
||||
let mgr3 = manager(tmp.path(), agent3);
|
||||
let task3 = mgr3
|
||||
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr3, &task3.id, AgentStatus::Failed).await;
|
||||
let snap3 = mgr3.task(&task3.id).unwrap().state.lock().snapshot();
|
||||
assert!(snap3.interrupted.is_none());
|
||||
|
||||
mgr.shutdown();
|
||||
mgr2.shutdown();
|
||||
mgr3.shutdown();
|
||||
}
|
||||
@@ -645,6 +645,7 @@ mod tests {
|
||||
sent_ms: Some(sent),
|
||||
done_ms: None,
|
||||
steered: false,
|
||||
recovery: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0));
|
||||
@@ -666,6 +667,7 @@ mod tests {
|
||||
sent_ms: Some(sent),
|
||||
done_ms: None,
|
||||
steered,
|
||||
recovery: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0, false));
|
||||
|
||||
@@ -29,6 +29,7 @@ pub use up_to_date::{menu_up_to_date, record_menu_build};
|
||||
|
||||
use crate::process::{self, Stream};
|
||||
use crate::{BuildModel, maven};
|
||||
use ide_core::build_jobs::append_default_jobs;
|
||||
use ide_core::settings::CMakeProfile;
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeError, IdeResult, Pos, Range, Severity};
|
||||
use parse::{ColUnit, Format, OutputParser, RawMessage};
|
||||
@@ -420,7 +421,8 @@ fn cargo_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
}
|
||||
|
||||
/// CLion's Build Project for a CMake project: configures the build directory when it has no
|
||||
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild). The directory and
|
||||
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild), one job per
|
||||
/// logical CPU unless the profile's build arguments choose a count. The directory and
|
||||
/// options come from the CMake profile; without one, a configured directory of the project
|
||||
/// (the first by name), else `build`, as the generated run configurations use.
|
||||
fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> Vec<BuildStep> {
|
||||
@@ -458,6 +460,7 @@ fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> V
|
||||
build.args.push("--clean-first".into());
|
||||
}
|
||||
build.args.extend(profile.map(|p| p.build_args.clone()).unwrap_or_default());
|
||||
append_default_jobs(&mut build.args);
|
||||
build.env = env;
|
||||
steps.push(build);
|
||||
steps
|
||||
@@ -1508,14 +1511,15 @@ mod tests {
|
||||
let cm = tmp.path().join("cm");
|
||||
write(&cm, "CMakeLists.txt", "project(app)");
|
||||
let args = |p: &BuildPlan| p.steps.iter().map(|s| s.args.join(" ")).collect::<Vec<_>>();
|
||||
let jobs = format!("-j {}", ide_core::build_jobs::default_jobs());
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::CMake);
|
||||
assert_eq!(
|
||||
args(&p),
|
||||
[
|
||||
"-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON",
|
||||
"--build build --config Debug"
|
||||
"-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned(),
|
||||
format!("--build build --config Debug {jobs}"),
|
||||
],
|
||||
"an unconfigured project is configured first"
|
||||
);
|
||||
@@ -1524,7 +1528,7 @@ mod tests {
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(
|
||||
args(&p),
|
||||
["--build cmake-build-release --config Debug --clean-first"],
|
||||
[format!("--build cmake-build-release --config Debug --clean-first {jobs}")],
|
||||
"a configured directory is reused"
|
||||
);
|
||||
let profile = CMakeProfile {
|
||||
|
||||
@@ -5,8 +5,10 @@
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub const SETTINGS_FILES: &[&str] = &["settings.gradle.kts", "settings.gradle"];
|
||||
pub const BUILD_FILES: &[&str] = &["build.gradle.kts", "build.gradle"];
|
||||
@@ -227,9 +229,41 @@ pub fn build_dir(root: &Path) -> Option<PathBuf> {
|
||||
build_dirs(root).into_iter().next()
|
||||
}
|
||||
|
||||
/// How long [`cached_build_dirs`] reuses a walk. Project roots, content roots and the index
|
||||
/// ask for the builds many times while a project opens; on a network share each walk is
|
||||
/// thousands of round trips. A build file changing in a project calls [`forget_build_dirs`].
|
||||
const BUILD_DIRS_TTL: Duration = Duration::from_secs(30);
|
||||
|
||||
type BuildDirsCache = HashMap<PathBuf, (Instant, Vec<PathBuf>)>;
|
||||
|
||||
static BUILD_DIRS: Mutex<Option<BuildDirsCache>> = Mutex::new(None);
|
||||
|
||||
/// Walks for builds now; the result also refreshes [`cached_build_dirs`].
|
||||
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)
|
||||
let dirs = ide_core::project_roots::discover(root, &markers);
|
||||
let now = Instant::now();
|
||||
let mut guard = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let map = guard.get_or_insert_with(HashMap::new);
|
||||
map.retain(|_, (at, _)| now.duration_since(*at) < BUILD_DIRS_TTL);
|
||||
map.insert(root.to_path_buf(), (now, dirs.clone()));
|
||||
dirs
|
||||
}
|
||||
|
||||
fn cached_build_dirs(root: &Path) -> Vec<PathBuf> {
|
||||
let cached = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(root)).cloned();
|
||||
match cached {
|
||||
Some((at, dirs)) if at.elapsed() < BUILD_DIRS_TTL => dirs,
|
||||
_ => build_dirs(root),
|
||||
}
|
||||
}
|
||||
|
||||
/// Forgets the discovered Gradle builds of `root`, and of folders above or below it
|
||||
/// (after a build or settings script appeared, changed or was removed there).
|
||||
pub fn forget_build_dirs(root: &Path) {
|
||||
if let Some(map) = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
|
||||
map.retain(|dir, _| !dir.starts_with(root) && !root.starts_with(dir));
|
||||
}
|
||||
}
|
||||
|
||||
fn wrapper(dir: &Path) -> String {
|
||||
@@ -506,10 +540,23 @@ pub fn linked_project_key(root: &Path, dir: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Linked build identities without reading their scripts (also used by index hot paths).
|
||||
/// Linked build identities without reading their scripts, as of now (a sync, a build).
|
||||
pub(crate) fn linked_dirs(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
|
||||
linked_dirs_from(root, settings, build_dirs)
|
||||
}
|
||||
|
||||
/// [`linked_dirs`] for hot paths (project and index roots): discovered builds are reused for a while.
|
||||
pub(crate) fn linked_dirs_cached(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
|
||||
linked_dirs_from(root, settings, cached_build_dirs)
|
||||
}
|
||||
|
||||
fn linked_dirs_from(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
discover: fn(&Path) -> Vec<PathBuf>,
|
||||
) -> Vec<String> {
|
||||
match &settings.linked_projects {
|
||||
None => build_dirs(root).iter().map(|dir| rel(root, dir)).collect(),
|
||||
None => discover(root).iter().map(|dir| rel(root, dir)).collect(),
|
||||
Some(dirs) => {
|
||||
let mut out = Vec::new();
|
||||
for dir in dirs {
|
||||
@@ -1047,6 +1094,27 @@ pub(crate) fn has_war_plugin(script: &str) -> bool {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn discovered_builds_are_reused_until_forgotten() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
std::fs::create_dir_all(root.join("a")).unwrap();
|
||||
std::fs::write(root.join("a/settings.gradle"), "").unwrap();
|
||||
assert_eq!(super::cached_build_dirs(root), vec![root.join("a")]);
|
||||
std::fs::create_dir_all(root.join("b")).unwrap();
|
||||
std::fs::write(root.join("b/build.gradle"), "").unwrap();
|
||||
// A walk per call is thousands of round trips on a network share.
|
||||
assert_eq!(super::cached_build_dirs(root), vec![root.join("a")]);
|
||||
super::forget_build_dirs(&root.join("b"));
|
||||
assert_eq!(super::cached_build_dirs(root), vec![root.join("a"), root.join("b")]);
|
||||
// A sync sees a new build at once, and so does every later lookup.
|
||||
std::fs::create_dir_all(root.join("c")).unwrap();
|
||||
std::fs::write(root.join("c/build.gradle"), "").unwrap();
|
||||
let all = vec![root.join("a"), root.join("b"), root.join("c")];
|
||||
assert_eq!(super::build_dirs(root), all);
|
||||
assert_eq!(super::cached_build_dirs(root), all);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_linkage_discovers_all_shallow_builds() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -129,7 +129,7 @@ pub fn gradle_external_roots(
|
||||
cache_dir: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
) -> Vec<PathBuf> {
|
||||
let builds = gradle::linked_dirs(root, settings);
|
||||
let builds = gradle::linked_dirs_cached(root, settings);
|
||||
let dirs: Vec<String> = builds
|
||||
.iter()
|
||||
.flat_map(|dir| {
|
||||
@@ -171,7 +171,7 @@ pub fn gradle_source_roots(
|
||||
cache_dir: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
) -> Vec<(PathBuf, gradle::ReportedRoot, PathBuf)> {
|
||||
let reported = gradle::linked_dirs(root, settings)
|
||||
let reported = gradle::linked_dirs_cached(root, settings)
|
||||
.iter()
|
||||
.flat_map(|dir| sync::reported_gradle_projects(&gradle::cache_dir(cache_dir, dir)).as_ref().clone())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -27,4 +27,4 @@ libc = "0.2"
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
dirs.workspace = true
|
||||
tracing.workspace = true
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Parallelism for build tools whose default is one compiler process at a time.
|
||||
//!
|
||||
//! `cmake --build` with a Makefile generator (the default) compiles one file at a
|
||||
//! time unless it is given `-j N`; the IDE asks for one job per logical CPU. A count
|
||||
//! the user wrote into the build arguments is left alone.
|
||||
|
||||
/// Jobs a native build tool gets when the user did not choose a count.
|
||||
pub fn default_jobs() -> usize {
|
||||
std::thread::available_parallelism().map_or(1, |jobs| jobs.get())
|
||||
}
|
||||
|
||||
/// Appends `-j <jobs>` unless `args` already carries the user's own count. The count
|
||||
/// goes before a `--` separator, so cmake's own options stay cmake's and the native
|
||||
/// build tool's options stay last.
|
||||
pub fn append_default_jobs(args: &mut Vec<String>) {
|
||||
if args.iter().any(|arg| is_jobs_flag(arg)) {
|
||||
return;
|
||||
}
|
||||
let jobs = default_jobs().to_string();
|
||||
let at = args.iter().position(|arg| arg == "--").unwrap_or(args.len());
|
||||
args.splice(at..at, ["-j".to_owned(), jobs]);
|
||||
}
|
||||
|
||||
/// `-j`, `-j8`, `--parallel`, `--parallel=8`, `--jobs`, `--jobs=8`.
|
||||
fn is_jobs_flag(arg: &str) -> bool {
|
||||
let count = |rest: &str| rest.chars().all(|c| c.is_ascii_digit());
|
||||
arg.strip_prefix("-j").is_some_and(count)
|
||||
|| arg.strip_prefix("--parallel=").is_some_and(count)
|
||||
|| arg.strip_prefix("--jobs=").is_some_and(count)
|
||||
|| arg == "--parallel"
|
||||
|| arg == "--jobs"
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn args_of(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).to_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_is_one_job_per_logical_cpu() {
|
||||
let expected = std::thread::available_parallelism().map_or(1, |jobs| jobs.get());
|
||||
assert_eq!(default_jobs(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_build_without_a_count_gets_one() {
|
||||
let mut argv = args_of(&["--build", "build", "--config", "Debug"]);
|
||||
append_default_jobs(&mut argv);
|
||||
assert_eq!(argv, args_of(&["--build", "build", "--config", "Debug", "-j", &default_jobs().to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_count_the_user_chose_is_left_alone() {
|
||||
let own: [&[&str]; 6] =
|
||||
[&["-j", "2"], &["-j8"], &["-j", "2"], &["--parallel", "2"], &["--parallel=2"], &["--jobs=2"]];
|
||||
for flags in own {
|
||||
let mut argv = args_of(&["--build", "build"]);
|
||||
argv.extend(flags.iter().map(|value| (*value).to_owned()));
|
||||
let expected = argv.clone();
|
||||
append_default_jobs(&mut argv);
|
||||
assert_eq!(argv, expected, "the build arguments set the count");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_count_stays_before_native_build_tool_options() {
|
||||
let mut argv = args_of(&["--build", "build", "--", "VERBOSE=1"]);
|
||||
append_default_jobs(&mut argv);
|
||||
assert_eq!(argv, args_of(&["--build", "build", "-j", &default_jobs().to_string(), "--", "VERBOSE=1"]));
|
||||
}
|
||||
}
|
||||
@@ -302,6 +302,12 @@ pub struct SmartKeysSettings {
|
||||
pub simultaneous_tag_editing: bool,
|
||||
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
|
||||
pub reformat_on_paste: String,
|
||||
/// Advanced Settings: Copy/Cut without a selection copies the whole caret lines.
|
||||
pub copy_line_when_no_selection: bool,
|
||||
/// Advanced Settings: Copy selects the lines copied without a selection.
|
||||
pub select_copied_line: bool,
|
||||
/// Advanced Settings: linewise paste `above` the caret | `caret` | `trim` at mid-line.
|
||||
pub line_paste_mode: String,
|
||||
pub escape_on_paste: bool,
|
||||
pub smart_indent: bool,
|
||||
/// Enter › Insert documentation comment stub: Enter after `/**` closes the comment.
|
||||
@@ -322,6 +328,9 @@ impl Default for SmartKeysSettings {
|
||||
semicolon_at_statement_end: true,
|
||||
simultaneous_tag_editing: true,
|
||||
reformat_on_paste: "indentEachLine".into(),
|
||||
copy_line_when_no_selection: true,
|
||||
select_copied_line: true,
|
||||
line_paste_mode: "above".into(),
|
||||
escape_on_paste: true,
|
||||
smart_indent: true,
|
||||
insert_doc_stub: true,
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! feature crates depend on `ide-core` and never on each other's internals.
|
||||
//! All IPC-facing types derive `specta::Type`, which generates `src/bindings.ts`.
|
||||
|
||||
pub mod build_jobs;
|
||||
pub mod cli_process;
|
||||
pub mod editor_settings;
|
||||
pub mod error;
|
||||
@@ -18,6 +19,7 @@ pub mod ipc_path;
|
||||
pub mod java_runtime;
|
||||
pub mod jsonc;
|
||||
pub mod memory;
|
||||
pub mod network_path;
|
||||
pub mod output_encoding;
|
||||
pub mod output_rate;
|
||||
pub mod platform;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Whether a path is on a network file system, where every stat is a round trip to a server.
|
||||
|
||||
use std::path::{Component, Path, Prefix};
|
||||
|
||||
/// A UNC path (`\\server\share`, `\\wsl.localhost\…`) or a drive letter mapped to a network
|
||||
/// share (`Z:\`). Always `false` off Windows: there a mount point is not visible in the path.
|
||||
pub fn is_network_path(path: &Path) -> bool {
|
||||
match path.components().next() {
|
||||
Some(Component::Prefix(prefix)) => match prefix.kind() {
|
||||
Prefix::UNC(..) | Prefix::VerbatimUNC(..) => true,
|
||||
Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => is_remote_drive(letter),
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn is_remote_drive(letter: u8) -> bool {
|
||||
use windows_sys::Win32::Storage::FileSystem::GetDriveTypeW;
|
||||
/// `DRIVE_REMOTE` (WindowsProgramming).
|
||||
const DRIVE_REMOTE: u32 = 4;
|
||||
let root = [u16::from(letter), u16::from(b':'), u16::from(b'\\'), 0];
|
||||
// SAFETY: `root` is a NUL-terminated wide string that outlives the call.
|
||||
unsafe { GetDriveTypeW(root.as_ptr()) == DRIVE_REMOTE }
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn is_remote_drive(_letter: u8) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::is_network_path;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn unc_paths_are_on_the_network() {
|
||||
if cfg!(windows) {
|
||||
assert!(is_network_path(Path::new(r"\\server\share\repo")));
|
||||
assert!(is_network_path(Path::new(r"\\?\UNC\server\share\repo")));
|
||||
assert!(is_network_path(Path::new(r"\\wsl.localhost\Ubuntu\home")));
|
||||
}
|
||||
assert!(!is_network_path(Path::new("relative/path")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_local_directory_is_not() {
|
||||
let dir = std::env::temp_dir();
|
||||
assert!(!is_network_path(&dir), "{}", dir.display());
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,8 @@ pub struct Settings {
|
||||
/// Per language server, by name (`rust-analyzer`): launch and protocol
|
||||
/// options on top of the language definition, or a server defined here.
|
||||
pub language_servers: BTreeMap<String, LanguageServerSettings>,
|
||||
/// Languages & Frameworks › JSON Schema Mappings: schemas for JSON and YAML files.
|
||||
pub json_schemas: Vec<JsonSchemaMapping>,
|
||||
/// Tools › Download sources: a mirror prefix for the release archives the installer fetches.
|
||||
pub tool_downloads: ToolDownloadSettings,
|
||||
/// Editor › Inspections profiles.
|
||||
@@ -78,6 +80,8 @@ pub struct Settings {
|
||||
pub file_colors: FileColorSettings,
|
||||
/// Database › Query Execution, Languages & Frameworks › SQL Resolution Scopes.
|
||||
pub database: DatabaseSettings,
|
||||
/// Settings › Settings Sync (global only, never synced itself).
|
||||
pub settings_sync: SettingsSyncSettings,
|
||||
/// Plugin settings (`[contributes.settings]`): plugin id → its values by key.
|
||||
#[specta(type = BTreeMap<String, BTreeMap<String, specta_typescript::Unknown>>)]
|
||||
pub plugins: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
|
||||
@@ -134,6 +138,19 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = NewTaskApprovals)]
|
||||
pub new_task_approvals: NewTaskApprovals,
|
||||
/// How long an in-flight turn hit by a transient network outage waits and probes for
|
||||
/// connectivity before degrading to a manual Resume prompt.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = NetworkRetryWindow)]
|
||||
pub network_retry_window: NetworkRetryWindow,
|
||||
/// What opening a project does with tasks interrupted when OpenIDEA closed or restarted.
|
||||
/// User settings only.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = ResumeInterruptedPolicy)]
|
||||
pub resume_interrupted: ResumeInterruptedPolicy,
|
||||
/// Warn before closing a local window whose project still has running agent tasks.
|
||||
/// User settings only.
|
||||
pub confirm_terminate_on_close: bool,
|
||||
/// Settings new tasks of an agent start with: agent id → option id → value.
|
||||
#[serde(deserialize_with = "agent_defaults")]
|
||||
#[specta(type = BTreeMap<String, BTreeMap<String, String>>)]
|
||||
@@ -173,6 +190,9 @@ impl Default for AgentSettings {
|
||||
send_with: SendKey::Enter,
|
||||
while_running: WhileRunning::Queue,
|
||||
new_task_approvals: NewTaskApprovals::Bypass,
|
||||
network_retry_window: NetworkRetryWindow::Hour1,
|
||||
resume_interrupted: ResumeInterruptedPolicy::Ask,
|
||||
confirm_terminate_on_close: true,
|
||||
defaults: BTreeMap::new(),
|
||||
mcp_servers: BTreeMap::new(),
|
||||
skills: BTreeMap::new(),
|
||||
@@ -360,6 +380,49 @@ pub enum NewTaskApprovals {
|
||||
Ask,
|
||||
}
|
||||
|
||||
/// Default auto-retry window for transient network outages during an active agent turn.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub enum NetworkRetryWindow {
|
||||
#[serde(rename = "off")]
|
||||
Off,
|
||||
#[serde(rename = "15m")]
|
||||
Minutes15,
|
||||
#[default]
|
||||
#[serde(rename = "1h")]
|
||||
Hour1,
|
||||
#[serde(rename = "4h")]
|
||||
Hours4,
|
||||
#[serde(rename = "24h")]
|
||||
Hours24,
|
||||
}
|
||||
|
||||
impl NetworkRetryWindow {
|
||||
pub fn minutes(self) -> u32 {
|
||||
match self {
|
||||
Self::Off => 0,
|
||||
Self::Minutes15 => 15,
|
||||
Self::Hour1 => 60,
|
||||
Self::Hours4 => 240,
|
||||
Self::Hours24 => 1440,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How interrupted agent tasks are handled when a project reopens.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ResumeInterruptedPolicy {
|
||||
/// Show Interrupted markers, banner and balloon; wait for the user to click Resume.
|
||||
#[default]
|
||||
Ask,
|
||||
/// Auto-resume tasks interrupted by an IDE restart or backend upgrade within 15 minutes.
|
||||
Restart,
|
||||
/// Auto-resume tasks interrupted by close, quit or restart within the session recovery window.
|
||||
Window,
|
||||
/// Settle quietly to Ready with no Interrupted markers or balloons.
|
||||
Off,
|
||||
}
|
||||
|
||||
/// Which folders without an open window the MCP server still serves tools for.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -462,6 +525,47 @@ pub struct ToolDownloadSettings {
|
||||
pub configured_registries_only: bool,
|
||||
}
|
||||
|
||||
/// Settings › Settings Sync: the Git repository the IDE settings sync through, and what syncs.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct SettingsSyncSettings {
|
||||
/// Clone URL (a secret GitHub Gist's works too, though anyone with its link can read it);
|
||||
/// empty = sync off.
|
||||
pub repository: String,
|
||||
/// Sync on startup and after the settings change, besides Sync Now.
|
||||
pub auto: bool,
|
||||
pub appearance: bool,
|
||||
/// Editor settings, color schemes, code style, inspections and spelling.
|
||||
pub editor: bool,
|
||||
pub keymaps: bool,
|
||||
/// Every other setting that is not machine-specific.
|
||||
pub other: bool,
|
||||
/// Live, file and postfix templates.
|
||||
pub templates: bool,
|
||||
pub macros: bool,
|
||||
/// Tool window layouts and view options.
|
||||
pub ui: bool,
|
||||
/// The list of installed plugins: missing ones are offered, never installed or removed.
|
||||
pub plugins: bool,
|
||||
}
|
||||
|
||||
impl Default for SettingsSyncSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
repository: String::new(),
|
||||
auto: true,
|
||||
appearance: true,
|
||||
editor: true,
|
||||
keymaps: true,
|
||||
other: true,
|
||||
templates: true,
|
||||
macros: true,
|
||||
ui: true,
|
||||
plugins: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Absent profiles retain automatic discovery for existing projects.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -613,8 +717,10 @@ impl Default for Settings {
|
||||
mcp_server: McpServerSettings::default(),
|
||||
agent_security: AgentSecuritySettings::default(),
|
||||
scopes: Vec::new(),
|
||||
json_schemas: Vec::new(),
|
||||
file_colors: FileColorSettings::default(),
|
||||
database: DatabaseSettings::default(),
|
||||
settings_sync: SettingsSyncSettings::default(),
|
||||
plugins: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
@@ -634,6 +740,17 @@ pub struct NamedScope {
|
||||
pub pattern: String,
|
||||
}
|
||||
|
||||
/// A schema for the JSON and YAML files matching `files`; wins over a built-in SchemaStore mapping.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct JsonSchemaMapping {
|
||||
pub name: String,
|
||||
/// A URL, or a file path relative to the project.
|
||||
pub schema: String,
|
||||
/// Project-relative paths or glob patterns (`config/*.json`, `**/*.app.yaml`).
|
||||
pub files: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct FileColorSettings {
|
||||
@@ -882,6 +999,8 @@ pub struct AppearanceSettings {
|
||||
pub widescreen_tool_windows: bool,
|
||||
/// Each tool window keeps its own size; off, the windows of a side share one.
|
||||
pub remember_tool_window_sizes: bool,
|
||||
/// Tool window shortcuts hide an open unfocused window right away instead of focusing it first.
|
||||
pub toggle_tool_windows_on_shortcut: bool,
|
||||
/// View › Appearance › Toolbar; hidden leaves IDEA's compact window header.
|
||||
pub show_main_toolbar: bool,
|
||||
pub show_status_bar: bool,
|
||||
@@ -1016,6 +1135,7 @@ impl Default for AppearanceSettings {
|
||||
show_tool_window_badges: true,
|
||||
widescreen_tool_windows: false,
|
||||
remember_tool_window_sizes: false,
|
||||
toggle_tool_windows_on_shortcut: false,
|
||||
show_main_toolbar: true,
|
||||
show_status_bar: true,
|
||||
navigation_bar: NavigationBarPosition::StatusBar,
|
||||
@@ -2002,6 +2122,19 @@ mod tests {
|
||||
assert_eq!(json["appearance"]["smoothScrolling"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn database_output_destination_defaults_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"database":{"inEditorResults":true}}"#).unwrap();
|
||||
assert_eq!(old.database.output_destination, DatabaseOutputDestination::DatabaseOutput);
|
||||
assert!(old.database.in_editor_results);
|
||||
|
||||
let services: Settings = serde_json::from_str(r#"{"database":{"outputDestination":"services"}}"#).unwrap();
|
||||
assert_eq!(services.database.output_destination, DatabaseOutputDestination::Services);
|
||||
let saved = serde_json::to_value(&services).unwrap();
|
||||
assert_eq!(saved["database"]["outputDestination"], "services");
|
||||
assert_eq!(serde_json::from_value::<Settings>(saved).unwrap().database, services.database);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_close_settings_default_off_and_round_trip() {
|
||||
for old in [r#"{}"#, r#"{"general":{"confirmExit":false}}"#] {
|
||||
@@ -2163,6 +2296,21 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_tool_windows_on_shortcut_defaults_off_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"showToolWindowNames":true}}"#).unwrap();
|
||||
assert!(!old.appearance.toggle_tool_windows_on_shortcut);
|
||||
assert!(!Settings::default().appearance.toggle_tool_windows_on_shortcut);
|
||||
for enabled in [true, false] {
|
||||
let mut settings = Settings::default();
|
||||
settings.appearance.toggle_tool_windows_on_shortcut = enabled;
|
||||
let json = serde_json::to_value(&settings).unwrap();
|
||||
assert_eq!(json["appearance"]["toggleToolWindowsOnShortcut"], enabled);
|
||||
let restored: Settings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(restored.appearance.toggle_tool_windows_on_shortcut, enabled);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_click_opens_diff_is_unset_by_default_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"vcs":{"commit":{"nonModal":true}}}"#).unwrap();
|
||||
|
||||
@@ -405,13 +405,24 @@ impl Default for LogLevelColors {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct DatabaseSettings {
|
||||
/// A console's result sets show under the statements that produced them, in the editor,
|
||||
/// instead of in the Services view's result tabs.
|
||||
/// instead of in the output window's result tabs.
|
||||
pub in_editor_results: bool,
|
||||
/// The tool window that receives SQL query output and plans.
|
||||
pub output_destination: DatabaseOutputDestination,
|
||||
/// Languages & Frameworks › SQL Resolution Scopes: the data source SQL in a file or folder
|
||||
/// resolves against (completion, inspections, navigation), most specific path first.
|
||||
pub resolution_scopes: Vec<SqlResolutionScope>,
|
||||
}
|
||||
|
||||
/// Database › Query Output: where SQL results open.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DatabaseOutputDestination {
|
||||
#[default]
|
||||
DatabaseOutput,
|
||||
Services,
|
||||
}
|
||||
|
||||
/// One row of SQL Resolution Scopes.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -606,6 +617,8 @@ pub struct TerminalSettings {
|
||||
pub shell_integration: bool,
|
||||
pub highlight_hyperlinks: bool,
|
||||
pub highlight_selection: bool,
|
||||
/// Highlights typed commands the IDE recognises; Run Highlighted Command runs them with it.
|
||||
pub run_commands_using_ide: bool,
|
||||
pub option_as_meta: bool,
|
||||
/// Escape moves focus to the editor instead of reaching the shell.
|
||||
pub escape_to_editor: bool,
|
||||
@@ -642,6 +655,7 @@ impl Default for TerminalSettings {
|
||||
shell_integration: true,
|
||||
highlight_hyperlinks: true,
|
||||
highlight_selection: true,
|
||||
run_commands_using_ide: true,
|
||||
option_as_meta: false,
|
||||
escape_to_editor: false,
|
||||
cursor_shape: "block".into(),
|
||||
|
||||
@@ -24,7 +24,7 @@ mod session;
|
||||
mod stream_trace;
|
||||
pub mod unity;
|
||||
|
||||
use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
use adapter::{AdapterIo, AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
use connection::{Connection, DapError};
|
||||
pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport};
|
||||
use futures::future::join_all;
|
||||
@@ -45,6 +45,11 @@ use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
pub use stream_trace::{TracePhase, TraceProgress, TraceRun, TraceUnavailable};
|
||||
|
||||
/// The adapter name of a notebook kernel's own debugger (see [`DebugManager::start_over`]).
|
||||
pub const NOTEBOOK_ADAPTER: &str = "jupyter-kernel";
|
||||
/// How a notebook cell's breakpoints are keyed: `vscode-notebook-cell:<notebook>#<cell>`.
|
||||
pub const NOTEBOOK_CELL_SCHEME: &str = "vscode-notebook-cell:";
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LaunchConfig {
|
||||
@@ -1078,6 +1083,51 @@ impl DebugManager {
|
||||
port,
|
||||
exception_classes,
|
||||
cancel,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Starts an `attach` session named `name` over `io`: a debugger reached without an
|
||||
/// adapter process, such as a notebook kernel's over its control channel
|
||||
/// ([`NOTEBOOK_ADAPTER`]). `arguments` is the `attach` request's. `notebook_cells`, the
|
||||
/// prefix of a notebook's cell URIs, gives the session that notebook's cell breakpoints.
|
||||
pub async fn start_over(
|
||||
&self,
|
||||
io: AdapterIo,
|
||||
name: String,
|
||||
adapter: String,
|
||||
arguments: Value,
|
||||
owner: SessionOwner,
|
||||
notebook_cells: Option<String>,
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
let spec = AdapterSpec {
|
||||
adapter: adapter.clone(),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
transport: adapter::Transport::Stdio,
|
||||
install_hint: None,
|
||||
cwd: PathBuf::new(),
|
||||
env: Vec::new(),
|
||||
server_host: None,
|
||||
connect: None,
|
||||
pinned: None,
|
||||
resolve_lazy_variables: false,
|
||||
};
|
||||
let cancel = ide_core::CancellationToken::new();
|
||||
self.start_session(
|
||||
DebugSessionId::next(),
|
||||
owner,
|
||||
name,
|
||||
adapter,
|
||||
None,
|
||||
"attach".into(),
|
||||
arguments,
|
||||
spec,
|
||||
None,
|
||||
None,
|
||||
cancel,
|
||||
Some((io, notebook_cells)),
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -1113,6 +1163,7 @@ impl DebugManager {
|
||||
port,
|
||||
None,
|
||||
ide_core::CancellationToken::new(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
@@ -1132,6 +1183,7 @@ impl DebugManager {
|
||||
reuse_port: Option<u16>,
|
||||
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
cancel: ide_core::CancellationToken,
|
||||
connected: Option<(AdapterIo, Option<String>)>,
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
if request != "launch" && request != "attach" {
|
||||
return Err(IdeError::invalid(format!("request must be `launch` or `attach`, got `{request}`")));
|
||||
@@ -1139,10 +1191,16 @@ impl DebugManager {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let io = tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
io = self.launcher.launch(spec.clone(), reuse_port) => io?,
|
||||
let (io, notebook_cells) = match connected {
|
||||
Some((io, cells)) => (io, cells),
|
||||
None => (
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
io = self.launcher.launch(spec.clone(), reuse_port) => io?,
|
||||
},
|
||||
None,
|
||||
),
|
||||
};
|
||||
let launch_after_configuration = io.launch_after_configuration && request == "launch";
|
||||
let stderr = io.stderr.clone();
|
||||
@@ -1155,6 +1213,7 @@ impl DebugManager {
|
||||
.flatten();
|
||||
let mut session = Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child);
|
||||
session.exception_classes = exception_classes;
|
||||
session.notebook_cells = notebook_cells;
|
||||
session.run = take_run_link(&mut arguments);
|
||||
let session = Arc::new(session);
|
||||
if let Some(launch_type) = arguments.get("type").and_then(Value::as_str) {
|
||||
@@ -1378,6 +1437,7 @@ impl DebugManager {
|
||||
.map(|b| b.lines.iter().map(|(p, b)| (p.clone(), b.clone())).collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|(path, _)| s.takes(path))
|
||||
.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.
|
||||
@@ -1607,7 +1667,7 @@ impl DebugManager {
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
let mut result: Option<Vec<BreakpointState>> = None;
|
||||
for s in self.configured_sessions(owner) {
|
||||
for s in self.configured_sessions(owner).into_iter().filter(|s| s.takes(&path)) {
|
||||
match s.send_breakpoints(&path, &breakpoints, None).await {
|
||||
Ok(states) => {
|
||||
result.get_or_insert(states);
|
||||
|
||||
@@ -125,6 +125,8 @@ pub(crate) struct Session {
|
||||
pub stream_tracer: parking_lot::Mutex<Option<Arc<dyn ide_jvm_inspect::StreamTracer>>>,
|
||||
/// Given at start: the class breakpoints must be armed before `configurationDone`.
|
||||
pub(crate) exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
/// A notebook kernel's session: the prefix of its notebook's cell URIs (`…/a.ipynb#`).
|
||||
pub(crate) notebook_cells: Option<String>,
|
||||
/// Held from `setExceptionBreakpoints`, which drops the class breakpoints, until they are
|
||||
/// armed again, so that the last list armed is the manager's.
|
||||
pub(crate) exception_turn: tokio::sync::Mutex<()>,
|
||||
@@ -342,6 +344,7 @@ impl Session {
|
||||
run: None,
|
||||
stream_tracer: parking_lot::Mutex::new(None),
|
||||
exception_classes: None,
|
||||
notebook_cells: None,
|
||||
exception_turn: tokio::sync::Mutex::default(),
|
||||
stream_trace: parking_lot::Mutex::new(None),
|
||||
stream_trace_done: parking_lot::Mutex::new(None),
|
||||
@@ -425,6 +428,14 @@ impl Session {
|
||||
|
||||
/// Sends the breakpoints of one file (disabled ones omitted, plus an optional
|
||||
/// temporary line) and returns verification states aligned with `breakpoints`.
|
||||
/// Whether this session gets the breakpoints of `path`: a notebook cell's go only to the
|
||||
/// session of that notebook's kernel, which knows the cell's code.
|
||||
pub(crate) fn takes(&self, path: &Path) -> bool {
|
||||
let path = path.to_string_lossy();
|
||||
!path.starts_with(crate::NOTEBOOK_CELL_SCHEME)
|
||||
|| self.notebook_cells.as_deref().is_some_and(|cells| path.starts_with(cells))
|
||||
}
|
||||
|
||||
pub async fn send_breakpoints(
|
||||
&self,
|
||||
path: &Path,
|
||||
|
||||
@@ -3791,3 +3791,19 @@ async fn stop_detaches_from_an_attached_program() {
|
||||
assert!(!h.commands().contains(&"terminate".to_owned()));
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cell_breakpoints_go_only_to_their_notebooks_kernel_session() {
|
||||
use crate::jvm_memory::test_support::bare_session_of;
|
||||
use std::path::Path;
|
||||
let (a, b) = ("vscode-notebook-cell:/p/a.ipynb#c1", "vscode-notebook-cell:/p/b.ipynb#c1");
|
||||
let mut kernel = bare_session_of(crate::NOTEBOOK_ADAPTER, "attach");
|
||||
std::sync::Arc::get_mut(&mut kernel.session).unwrap().notebook_cells =
|
||||
Some("vscode-notebook-cell:/p/a.ipynb#".into());
|
||||
let python = bare_session_of("debugpy", "launch");
|
||||
assert!(kernel.session.takes(Path::new(a)));
|
||||
assert!(!kernel.session.takes(Path::new(b)), "another notebook's cells");
|
||||
assert!(kernel.session.takes(Path::new("/p/lib.py")), "files the cells may call");
|
||||
assert!(!python.session.takes(Path::new(a)));
|
||||
assert!(python.session.takes(Path::new("/p/lib.py")));
|
||||
}
|
||||
@@ -426,6 +426,8 @@ impl JdbcPool {
|
||||
self.request(&["page", sql, &offset.to_string(), &limit.min(i32::MAX as u64).to_string()], sql, cancel).await
|
||||
}
|
||||
|
||||
/// Introspection on this connection. `catalogs` lists live catalogs with the current one marked.
|
||||
/// `schemas`, `tables`, `schemaColumns`, and `columns` accept a final catalog argument.
|
||||
pub(crate) async fn metadata(&self, fields: &[&str]) -> IdeResult<Vec<Vec<Option<String>>>> {
|
||||
Ok(self.request(fields, "", &CancellationToken::new()).await?.rows)
|
||||
}
|
||||
@@ -706,6 +708,86 @@ mod tests {
|
||||
assert_eq!(by_table.len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
|
||||
async fn duckdb_live_catalog_metadata_is_scoped_to_the_requested_namespace() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let source = DataSource { url: "jdbc:duckdb:".into(), ..Default::default() };
|
||||
let driver = DbJdbcDriver {
|
||||
id: "duckdb".into(),
|
||||
name: "DuckDB".into(),
|
||||
vendor: None,
|
||||
jars: vec![std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR")],
|
||||
class_name: "org.duckdb.DuckDBDriver".into(),
|
||||
url_template: String::new(),
|
||||
};
|
||||
let pool = JdbcPool::connect(&source, None, driver, tmp.path().join("jdbc")).await?;
|
||||
let stop = CancellationToken::new();
|
||||
let path = |file| tmp.path().join(file).to_string_lossy().replace('\'', "''");
|
||||
let archive = "archive.db:1";
|
||||
for sql in [
|
||||
"SET threads = 1".into(),
|
||||
"CREATE TABLE memory.main.dupe (root_only INT)".into(),
|
||||
format!("ATTACH '{}' AS first", path("first.duckdb")),
|
||||
format!(r#"ATTACH '{}' AS "archive.db:1""#, path("archive.duckdb")),
|
||||
"CREATE TABLE first.main.dupe (first_only INT PRIMARY KEY)".into(),
|
||||
r#"CREATE TABLE "archive.db:1".main.dupe (archive_only INT)"#.into(),
|
||||
r#"CREATE SCHEMA "archive.db:1"."qa_%""#.into(),
|
||||
r#"CREATE SCHEMA "archive.db:1".qaSimilar"#.into(),
|
||||
r#"CREATE TABLE "archive.db:1"."qa_%"."t_%""q" (quoted_only INT PRIMARY KEY)"#.into(),
|
||||
r#"COMMENT ON TABLE "archive.db:1"."qa_%"."t_%""q" IS 'Archive table'"#.into(),
|
||||
r#"COMMENT ON COLUMN "archive.db:1"."qa_%"."t_%""q".quoted_only IS 'In the archive'"#.into(),
|
||||
r#"CREATE TABLE "archive.db:1".qaSimilar."t_%""q" (wrong_schema INT)"#.into(),
|
||||
r#"COMMENT ON TABLE "archive.db:1".qaSimilar."t_%""q" IS 'Wrong schema table'"#.into(),
|
||||
r#"COMMENT ON COLUMN "archive.db:1".qaSimilar."t_%""q".wrong_schema IS 'Outside the schema'"#.into(),
|
||||
] {
|
||||
pool.query(&sql, 0, 1, &stop).await?;
|
||||
}
|
||||
|
||||
let catalogs = pool.metadata(&["catalogs"]).await?;
|
||||
assert!(catalogs.contains(&vec![Some("memory".into()), Some("1".into())]));
|
||||
assert!(catalogs.contains(&vec![Some("first".into()), Some("0".into())]));
|
||||
assert!(catalogs.contains(&vec![Some(archive.into()), Some("0".into())]));
|
||||
let schemas = pool.metadata(&["schemas", archive]).await?;
|
||||
assert_eq!(schemas, ["main", "qaSimilar", "qa_%"].map(|schema| vec![Some(schema.into())]));
|
||||
let tables = pool.metadata(&["tables", "qa_%", archive]).await?;
|
||||
assert_eq!(tables.len(), 1);
|
||||
assert_eq!(tables[0][0].as_deref(), Some(r#"t_%"q"#));
|
||||
assert_eq!(tables[0][2].as_deref(), Some("Archive table"));
|
||||
|
||||
for (catalog, column, primary) in
|
||||
[("memory", "root_only", "0"), ("first", "first_only", "1"), (archive, "archive_only", "0")]
|
||||
{
|
||||
let columns = pool.metadata(&["columns", "main", "dupe", catalog]).await?;
|
||||
assert_eq!(columns.len(), 1);
|
||||
assert_eq!(columns[0][0].as_deref(), Some(column));
|
||||
assert_eq!(columns[0][4].as_deref(), Some(primary));
|
||||
}
|
||||
let quoted = pool.metadata(&["columns", "qa_%", r#"t_%"q"#, archive]).await?;
|
||||
assert_eq!(quoted.len(), 1);
|
||||
assert_eq!(quoted[0][0].as_deref(), Some("quoted_only"));
|
||||
assert_eq!(quoted[0][4].as_deref(), Some("1"));
|
||||
let all = schema_columns(pool.metadata(&["schemaColumns", "qa_%", archive]).await?);
|
||||
assert_eq!(all.len(), 1);
|
||||
assert_eq!(all[r#"t_%"q"#][0].name, "quoted_only");
|
||||
assert_eq!(all[r#"t_%"q"#][0].comment.as_deref(), Some("In the archive"));
|
||||
|
||||
pool.query("USE first", 0, 1, &stop).await?;
|
||||
let catalogs = pool.metadata(&["catalogs"]).await?;
|
||||
assert!(catalogs.contains(&vec![Some("first".into()), Some("1".into())]));
|
||||
let legacy = pool.metadata(&["columns", "main", "dupe"]).await?;
|
||||
assert_eq!(legacy[0][0].as_deref(), Some("first_only"));
|
||||
pool.query("USE memory", 0, 1, &stop).await?;
|
||||
pool.query("DETACH first", 0, 1, &stop).await?;
|
||||
let catalogs = pool.metadata(&["catalogs"]).await?;
|
||||
assert!(!catalogs.iter().any(|r| r[0].as_deref() == Some("first")));
|
||||
assert!(pool.metadata(&["schemas", "first"]).await?.is_empty());
|
||||
assert!(pool.metadata(&["tables", "main", "first"]).await?.is_empty());
|
||||
assert!(pool.metadata(&["columns", "main", "dupe", "first"]).await?.is_empty());
|
||||
pool.close().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn result_codec_preserves_null_and_rejects_incomplete_frames() {
|
||||
let mut frame =
|
||||
|
||||
+154
-18
@@ -43,7 +43,7 @@ use parking_lot::Mutex;
|
||||
use secrets::SecretStore;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -435,6 +435,41 @@ fn tunnel_target(source: &DataSource) -> (&str, u16) {
|
||||
(if source.host.trim().is_empty() { "localhost" } else { source.host.trim() }, port)
|
||||
}
|
||||
|
||||
fn is_duckdb(source: &DataSource) -> bool {
|
||||
const PREFIX: &str = "jdbc:duckdb:";
|
||||
source.driver == DbDriver::Jdbc
|
||||
&& (source.vendor == "duckdb"
|
||||
|| source.url.trim().get(..PREFIX.len()).is_some_and(|url| url.eq_ignore_ascii_case(PREFIX)))
|
||||
}
|
||||
|
||||
async fn duckdb_catalog(pool: &Pool, database: &str) -> IdeResult<Vec<CatalogSchema>> {
|
||||
// List empty schemas too and put all schema names before the bounded table rows.
|
||||
const MAX_CATALOG_ROWS: usize = 20_000;
|
||||
let name = sql::quote_literal(DbDriver::Jdbc, database);
|
||||
let query = format!(
|
||||
"SELECT schema_name AS schema, NULL::VARCHAR AS name, NULL::VARCHAR AS kind, NULL::VARCHAR AS comment \
|
||||
FROM system.main.duckdb_schemas() WHERE database_name = {name} \
|
||||
UNION ALL \
|
||||
SELECT table_schema, table_name, lower(table_type), table_comment \
|
||||
FROM system.information_schema.tables WHERE table_catalog = {name} \
|
||||
ORDER BY name NULLS FIRST, schema LIMIT {MAX_CATALOG_ROWS}"
|
||||
);
|
||||
let mut schemas = BTreeMap::<String, Vec<TableInfo>>::new();
|
||||
for row in pool.rows(&query, MAX_CATALOG_ROWS).await? {
|
||||
let mut values = row.into_iter();
|
||||
let Some(Some(schema)) = values.next() else { continue };
|
||||
let tables = schemas.entry(schema).or_default();
|
||||
if let Some(Some(name)) = values.next() {
|
||||
tables.push(TableInfo {
|
||||
name,
|
||||
kind: DbTableKind::from_catalog(values.next().flatten().as_deref()),
|
||||
comment: values.next().flatten().filter(|comment| !comment.is_empty()),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(schemas.into_iter().map(|(name, tables)| CatalogSchema { name, tables }).collect())
|
||||
}
|
||||
|
||||
pub fn split_target(target: &str) -> (&str, Option<&str>) {
|
||||
match target.split_once(':') {
|
||||
Some((id, db)) if !db.is_empty() => (id, Some(db)),
|
||||
@@ -1024,12 +1059,30 @@ impl DbManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The databases of the server of data source `id` (PostgreSQL), the connected one first.
|
||||
/// What databases this data source can see, including DuckDB's live attachments.
|
||||
pub async fn databases(&self, id: &str) -> IdeResult<Databases> {
|
||||
let id = split_target(id).0;
|
||||
let introspection = self.source(id)?.introspection;
|
||||
let source = self.source(id)?;
|
||||
let introspection = &source.introspection;
|
||||
let system = introspection.show_system;
|
||||
let pool = self.pool(id).await?;
|
||||
if let Pool::Jdbc(p) = &*pool
|
||||
&& is_duckdb(&source)
|
||||
{
|
||||
let mut current = String::new();
|
||||
let mut names = Vec::new();
|
||||
for mut row in p.metadata(&["catalogs"]).await? {
|
||||
if let [Some(name), active] = row.as_mut_slice() {
|
||||
if active.as_deref() == Some("1") {
|
||||
current = name.clone();
|
||||
names.insert(0, std::mem::take(name));
|
||||
} else if system || name != "system" {
|
||||
names.push(std::mem::take(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(Databases { current, names });
|
||||
}
|
||||
if pool.driver() == DbDriver::SqlServer {
|
||||
let first =
|
||||
|rows: Vec<Vec<Option<String>>>| rows.into_iter().filter_map(|r| r.into_iter().next().flatten());
|
||||
@@ -1068,12 +1121,13 @@ impl DbManager {
|
||||
Ok(Databases { current, names })
|
||||
}
|
||||
|
||||
/// The schemas of `database` of data source `id` with their tables and views (Snowflake):
|
||||
/// what completion needs to follow `database.schema.table` without the tree being opened.
|
||||
/// The result is also saved ([`DbManager::saved_catalog`]) for the next run.
|
||||
/// The schemas of `database` with their tables and views for qualified SQL completion.
|
||||
/// Snowflake's result is also saved ([`DbManager::saved_catalog`]) for the next run.
|
||||
pub async fn database_catalog(&self, id: &str, database: &str) -> IdeResult<Vec<CatalogSchema>> {
|
||||
let id = split_target(id).0;
|
||||
let schemas = match &*self.pool(id).await? {
|
||||
let pool = self.pool(id).await?;
|
||||
let schemas = match &*pool {
|
||||
Pool::Jdbc(_) if is_duckdb(&self.source(id)?) => return duckdb_catalog(&pool, database).await,
|
||||
Pool::Snowflake(p) => snowflake::meta::catalog(p, database).await?,
|
||||
_ => return Err(IdeError::invalid("this data source does not list other databases")),
|
||||
};
|
||||
@@ -1178,14 +1232,45 @@ impl DbManager {
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn duckdb_catalog_pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
|
||||
let source = self.source(id)?;
|
||||
if id != source.id || source.driver != DbDriver::Jdbc || source.vendor != "duckdb" {
|
||||
return Err(IdeError::invalid("Catalog browsing requires a DuckDB data source"));
|
||||
}
|
||||
self.pool(id).await
|
||||
}
|
||||
|
||||
pub async fn catalog_table_details(
|
||||
&self,
|
||||
id: &str,
|
||||
catalog: &str,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
) -> IdeResult<TableDetails> {
|
||||
let pool = self.duckdb_catalog_pool(id).await?;
|
||||
Self::table_details_on(&pool, Some(catalog), schema, table).await
|
||||
}
|
||||
|
||||
pub async fn table_details(&self, id: &str, schema: &str, table: &str) -> IdeResult<TableDetails> {
|
||||
let pool = self.pool(id).await?;
|
||||
if let Pool::Snowflake(p) = &*pool {
|
||||
Self::table_details_on(&pool, None, schema, table).await
|
||||
}
|
||||
|
||||
async fn table_details_on(
|
||||
pool: &Pool,
|
||||
catalog: Option<&str>,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
) -> IdeResult<TableDetails> {
|
||||
if let Pool::Snowflake(p) = pool {
|
||||
return snowflake::meta::table_details(p, schema, table).await;
|
||||
}
|
||||
let driver = pool.driver();
|
||||
let rows = match &*pool {
|
||||
Pool::Jdbc(p) => p.metadata(&["columns", schema, table]).await?,
|
||||
let rows = match pool {
|
||||
Pool::Jdbc(p) => match catalog {
|
||||
Some(catalog) => p.metadata(&["columns", schema, table, catalog]).await?,
|
||||
None => p.metadata(&["columns", schema, table]).await?,
|
||||
},
|
||||
_ => pool.rows(&sql::columns(driver, schema, table), MAX_META_ROWS).await?,
|
||||
};
|
||||
let columns = rows
|
||||
@@ -1775,9 +1860,24 @@ impl DbManager {
|
||||
schema: Option<&str>,
|
||||
console: Option<ConsoleId<'_>>,
|
||||
) -> IdeResult<Vec<PlanNode>> {
|
||||
let driver = self.pool(id).await?.driver();
|
||||
if driver == DbDriver::Jdbc {
|
||||
return Err(IdeError::invalid("Custom JDBC execution plans are unsupported"));
|
||||
let pool = self.pool(id).await?;
|
||||
let driver = pool.driver();
|
||||
if let Pool::Jdbc(jdbc) = &*pool {
|
||||
if self.source(id)?.vendor != "duckdb" || !jdbc.version.starts_with("DuckDB ") {
|
||||
return Err(IdeError::invalid("Custom JDBC execution plans are unsupported"));
|
||||
}
|
||||
let sql = statement.trim().trim_end_matches(';');
|
||||
if sql.contains(';') {
|
||||
// The driver can execute a whole script. Have DuckDB count its statements before prefixing EXPLAIN.
|
||||
let literal = sql::quote_literal(driver, sql);
|
||||
let check = format!("SELECT json_array_length(json_serialize_plan({literal}), '$.plans')");
|
||||
let result = self.run(id, &check, 0, 1, cancel, schema, console).await?;
|
||||
if result.rows.first().and_then(|r| r.first()).and_then(Option::as_deref) != Some("1") {
|
||||
return Err(IdeError::invalid("Choose one statement to explain"));
|
||||
}
|
||||
}
|
||||
let result = self.run(id, &format!("EXPLAIN (FORMAT JSON) {sql}"), 0, 3, cancel, schema, console).await?;
|
||||
return plan::duckdb(&result);
|
||||
}
|
||||
if driver == DbDriver::Oracle {
|
||||
// EXPLAIN PLAN writes PLAN_TABLE; the plan is read (and cleaned up) separately.
|
||||
@@ -1982,18 +2082,54 @@ impl DbManager {
|
||||
limit: u64,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<TablePage> {
|
||||
let details = self.table_details(id, schema, table).await?;
|
||||
let pool = self.pool(id).await?;
|
||||
let mut result = if let Pool::Jdbc(p) = &*pool {
|
||||
Self::table_page_on(&pool, None, schema, table, filter, sort, offset, limit, cancel).await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn catalog_table_page(
|
||||
&self,
|
||||
id: &str,
|
||||
catalog: &str,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
filter: Option<&str>,
|
||||
sort: &[SortKey],
|
||||
offset: u64,
|
||||
limit: u64,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<TablePage> {
|
||||
let pool = self.duckdb_catalog_pool(id).await?;
|
||||
Self::table_page_on(&pool, Some(catalog), schema, table, filter, sort, offset, limit, cancel).await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn table_page_on(
|
||||
pool: &Pool,
|
||||
catalog: Option<&str>,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
filter: Option<&str>,
|
||||
sort: &[SortKey],
|
||||
offset: u64,
|
||||
limit: u64,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<TablePage> {
|
||||
let details = Self::table_details_on(pool, catalog, schema, table).await?;
|
||||
let mut result = if let Pool::Jdbc(p) = pool {
|
||||
let q = &p.identifier_quote;
|
||||
let names = [schema, table].into_iter().chain(sort.iter().map(|k| k.column.as_str()));
|
||||
let names =
|
||||
catalog.into_iter().chain((catalog.is_some() || !schema.is_empty()).then_some(schema)).chain([table]);
|
||||
if q.is_empty()
|
||||
&& names.into_iter().any(|name| !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
|
||||
&& names
|
||||
.clone()
|
||||
.chain(sort.iter().map(|k| k.column.as_str()))
|
||||
.any(|name| !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
|
||||
{
|
||||
return Err(IdeError::invalid("This JDBC driver cannot quote the selected identifier"));
|
||||
}
|
||||
let quote = |s: &str| format!("{q}{}{q}", s.replace(q, &format!("{q}{q}")));
|
||||
let name = if schema.is_empty() { quote(table) } else { format!("{}.{}", quote(schema), quote(table)) };
|
||||
let name = names.map(quote).collect::<Vec<_>>().join(".");
|
||||
let sql = sql::table_select(&name, filter, sort, quote);
|
||||
p.page(&sql, offset, limit, cancel).await?
|
||||
} else {
|
||||
|
||||
@@ -90,6 +90,54 @@ fn prop(name: &str, value: impl Into<String>) -> PlanProperty {
|
||||
PlanProperty { name: name.to_owned(), value: value.into() }
|
||||
}
|
||||
|
||||
fn json_property(name: &str, value: &Value) -> PlanProperty {
|
||||
let as_text = |v: &Value| v.as_str().map_or_else(|| v.to_string(), str::to_owned);
|
||||
let text = match value {
|
||||
Value::Array(items) => items.iter().map(as_text).collect::<Vec<_>>().join(", "),
|
||||
other => as_text(other),
|
||||
};
|
||||
prop(name, text)
|
||||
}
|
||||
|
||||
/// DuckDB's explain_output may request the physical plan, the optimized logical plan, or all three.
|
||||
pub(crate) fn duckdb(result: &QueryResult) -> IdeResult<Vec<PlanNode>> {
|
||||
#[derive(Deserialize)]
|
||||
struct Operator {
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
children: Vec<Operator>,
|
||||
#[serde(default)]
|
||||
extra_info: serde_json::Map<String, Value>,
|
||||
}
|
||||
|
||||
fn append(node: Operator, parent: Option<u32>, out: &mut Vec<PlanNode>) {
|
||||
let index = out.len() as u32;
|
||||
let properties = node.extra_info.iter().map(|(k, v)| json_property(k, v)).collect();
|
||||
let params = ["Table", "Conditions", "Filters", "Projections"]
|
||||
.iter()
|
||||
.find_map(|key| node.extra_info.get(*key).map(|v| json_property(key, v).value))
|
||||
.unwrap_or_default();
|
||||
out.push(PlanNode { parent, operation: node.name.trim().to_owned(), params, properties });
|
||||
for child in node.children {
|
||||
append(child, Some(index), out);
|
||||
}
|
||||
}
|
||||
|
||||
let json = ["physical_plan", "logical_opt", "logical_plan"]
|
||||
.iter()
|
||||
.find_map(|kind| {
|
||||
result.rows.iter().find(|r| r.first().and_then(Option::as_deref) == Some(*kind))?.get(1)?.as_deref()
|
||||
})
|
||||
.ok_or_else(|| IdeError::invalid("DuckDB returned no execution plan"))?;
|
||||
let roots: Vec<Operator> =
|
||||
serde_json::from_str(json).map_err(|e| IdeError::invalid(format!("DuckDB plan: {e}")))?;
|
||||
let mut out = Vec::new();
|
||||
for root in roots {
|
||||
append(root, None, &mut out);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// SQLite rows: `id, parent, notused, detail` (`SCAN o`, `SEARCH c USING INTEGER PRIMARY KEY (rowid=?)`).
|
||||
fn sqlite(rows: &[Vec<Option<String>>]) -> Vec<PlanNode> {
|
||||
let mut ids: Vec<String> = Vec::new();
|
||||
@@ -149,18 +197,7 @@ fn postgres(node: &Value, parent: Option<u32>, out: &mut Vec<PlanNode>) {
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|(k, _)| k.as_str() != "Plans")
|
||||
.map(|(k, v)| {
|
||||
let value = match v {
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Array(a) => a
|
||||
.iter()
|
||||
.map(|x| x.as_str().map_or_else(|| x.to_string(), str::to_owned))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
other => other.to_string(),
|
||||
};
|
||||
prop(k, value)
|
||||
})
|
||||
.map(|(k, v)| json_property(k, v))
|
||||
.collect();
|
||||
let me = out.len() as u32;
|
||||
out.push(PlanNode { parent, operation, params: params.join(" "), properties });
|
||||
@@ -287,6 +324,25 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duckdb_prefers_the_physical_plan_and_preserves_operator_details() {
|
||||
let physical = r#"[{"name":"PROJECTION","extra_info":{"Projections":["a","b"]},"children":[{"name":"SEQ_SCAN ","extra_info":{"Table":"items"}}]}]"#;
|
||||
let rows = result(
|
||||
&["explain_key", "explain_value"],
|
||||
vec![vec![Some("logical_opt"), Some("[]")], vec![Some("physical_plan"), Some(physical)]],
|
||||
);
|
||||
let nodes = duckdb(&rows).unwrap();
|
||||
assert_eq!(nodes.len(), 2);
|
||||
assert_eq!((nodes[0].parent, nodes[0].params.as_str()), (None, "a, b"));
|
||||
assert_eq!(
|
||||
(nodes[1].parent, nodes[1].operation.as_str(), nodes[1].params.as_str()),
|
||||
(Some(0), "SEQ_SCAN", "items")
|
||||
);
|
||||
assert_eq!(nodes[1].properties, [prop("Table", "items")]);
|
||||
assert!(duckdb(&result(&[], vec![])).is_err());
|
||||
assert!(duckdb(&result(&[], vec![vec![Some("physical_plan"), Some("invalid")]])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explains_per_dialect() {
|
||||
assert_eq!(explain_statement(DbDriver::Sqlite, "select 1;"), "EXPLAIN QUERY PLAN select 1");
|
||||
|
||||
@@ -122,9 +122,12 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
|
||||
let db = manager(tmp.path());
|
||||
let c = CancellationToken::new();
|
||||
db.execute("test", "create table items(id int primary key, label varchar)", 1, &c).await?;
|
||||
db.execute("test", "comment on table items is 'Local items'", 1, &c).await?;
|
||||
db.execute("test", "insert into items values (1, NULL), (2, 'row')", 1, &c).await?;
|
||||
assert!(db.schemas("test").await?.iter().any(|v| v == "main"));
|
||||
assert!(db.tables("test", "main").await?.iter().any(|v| v.name == "items"));
|
||||
let tables = db.tables("test", "main").await?;
|
||||
let items = tables.iter().find(|table| table.name == "items").expect("items");
|
||||
assert_eq!(items.comment.as_deref(), Some("Local items"));
|
||||
let details = db.table_details("test", "main", "items").await?;
|
||||
assert_eq!(details.columns.len(), 2);
|
||||
let result = db.execute("test", "select id, label from items order by id", 1, &c).await?;
|
||||
@@ -154,6 +157,40 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
|
||||
assert!(!last.has_more);
|
||||
let past = db.table_page("test", "main", "items", None, &sort, 2, 1, &c).await?.result;
|
||||
assert!(past.rows.is_empty() && !past.has_more);
|
||||
let path = tmp.path().join("attachment.duckdb");
|
||||
let path = ide_db::sql::quote_literal(DbDriver::Jdbc, &path.to_string_lossy());
|
||||
let catalog = "archive.db:'1";
|
||||
let quoted = ide_db::sql::quote_ident(DbDriver::Jdbc, catalog);
|
||||
for statement in [
|
||||
format!("ATTACH {path} AS {quoted}"),
|
||||
format!("CREATE SCHEMA {quoted}.empty"),
|
||||
format!("CREATE TABLE {quoted}.main.items(remote_only INTEGER)"),
|
||||
format!("COMMENT ON TABLE {quoted}.main.items IS 'Archived items'"),
|
||||
format!("CREATE VIEW {quoted}.main.remote_view AS SELECT * FROM {quoted}.main.items"),
|
||||
format!("COMMENT ON VIEW {quoted}.main.remote_view IS 'Archived view'"),
|
||||
] {
|
||||
db.execute("test", &statement, 1, &c).await?;
|
||||
}
|
||||
let databases = db.databases("test").await?;
|
||||
assert_eq!(databases.current, "local");
|
||||
assert!(databases.names.iter().any(|name| name == catalog));
|
||||
let schemas = db.database_catalog("test", catalog).await?;
|
||||
assert!(schemas.iter().any(|schema| schema.name == "empty" && schema.tables.is_empty()));
|
||||
let main = schemas.iter().find(|schema| schema.name == "main").expect("main");
|
||||
assert_eq!(
|
||||
main.tables.iter().map(|table| (table.name.as_str(), table.kind, table.comment.as_deref())).collect::<Vec<_>>(),
|
||||
[
|
||||
("items", ide_db::DbTableKind::Table, Some("Archived items")),
|
||||
("remote_view", ide_db::DbTableKind::View, Some("Archived view")),
|
||||
]
|
||||
);
|
||||
assert!(db.saved_catalog("test").await?.is_none());
|
||||
db.execute("test", &format!("USE {quoted}"), 1, &c).await?;
|
||||
assert_eq!(db.databases("test").await?.current, catalog);
|
||||
db.execute("test", "USE local", 1, &c).await?;
|
||||
db.execute("test", &format!("DETACH {quoted}"), 1, &c).await?;
|
||||
assert!(!db.databases("test").await?.names.iter().any(|name| name == catalog));
|
||||
assert!(db.database_catalog("test", catalog).await?.is_empty());
|
||||
db.disconnect("test").await;
|
||||
let reopened = manager(tmp.path());
|
||||
assert_eq!(reopened.execute("test", "select count(*) from items", 1, &c).await?.rows, [vec![Some("2".into())]]);
|
||||
@@ -248,6 +285,21 @@ async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> {
|
||||
db.save_sources(vec![source.clone()]).await?;
|
||||
db.execute("test", "create table session_items as select 42 as id", 1, &cancel).await?;
|
||||
assert_eq!(db.execute("test", "select id from session_items", 1, &cancel).await?.rows, [vec![Some("42".into())]]);
|
||||
let join = "SELECT a.id FROM session_items a JOIN session_items b ON a.id = b.id";
|
||||
let nodes = db.explain("test", join, &cancel, None).await?;
|
||||
let join_node = nodes.iter().position(|n| n.operation == "HASH_JOIN").expect("physical join");
|
||||
assert_eq!(nodes.iter().filter(|n| n.parent == Some(join_node as u32)).count(), 2);
|
||||
assert!(nodes[join_node].properties.iter().any(|p| p.name == "Conditions" && p.value.contains("id")));
|
||||
let batch = db.explain("test", "SELECT 1; SELECT 2", &cancel, None).await.unwrap_err();
|
||||
assert!(batch.message.contains("one statement"));
|
||||
assert!(!db.explain("test", "SELECT ';' AS delimiter", &cancel, None).await?.is_empty());
|
||||
db.execute("test", "SET explain_output = 'optimized_only'", 1, &cancel).await?;
|
||||
assert!(!db.explain("test", "SELECT id FROM session_items", &cancel, None).await?.is_empty());
|
||||
db.explain("test", "INSERT INTO session_items VALUES (43)", &cancel, None).await?;
|
||||
assert_eq!(
|
||||
db.execute("test", "SELECT count(*) FROM session_items", 1, &cancel).await?.rows,
|
||||
[vec![Some("1".into())]]
|
||||
);
|
||||
db.disconnect("test").await;
|
||||
assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items"));
|
||||
db.disconnect("test").await;
|
||||
@@ -261,6 +313,78 @@ async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
|
||||
async fn duckdb_named_catalog_page_uses_the_source_session_and_exact_names() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let db = manager(tmp.path());
|
||||
register_duckdb(&db, Some("duckdb"))?;
|
||||
db.save_sources(vec![DataSource {
|
||||
id: "test".into(),
|
||||
name: "DuckDB".into(),
|
||||
driver: DbDriver::Jdbc,
|
||||
vendor: "duckdb".into(),
|
||||
global: true,
|
||||
jdbc_driver: "duck".into(),
|
||||
url: "jdbc:duckdb:".into(),
|
||||
..Default::default()
|
||||
}])
|
||||
.await?;
|
||||
|
||||
let stop = CancellationToken::new();
|
||||
let file = tmp.path().join("attachment.duckdb");
|
||||
let file = ide_db::sql::quote_literal(DbDriver::Jdbc, &file.to_string_lossy());
|
||||
let catalog = r#"archive.db:with/"quote"#;
|
||||
let schema = "some.schema_%";
|
||||
let table = r#"same."table"#;
|
||||
let quote = |name: &str| ide_db::sql::quote_ident(DbDriver::Jdbc, name);
|
||||
let base_table = format!("memory.{}.{}", quote(schema), quote(table));
|
||||
let attached_table = format!("{}.{}.{}", quote(catalog), quote(schema), quote(table));
|
||||
db.execute_in_console(
|
||||
"test",
|
||||
&format!("ATTACH {file} AS {}", quote(catalog)),
|
||||
0,
|
||||
1,
|
||||
&stop,
|
||||
None,
|
||||
Some(ConsoleId::new("window", "/attach.sql")),
|
||||
)
|
||||
.await?;
|
||||
for statement in [
|
||||
"SET threads = 1".into(),
|
||||
format!("CREATE SCHEMA memory.{}", quote(schema)),
|
||||
format!("CREATE SCHEMA {}.{}", quote(catalog), quote(schema)),
|
||||
format!("CREATE TABLE {base_table} (base_only INTEGER PRIMARY KEY)"),
|
||||
format!("CREATE TABLE {attached_table} (attached_only INTEGER PRIMARY KEY)"),
|
||||
format!("INSERT INTO {base_table} VALUES (3)"),
|
||||
format!("INSERT INTO {attached_table} VALUES (42), (41)"),
|
||||
] {
|
||||
db.execute("test", &statement, 1, &stop).await?;
|
||||
}
|
||||
|
||||
let details = db.catalog_table_details("test", catalog, schema, table).await?;
|
||||
assert_eq!(details.columns.len(), 1);
|
||||
assert_eq!(details.columns[0].name, "attached_only");
|
||||
assert!(details.columns[0].primary_key);
|
||||
let sort = [SortKey { column: "attached_only".into(), descending: true }];
|
||||
let attached = db.catalog_table_page("test", catalog, schema, table, None, &sort, 0, 1, &stop).await?;
|
||||
assert_eq!(attached.result.rows, [vec![Some("42".into())]]);
|
||||
assert!(attached.result.has_more);
|
||||
assert_eq!(db.connected(), ["test"]);
|
||||
|
||||
db.execute("test", &format!("USE {}.{}", quote(catalog), quote(schema)), 1, &stop).await?;
|
||||
let initial = db.catalog_table_page("test", "memory", schema, table, None, &[], 0, 1, &stop).await?;
|
||||
assert_eq!(initial.result.rows, [vec![Some("3".into())]]);
|
||||
assert_eq!(initial.details.columns[0].name, "base_only");
|
||||
assert_eq!(db.databases("test").await?.current, catalog);
|
||||
db.execute("test", "USE memory", 1, &stop).await?;
|
||||
db.execute("test", &format!("DETACH {}", quote(catalog)), 1, &stop).await?;
|
||||
assert!(db.catalog_table_page("test", catalog, schema, table, None, &[], 0, 1, &stop).await.is_err());
|
||||
assert_eq!(db.connected(), ["test"]);
|
||||
db.disconnect("test").await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
|
||||
async fn duckdb_consoles_share_catalog_but_isolate_transactions_and_temporary_tables() -> IdeResult<()> {
|
||||
|
||||
@@ -49,11 +49,15 @@ pub struct Manifest {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub description: String,
|
||||
/// Markdown file for Settings › Plugins › Overview (`description-file`).
|
||||
pub description_file: Option<PathBuf>,
|
||||
pub authors: Vec<String>,
|
||||
pub homepage: Option<String>,
|
||||
pub license: Option<String>,
|
||||
/// Release notes of this version (Settings › Plugins › What's New).
|
||||
pub change_notes: Option<String>,
|
||||
/// Markdown file for Settings › Plugins › What's New (`change-notes-file`).
|
||||
pub change_notes_file: Option<PathBuf>,
|
||||
/// Marketplace categories as declared (see [`Manifest::categories`]).
|
||||
pub declared_categories: Vec<String>,
|
||||
/// SVG shown in Settings › Plugins and the marketplace.
|
||||
@@ -195,6 +199,8 @@ struct Raw {
|
||||
#[serde(default)]
|
||||
description: String,
|
||||
#[serde(default)]
|
||||
description_file: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
authors: Vec<String>,
|
||||
#[serde(default)]
|
||||
homepage: Option<String>,
|
||||
@@ -203,6 +209,8 @@ struct Raw {
|
||||
#[serde(default)]
|
||||
change_notes: Option<String>,
|
||||
#[serde(default)]
|
||||
change_notes_file: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
categories: Vec<String>,
|
||||
#[serde(default)]
|
||||
icon: Option<PathBuf>,
|
||||
@@ -286,10 +294,12 @@ impl Manifest {
|
||||
name: raw.name,
|
||||
version: raw.version,
|
||||
description: raw.description,
|
||||
description_file: raw.description_file,
|
||||
authors: raw.authors,
|
||||
homepage: raw.homepage,
|
||||
license: raw.license,
|
||||
change_notes: raw.change_notes,
|
||||
change_notes_file: raw.change_notes_file,
|
||||
declared_categories: raw.categories,
|
||||
icon: raw.icon,
|
||||
icon_dark: raw.icon_dark,
|
||||
@@ -347,6 +357,14 @@ impl Manifest {
|
||||
self.needs_api("`icon`", 2)?;
|
||||
check_relative(icon, "icon")?;
|
||||
}
|
||||
if let Some(path) = &self.description_file {
|
||||
self.needs_api("`description-file`", 18)?;
|
||||
check_relative(path, "description-file")?;
|
||||
}
|
||||
if let Some(path) = &self.change_notes_file {
|
||||
self.needs_api("`change-notes-file`", 18)?;
|
||||
check_relative(path, "change-notes-file")?;
|
||||
}
|
||||
for cap in self.capabilities.required.iter().chain(&self.capabilities.optional) {
|
||||
if matches!(
|
||||
cap,
|
||||
@@ -1005,4 +1023,27 @@ mod net_ask_api_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doc_files_require_api_1_18_and_relative_paths() {
|
||||
for field in ["description-file", "change-notes-file"] {
|
||||
for engine in ["^1.17", "^1.18"] {
|
||||
let manifest = format!(
|
||||
"id = 'test'\nname = 'Test'\nversion = '0.1.0'\nengines.openidea = '{engine}'\n{field} = 'docs.md'\n"
|
||||
);
|
||||
let parsed = Manifest::parse(&manifest);
|
||||
if engine == "^1.18" {
|
||||
parsed.unwrap();
|
||||
} else {
|
||||
assert!(parsed.unwrap_err().contains("new in plugin API 1.18"), "{field} {engine}");
|
||||
}
|
||||
}
|
||||
for bad in ["../escape.md", "/abs/path.md"] {
|
||||
let manifest = format!(
|
||||
"id = 'test'\nname = 'Test'\nversion = '0.1.0'\nengines.openidea = '^1.18'\n{field} = '{bad}'\n"
|
||||
);
|
||||
assert!(Manifest::parse(&manifest).unwrap_err().contains("relative path"), "{field} {bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ use crate::MANIFEST_FILE;
|
||||
use base64::Engine as _;
|
||||
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
@@ -331,6 +332,9 @@ pub struct IndexEntry {
|
||||
pub version: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
/// Localized descriptions keyed by BCP 47 language tag (e.g. `zh-CN`).
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub description_locales: BTreeMap<String, String>,
|
||||
#[serde(default)]
|
||||
pub authors: Vec<String>,
|
||||
pub publisher: String,
|
||||
@@ -358,6 +362,9 @@ pub struct IndexEntry {
|
||||
/// This version's release notes (the manifest's `change-notes`).
|
||||
#[serde(default)]
|
||||
pub notes: Option<String>,
|
||||
/// Localized release notes keyed by BCP 47 language tag (e.g. `zh-CN`).
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub notes_locales: BTreeMap<String, String>,
|
||||
/// Downloads of the plugin's packages, as counted by whoever serves them.
|
||||
#[serde(default)]
|
||||
pub downloads: Option<u64>,
|
||||
@@ -715,6 +722,7 @@ mod tests {
|
||||
name: id.into(),
|
||||
version: "1.0.0".into(),
|
||||
description: String::new(),
|
||||
description_locales: BTreeMap::new(),
|
||||
authors: Vec::new(),
|
||||
publisher: publisher.into(),
|
||||
download: format!("https://example.com/{id}.oiplugin"),
|
||||
@@ -725,6 +733,7 @@ mod tests {
|
||||
icon: None,
|
||||
homepage: None,
|
||||
notes: None,
|
||||
notes_locales: BTreeMap::new(),
|
||||
downloads: None,
|
||||
featured: false,
|
||||
suggest: Vec::new(),
|
||||
|
||||
@@ -111,7 +111,17 @@ pub fn availability(root: &Path) -> GhAvailability {
|
||||
let login = login.ok().and_then(Result::ok).map(|l| l.trim().to_owned()).filter(|l| !l.is_empty());
|
||||
match repo {
|
||||
Ok(Ok(out)) if out.success => match parse_repo(&out.stdout) {
|
||||
Ok(repo) => GhAvailability::Ready { repo, login },
|
||||
Ok(repo) => {
|
||||
// The login above is github.com's; an Enterprise repository has its own.
|
||||
let login = match url_host(&repo.url).filter(|h| !h.eq_ignore_ascii_case("github.com")) {
|
||||
Some(host) => run(root, &["api", "--hostname", host, "user", "--jq", ".login"])
|
||||
.ok()
|
||||
.map(|l| l.trim().to_owned())
|
||||
.filter(|l| !l.is_empty()),
|
||||
None => login,
|
||||
};
|
||||
GhAvailability::Ready { repo, login }
|
||||
}
|
||||
Err(e) => GhAvailability::Error { message: format!("unexpected gh output: {e}") },
|
||||
},
|
||||
Ok(Ok(out)) => classify_failure(if out.stderr.trim().is_empty() { &out.stdout } else { &out.stderr }),
|
||||
@@ -286,6 +296,10 @@ pub struct GhApiRequest {
|
||||
pub body: Option<String>,
|
||||
/// Follow REST `Link` pages; the result is the array of all pages (`--slurp`).
|
||||
pub paginate: bool,
|
||||
/// The repository's GitHub host (`ghe.example.com`); none: gh's default host. `gh api`
|
||||
/// doesn't take the host from the remote as `gh pr` does.
|
||||
#[serde(default)]
|
||||
pub host: Option<String>,
|
||||
}
|
||||
|
||||
const METHODS: &[&str] = &["GET", "POST", "PATCH", "PUT", "DELETE"];
|
||||
@@ -301,6 +315,13 @@ pub fn api_args(req: &GhApiRequest) -> IdeResult<Vec<String>> {
|
||||
return Err(IdeError::invalid(format!("not a GitHub API endpoint: {endpoint}")));
|
||||
}
|
||||
let mut args: Vec<String> = vec!["api".into(), "--method".into(), method, endpoint.into()];
|
||||
if let Some(host) = req.host.as_deref().map(str::trim).filter(|h| !h.is_empty()) {
|
||||
if !is_host(host) {
|
||||
return Err(IdeError::invalid(format!("not a GitHub host: {host}")));
|
||||
}
|
||||
args.push("--hostname".into());
|
||||
args.push(host.into());
|
||||
}
|
||||
if req.body.is_some() {
|
||||
args.push("--input".into());
|
||||
args.push("-".into());
|
||||
@@ -312,14 +333,45 @@ pub fn api_args(req: &GhApiRequest) -> IdeResult<Vec<String>> {
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// `host` or `host:port`, as gh's `--hostname` takes it.
|
||||
fn is_host(host: &str) -> bool {
|
||||
let (name, port) = host.split_once(':').unwrap_or((host, "1"));
|
||||
!name.is_empty()
|
||||
&& !name.starts_with(['-', '.'])
|
||||
&& name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.')
|
||||
&& !port.is_empty()
|
||||
&& port.bytes().all(|b| b.is_ascii_digit())
|
||||
}
|
||||
|
||||
/// The host of a repository URL from gh (`https://ghe.example.com/o/r` → `ghe.example.com`).
|
||||
pub fn url_host(url: &str) -> Option<&str> {
|
||||
let rest = url.split_once("://")?.1;
|
||||
let host = rest.split('/').next()?;
|
||||
let host = host.rsplit_once('@').map_or(host, |(_, h)| h);
|
||||
is_host(host).then_some(host)
|
||||
}
|
||||
|
||||
/// Runs `req`; returns the response body (JSON text, empty for `204 No Content`).
|
||||
pub fn api(root: &Path, req: &GhApiRequest) -> IdeResult<String> {
|
||||
let args = api_args(req)?;
|
||||
let refs: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
let out = process::run_with_input(command(root, &refs)?, req.body.as_deref(), QUICK, None)?;
|
||||
let mut args = api_args(req)?;
|
||||
let run = |args: &[String]| {
|
||||
let refs: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
process::run_with_input(command(root, &refs)?, req.body.as_deref(), QUICK, None)
|
||||
};
|
||||
let mut out = run(&args)?;
|
||||
// Recent gh refuses plain-text bodies with terminal escape sequences (coloured Actions job
|
||||
// logs) unless allowed; older gh lacks the flag. Only a GET is safe to send twice.
|
||||
if !out.success && req.method.eq_ignore_ascii_case("GET") && refused_escape_sequences(&out.stderr) {
|
||||
args.insert(1, "--allow-escape-sequences".into());
|
||||
out = run(&args)?;
|
||||
}
|
||||
if out.success { Ok(out.stdout) } else { Err(failure(&out.stderr, &out.stdout)) }
|
||||
}
|
||||
|
||||
fn refused_escape_sequences(stderr: &str) -> bool {
|
||||
stderr.contains("--allow-escape-sequences")
|
||||
}
|
||||
|
||||
/// Revisions to diff a pull request's files with, present in the local repository.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -374,6 +426,15 @@ pub fn prepare_diff(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn recognises_gh_refusing_escape_sequences() {
|
||||
// gh 2.104's message for a coloured Actions job log.
|
||||
assert!(super::refused_escape_sequences(
|
||||
"the response contains terminal escape sequences; pass --allow-escape-sequences to output it anyway\n"
|
||||
));
|
||||
assert!(!super::refused_escape_sequences("gh: Not Found (HTTP 404)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gh_executable_picks_up_newly_installed_binary_without_restart() {
|
||||
let dir = std::env::temp_dir().join(format!("openidea-gh-test-{}", std::process::id()));
|
||||
|
||||
@@ -101,14 +101,28 @@ fn list_arguments() {
|
||||
|
||||
#[test]
|
||||
fn api_arguments() {
|
||||
let req =
|
||||
GhApiRequest { method: "post".into(), endpoint: "graphql".into(), body: Some("{}".into()), paginate: false };
|
||||
let req = GhApiRequest {
|
||||
method: "post".into(),
|
||||
endpoint: "graphql".into(),
|
||||
body: Some("{}".into()),
|
||||
paginate: false,
|
||||
host: None,
|
||||
};
|
||||
assert_eq!(api_args(&req).unwrap(), ["api", "--method", "POST", "graphql", "--input", "-"]);
|
||||
let ghe = GhApiRequest { host: Some("ghe.example.com:8443".into()), ..req.clone() };
|
||||
assert_eq!(
|
||||
api_args(&ghe).unwrap(),
|
||||
["api", "--method", "POST", "graphql", "--hostname", "ghe.example.com:8443", "--input", "-"]
|
||||
);
|
||||
for bad in ["--x", "evil.example/x", "a b", ".x", "h:", "h:8x"] {
|
||||
assert!(api_args(&GhApiRequest { host: Some(bad.into()), ..req.clone() }).is_err(), "{bad}");
|
||||
}
|
||||
let req = GhApiRequest {
|
||||
method: "GET".into(),
|
||||
endpoint: "repos/{owner}/{repo}/labels".into(),
|
||||
body: None,
|
||||
paginate: true,
|
||||
host: Some(" ".into()),
|
||||
};
|
||||
assert_eq!(
|
||||
api_args(&req).unwrap(),
|
||||
@@ -119,3 +133,11 @@ fn api_arguments() {
|
||||
}
|
||||
assert!(api_args(&GhApiRequest { method: "TRACE".into(), ..req }).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_url_hosts() {
|
||||
assert_eq!(url_host("https://ghe.example.com/acme/app"), Some("ghe.example.com"));
|
||||
assert_eq!(url_host("https://github.com/o/r"), Some("github.com"));
|
||||
assert_eq!(url_host("https://[email protected]:8443/o/r"), Some("ghe.example.com:8443"));
|
||||
assert_eq!(url_host("ghe.example.com/o/r"), None);
|
||||
}
|
||||
@@ -28,6 +28,7 @@ ide-syntax.workspace = true
|
||||
ide-search.workspace = true
|
||||
ide-lsp.workspace = true
|
||||
ide-vcs.workspace = true
|
||||
ide-github.workspace = true
|
||||
ide-dap.workspace = true
|
||||
ide-heap.workspace = true
|
||||
ide-jvm-attach.workspace = true
|
||||
|
||||
@@ -22,7 +22,9 @@
|
||||
mod templates;
|
||||
|
||||
use ide_extension::{Manifest, validate_plugin_id};
|
||||
use ide_host::plugins::{PluginHost, market_href_reachable_from, plugin_icon, read_market_url, resolve_market_href};
|
||||
use ide_host::plugins::{
|
||||
PluginHost, market_href_reachable_from, plugin_docs, plugin_icon, read_market_url, resolve_market_href,
|
||||
};
|
||||
use ide_plugin::{Limits, PluginEngine};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitCode};
|
||||
@@ -641,12 +643,15 @@ fn cmd_index(args: &[String]) -> Result<(), String> {
|
||||
Some(wasm) => engine.check_component(&engine.compile(&scratch.join(wasm))?)?,
|
||||
None => None,
|
||||
};
|
||||
let pkg = ide_extension::Package::new(m.clone(), scratch.clone());
|
||||
let docs = plugin_docs(&pkg)?;
|
||||
let file = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
Ok::<_, String>(IndexEntry {
|
||||
id: m.id.clone(),
|
||||
name: m.name.clone(),
|
||||
version: m.version.clone(),
|
||||
description: m.description.clone(),
|
||||
description: docs.description,
|
||||
description_locales: docs.description_locales,
|
||||
authors: m.authors.clone(),
|
||||
publisher: signer,
|
||||
download: base.map_or_else(|| file.clone(), |b| format!("{b}/{file}")),
|
||||
@@ -654,9 +659,10 @@ 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()))?,
|
||||
icon: plugin_icon(&pkg)?,
|
||||
homepage: m.homepage.clone().filter(|h| !h.trim().is_empty()),
|
||||
notes: m.change_notes.clone().filter(|n| !n.trim().is_empty()),
|
||||
notes: docs.change_notes.filter(|n| !n.trim().is_empty()),
|
||||
notes_locales: docs.change_notes_locales,
|
||||
downloads: None,
|
||||
featured: false,
|
||||
suggest: Vec::new(),
|
||||
@@ -1078,6 +1084,62 @@ mod tests {
|
||||
assert!(index.plugins[0].icon.as_ref().expect("icon").light.contains("<rect"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_validates_markdown_doc_files_and_index_carries_localized_docs() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let t = tmp.path();
|
||||
let key = t.join("acme.key");
|
||||
std::fs::write(&key, PublisherKey::from_seed([7; 32]).seed_base64()).unwrap();
|
||||
let src = t.join("src");
|
||||
let vars = templates::Vars { id: "acme.docs", name: "Docs", 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()
|
||||
.replace("engines.openidea = \"^1.0\"", "engines.openidea = \"^1.18\"");
|
||||
std::fs::write(
|
||||
src.join("plugin.toml"),
|
||||
format!("description-file = \"description.md\"\nchange-notes-file = \"CHANGELOG.md\"\n{manifest}"),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Missing md file fails `check`.
|
||||
let err = check(&src).unwrap_err();
|
||||
assert!(err.contains("no such file"), "{err}");
|
||||
|
||||
// Valid English + zh-CN md files pass `check`, `pack`, and `index`.
|
||||
std::fs::write(src.join("description.md"), "# English\n\n- Fast\n").unwrap();
|
||||
std::fs::write(src.join("description.zh-CN.md"), "# 中文\n\n- 快速\n").unwrap();
|
||||
std::fs::write(src.join("CHANGELOG.md"), "## 0.1.0\n\n- First release\n").unwrap();
|
||||
std::fs::write(src.join("CHANGELOG.zh-CN.md"), "## 0.1.0\n\n- 首次发布\n").unwrap();
|
||||
check(&src).unwrap();
|
||||
|
||||
let out = t.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let (src_str, key_str) = (src.to_string_lossy().into_owned(), key.to_string_lossy().into_owned());
|
||||
let package = out.join("acme.docs-0.1.0.oiplugin").to_string_lossy().into_owned();
|
||||
cmd_pack(&strings(&[&src_str, "--key", &key_str, "--publisher", "acme", "--out", &package])).unwrap();
|
||||
cmd_index(&strings(&[out.to_str().unwrap(), "--publisher", "acme", "--key", &key_str])).unwrap();
|
||||
let index = Index::parse(&std::fs::read_to_string(out.join("index.json")).unwrap()).unwrap();
|
||||
let entry = &index.plugins[0];
|
||||
assert!(entry.description.contains("# English"));
|
||||
assert_eq!(entry.description_locales.get("zh-CN").map(String::as_str), Some("# 中文\n\n- 快速\n"));
|
||||
assert_eq!(entry.notes.as_deref(), Some("## 0.1.0\n\n- First release\n"));
|
||||
assert_eq!(entry.notes_locales.get("zh-CN").map(String::as_str), Some("## 0.1.0\n\n- 首次发布\n"));
|
||||
|
||||
// Invalid extension fails `check`.
|
||||
std::fs::write(src.join("notes.txt"), "plain").unwrap();
|
||||
let bad = std::fs::read_to_string(src.join("plugin.toml"))
|
||||
.unwrap()
|
||||
.replace("change-notes-file = \"CHANGELOG.md\"", "change-notes-file = \"notes.txt\"");
|
||||
std::fs::write(src.join("plugin.toml"), bad).unwrap();
|
||||
let err = check(&src).unwrap_err();
|
||||
assert!(err.contains(".md or .markdown"), "{err}");
|
||||
}
|
||||
|
||||
/// `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() {
|
||||
|
||||
@@ -406,8 +406,14 @@ pub async fn serve(
|
||||
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.cancelled() => break Ok(()),
|
||||
_ = terminate.recv() => break Ok(()),
|
||||
_ = shutdown.cancelled() => {
|
||||
host.set_agent_shutdown_reason(ide_agent::AgentShutdownReason::BackendStop);
|
||||
break Ok(());
|
||||
}
|
||||
_ = terminate.recv() => {
|
||||
host.set_agent_shutdown_reason(ide_agent::AgentShutdownReason::BackendUpgrade);
|
||||
break Ok(());
|
||||
}
|
||||
_ = async {
|
||||
match &active {
|
||||
Some(peer) => { peer.closed().await; }
|
||||
@@ -445,6 +451,7 @@ pub async fn serve(
|
||||
if busy {
|
||||
let _ = stream.write_u8(BUSY).await;
|
||||
} else if stream.write_u8(RETIRING).await.is_ok() {
|
||||
host.set_agent_shutdown_reason(ide_agent::AgentShutdownReason::BackendUpgrade);
|
||||
retiring = Some(stream);
|
||||
break Ok(());
|
||||
}
|
||||
|
||||
@@ -420,12 +420,11 @@ pub(crate) fn run_command(
|
||||
}
|
||||
// A process it started in the background may keep the pipes open: the command is done.
|
||||
if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
|
||||
// Read what it wrote until the pipes close, for at most a second: a busy machine may
|
||||
// deliver its last lines (often the error) well after the exit.
|
||||
let deadline = Instant::now() + Duration::from_secs(1);
|
||||
while let Ok(line) = rx.recv_timeout(Duration::from_millis(100)) {
|
||||
while let Ok(line) = rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
|
||||
on_line(line);
|
||||
if Instant::now() > deadline {
|
||||
break;
|
||||
}
|
||||
}
|
||||
break status;
|
||||
}
|
||||
|
||||
@@ -139,6 +139,8 @@ pub struct Host {
|
||||
pub web: ide_web::WebServer,
|
||||
/// The HTTP proxy's saved password (see `proxy.rs`).
|
||||
proxy_password: ide_ssh::secrets::SecretFile,
|
||||
/// Tokens of the Jupyter servers notebooks run on, by server base URL.
|
||||
jupyter_tokens: ide_ssh::secrets::SecretFile,
|
||||
/// The proxy password when it could not be saved (no credential store).
|
||||
proxy_session_password: Mutex<Option<String>>,
|
||||
/// Values of agents' and MCP servers' environment variables and headers (see `agent_secrets.rs`).
|
||||
@@ -153,6 +155,8 @@ pub struct Host {
|
||||
project_requests: RwLock<HashMap<String, Vec<RequestId>>>,
|
||||
/// Shutdowns of projects closed with [`Host::close_project_detached`].
|
||||
closing: parking_lot::Mutex<Vec<DetachedClose>>,
|
||||
/// Why this host's agents are shutting down when [`Host::shutdown`] runs.
|
||||
agent_shutdown_reason: parking_lot::Mutex<ide_agent::AgentShutdownReason>,
|
||||
/// One open at a time per window (see [`Host::opening`]).
|
||||
open_locks: parking_lot::Mutex<HashMap<String, Arc<parking_lot::Mutex<()>>>>,
|
||||
}
|
||||
@@ -168,6 +172,7 @@ struct ShutdownWork {
|
||||
lsp: Option<Arc<ide_lsp::LspManager>>,
|
||||
debug: Option<(Arc<ide_dap::DebugManager>, String, Option<std::path::PathBuf>)>,
|
||||
agents: Vec<Arc<ide_agent::AgentManager>>,
|
||||
agent_reason: ide_agent::AgentShutdownReason,
|
||||
terminals: Option<ide_terminal::DetachedTerminals>,
|
||||
processes: Option<ide_run::DetachedProcessKills>,
|
||||
retired: Option<Arc<Project>>,
|
||||
@@ -235,6 +240,7 @@ impl Host {
|
||||
trust: std::sync::Arc::new(trust::TrustStore::load(&config_dir, &data_dir)),
|
||||
mcp_approvals: Arc::new(trust::McpServerApprovals::load(&data_dir)),
|
||||
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
|
||||
jupyter_tokens: ide_ssh::secrets::SecretFile::new(data_dir.join("jupyter-tokens.json")),
|
||||
proxy_session_password: Mutex::default(),
|
||||
agent_secrets: Arc::new(agent_secrets::AgentSecrets::new(&data_dir)),
|
||||
remote: Arc::new(ide_remote::RemoteService::new(ssh.clone(), data_dir.join("remote"))),
|
||||
@@ -270,6 +276,7 @@ impl Host {
|
||||
requests: Default::default(),
|
||||
project_requests: RwLock::default(),
|
||||
closing: Default::default(),
|
||||
agent_shutdown_reason: parking_lot::Mutex::new(ide_agent::AgentShutdownReason::Quit),
|
||||
open_locks: Default::default(),
|
||||
};
|
||||
host.apply_proxy();
|
||||
@@ -356,13 +363,18 @@ impl Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the shutdown reason reported on interrupted agent turns when [`Self::shutdown`] runs.
|
||||
pub fn set_agent_shutdown_reason(&self, reason: ide_agent::AgentShutdownReason) {
|
||||
*self.agent_shutdown_reason.lock() = reason;
|
||||
}
|
||||
|
||||
/// Closes `window`'s project and waits until its language servers, kernels and
|
||||
/// debug sessions have shut down. Never call this on the UI event-loop thread:
|
||||
/// the shutdown runs on the async runtime, whose workers may themselves be
|
||||
/// waiting for the event loop (IPC responses, window queries). Use
|
||||
/// [`Self::close_project_detached`] there.
|
||||
pub fn close_project(&self, window: &str) {
|
||||
if let Some(shutdown) = self.begin_close(window) {
|
||||
if let Some(shutdown) = self.begin_close(window, ide_agent::AgentShutdownReason::WindowClose) {
|
||||
self.wait_blocking(shutdown.handle);
|
||||
}
|
||||
}
|
||||
@@ -371,7 +383,12 @@ impl Host {
|
||||
/// the window; its workers finish shutting down in the background, and
|
||||
/// [`Self::shutdown_notebooks_on_exit`] waits for them before the process exits.
|
||||
pub fn close_project_detached(&self, window: &str) {
|
||||
if let Some(shutdown) = self.begin_close(window) {
|
||||
self.close_project_detached_with(window, ide_agent::AgentShutdownReason::WindowClose);
|
||||
}
|
||||
|
||||
/// Like [`Self::close_project_detached`], recording `reason` on any interrupted agent turn.
|
||||
pub fn close_project_detached_with(&self, window: &str, reason: ide_agent::AgentShutdownReason) {
|
||||
if let Some(shutdown) = self.begin_close(window, reason) {
|
||||
let mut closing = self.closing.lock();
|
||||
closing.retain(|entry| !entry.handle.is_finished());
|
||||
closing.push(shutdown);
|
||||
@@ -381,7 +398,7 @@ impl Host {
|
||||
/// Detaches the project from `window` synchronously so the caller (including the UI
|
||||
/// event-loop thread) never blocks on disk I/O or process shutdown, and returns the
|
||||
/// background handle that stops its workers, agents, terminals and processes.
|
||||
fn begin_close(&self, window: &str) -> Option<DetachedClose> {
|
||||
fn begin_close(&self, window: &str, agent_reason: ide_agent::AgentShutdownReason) -> Option<DetachedClose> {
|
||||
self.mcp_reports.forget_window(window);
|
||||
self.mcp_requests.forget_window(window);
|
||||
self.mcp_agent_runs.forget_window(window);
|
||||
@@ -453,6 +470,7 @@ impl Host {
|
||||
// Debug sessions under the root belong to windows: a project served without one starts none.
|
||||
debug: Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
|
||||
agents: vec![project.agents.clone()],
|
||||
agent_reason,
|
||||
terminals: Some(terminals),
|
||||
processes: Some(processes),
|
||||
retired: Some(project),
|
||||
@@ -480,9 +498,10 @@ impl Host {
|
||||
}
|
||||
let agents = (!work.agents.is_empty()).then(|| {
|
||||
let agents = work.agents;
|
||||
let reason = work.agent_reason;
|
||||
std::thread::spawn(move || {
|
||||
for manager in agents {
|
||||
manager.shutdown();
|
||||
manager.shutdown_with(reason);
|
||||
}
|
||||
})
|
||||
});
|
||||
@@ -573,6 +592,10 @@ impl Host {
|
||||
/// kernels and agents, but no longer than [`EXIT_SHUTDOWN_WAIT`], so a runtime worker
|
||||
/// stuck on the event loop cannot keep the process from exiting.
|
||||
pub fn shutdown_notebooks_on_exit(&self) {
|
||||
self.shutdown_notebooks_on_exit_with(ide_agent::AgentShutdownReason::Quit);
|
||||
}
|
||||
|
||||
pub fn shutdown_notebooks_on_exit_with(&self, agent_reason: ide_agent::AgentShutdownReason) {
|
||||
let projects = self.projects();
|
||||
let mut pending: Vec<_> = self.closing.lock().drain(..).map(|entry| entry.handle).collect();
|
||||
if !projects.is_empty() {
|
||||
@@ -582,6 +605,7 @@ impl Host {
|
||||
lsp: None,
|
||||
debug: None,
|
||||
agents: projects.iter().map(|project| project.agents.clone()).collect(),
|
||||
agent_reason,
|
||||
terminals: None,
|
||||
processes: None,
|
||||
retired: None,
|
||||
@@ -670,7 +694,8 @@ impl Host {
|
||||
}
|
||||
project.documents.clear_workspace_edit_history();
|
||||
project.notebooks.stop_admission();
|
||||
project.agents.shutdown();
|
||||
let reason = *self.agent_shutdown_reason.lock();
|
||||
project.agents.shutdown_with(reason);
|
||||
}
|
||||
let stop_processes = async {
|
||||
for project in &projects {
|
||||
|
||||
@@ -9,12 +9,21 @@ use std::path::Path;
|
||||
|
||||
/// Prefix of Open Recent item ids; the rest of the id is the project path.
|
||||
pub const RECENT_PREFIX: &str = "recent:";
|
||||
/// Item id of the local-projects section header in Open Recent.
|
||||
pub const RECENT_LOCAL_ID: &str = "recent.local";
|
||||
/// Prefix of remote host section header ids in Open Recent.
|
||||
pub const RECENT_SECTION_PREFIX: &str = "recent.section:";
|
||||
/// Prefix of items the frontend lists ([`MenuConfig::dynamic`]): `dyn:<action>` or `dyn:<action>|<arg>`.
|
||||
pub const DYNAMIC_PREFIX: &str = "dyn:";
|
||||
/// Action run for an Open Recent entry (argument: the project path).
|
||||
pub const OPEN_RECENT_ACTION: &str = "file.openRecentProject";
|
||||
pub const MAX_RECENT: usize = 15;
|
||||
|
||||
/// Whether `id` names a non-interactive Open Recent placeholder or section header.
|
||||
pub fn is_recent_placeholder(id: &str) -> bool {
|
||||
id == "recent.none" || id == RECENT_LOCAL_ID || id.starts_with(RECENT_SECTION_PREFIX)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Os {
|
||||
Mac,
|
||||
@@ -236,7 +245,9 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("remote.stopBackend", "Stop Remote Backend"),
|
||||
act("remote.reloadEnvironment", "Reload Environment"),
|
||||
SEP,
|
||||
act("file.saveAs", "Save As…"),
|
||||
act("file.save", "Save All"),
|
||||
act("templates.saveFileAsTemplate", "Save File as Template…"),
|
||||
act("file.reloadAllFromDisk", "Reload All from Disk"),
|
||||
sub("fileProperties", "File Properties", vec![act("file.toggleReadOnly", "Make File Read-only / Writable")]),
|
||||
SEP,
|
||||
@@ -251,6 +262,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("file.exportSettings", "Export Settings…"),
|
||||
act("file.importSettings", "Import Settings…"),
|
||||
act("file.importJetBrainsSettings", "Import Settings from JetBrains IDE…"),
|
||||
act("file.syncSettings", "Sync Settings Now"),
|
||||
],
|
||||
),
|
||||
sub(
|
||||
@@ -674,6 +686,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("vcs.pull", "Pull…"),
|
||||
act("vcs.fetch", "Fetch"),
|
||||
act("vcs.unshallow", "Fetch Full History"),
|
||||
act("vcs.lfsPull", "Pull LFS Objects"),
|
||||
SEP,
|
||||
// Operation items (Abort Merge, Continue Rebase…) are enabled only while it is in progress.
|
||||
act("vcs.merge", "Merge…"),
|
||||
@@ -691,6 +704,14 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
SEP,
|
||||
act("vcs.newWorktree", "New Worktree…"),
|
||||
act("vcs.worktrees", "Worktrees…"),
|
||||
sub(
|
||||
"gitSubmodules",
|
||||
"Submodules",
|
||||
vec![
|
||||
act("vcs.initSubmodules", "Initialize Submodules"),
|
||||
act("vcs.syncSubmodules", "Sync Submodule URLs"),
|
||||
],
|
||||
),
|
||||
SEP,
|
||||
act("vcs.showLog", "Show Git Log"),
|
||||
sub(
|
||||
@@ -739,6 +760,10 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("github.createPullRequest", "Create Pull Request…"),
|
||||
act("github.checkoutPullRequest", "Checkout Pull Request…"),
|
||||
act("github.openInBrowser", "Open on GitHub"),
|
||||
SEP,
|
||||
act("github.createGist", "Create Gist…"),
|
||||
act("github.shareProject", "Share Project on GitHub"),
|
||||
act("github.actions.show", "GitHub Actions"),
|
||||
],
|
||||
),
|
||||
act("vcs.manageRemotes", "Manage Remotes…"),
|
||||
@@ -1086,33 +1111,107 @@ pub struct RemoteRecent {
|
||||
pub opened_at_ms: f64,
|
||||
}
|
||||
|
||||
pub struct RecentItem {
|
||||
pub path: String,
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RecentSection {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
/// The local and remote recent projects, most recently opened first.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RecentItem {
|
||||
pub path: String,
|
||||
pub label: String,
|
||||
pub section: Option<RecentSection>,
|
||||
}
|
||||
|
||||
fn parse_remote_recent(r: &RemoteRecent) -> (RecentSection, String) {
|
||||
const SCHEMES: [(&str, &str, &str); 3] =
|
||||
[("ssh://", "ssh", "SSH"), ("wsl://", "wsl", "WSL"), ("devcontainer://", "devContainer", "Dev Container")];
|
||||
for (prefix, kind, kind_label) in SCHEMES {
|
||||
if let Some(rest) = r.location.strip_prefix(prefix)
|
||||
&& let Some(slash) = rest.find('/')
|
||||
&& slash > 0
|
||||
{
|
||||
let remote_path = &rest[slash..];
|
||||
let (host, shown_path) = match r.detail.strip_suffix(remote_path).and_then(|h| h.strip_suffix(':')) {
|
||||
Some(host) if !host.is_empty() => (host, remote_path),
|
||||
_ => r.detail.split_once(':').unwrap_or((&rest[..slash], remote_path)),
|
||||
};
|
||||
return (
|
||||
RecentSection {
|
||||
id: format!("{RECENT_SECTION_PREFIX}{kind}:{host}"),
|
||||
label: format!("{kind_label} · {host}"),
|
||||
},
|
||||
format!("{} — {shown_path}", r.name),
|
||||
);
|
||||
}
|
||||
}
|
||||
let (host, shown_path) = r.detail.split_once(':').unwrap_or((r.detail.as_str(), r.detail.as_str()));
|
||||
(
|
||||
RecentSection { id: format!("{RECENT_SECTION_PREFIX}remote:{host}"), label: host.to_owned() },
|
||||
format!("{} — {shown_path}", r.name),
|
||||
)
|
||||
}
|
||||
|
||||
/// The local and remote recent projects, grouped by host in MRU order when remote projects exist.
|
||||
pub fn recent_items(
|
||||
recent: &[ide_workspace::RecentProject],
|
||||
remote: &[RemoteRecent],
|
||||
home: Option<&Path>,
|
||||
) -> Vec<RecentItem> {
|
||||
enum Candidate<'a> {
|
||||
Local { path: String, label: String },
|
||||
Remote(&'a RemoteRecent),
|
||||
}
|
||||
|
||||
let local = recent.iter().map(|p| {
|
||||
let shown = match home.and_then(|h| p.path.strip_prefix(h).ok()) {
|
||||
Some(rest) => format!("~/{}", rest.display()),
|
||||
None => p.path.display().to_string(),
|
||||
};
|
||||
let item =
|
||||
RecentItem { path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name) };
|
||||
(p.opened_at_ms, item)
|
||||
(
|
||||
p.opened_at_ms,
|
||||
Candidate::Local {
|
||||
path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name)
|
||||
},
|
||||
)
|
||||
});
|
||||
let remote = remote.iter().map(|r| {
|
||||
(r.opened_at_ms, RecentItem { path: r.location.clone(), label: format!("{} — {}", r.name, r.detail) })
|
||||
});
|
||||
let mut items: Vec<(f64, RecentItem)> = local.chain(remote).collect();
|
||||
let remote_candidates = remote.iter().map(|r| (r.opened_at_ms, Candidate::Remote(r)));
|
||||
let mut items: Vec<(f64, Candidate<'_>)> = local.chain(remote_candidates).collect();
|
||||
// Stable: the local list's own order holds among equal times.
|
||||
items.sort_by(|a, b| b.0.total_cmp(&a.0));
|
||||
items.into_iter().take(MAX_RECENT).map(|(_, item)| item).collect()
|
||||
items.truncate(MAX_RECENT);
|
||||
|
||||
let has_remote = items.iter().any(|(_, c)| matches!(c, Candidate::Remote(_)));
|
||||
if !has_remote {
|
||||
return items
|
||||
.into_iter()
|
||||
.filter_map(|(_, c)| match c {
|
||||
Candidate::Local { path, label } => Some(RecentItem { path, label, section: None }),
|
||||
Candidate::Remote(_) => None,
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
let mut groups: Vec<(String, Vec<RecentItem>)> = Vec::new();
|
||||
for (_, candidate) in items {
|
||||
let (section, path, label) = match candidate {
|
||||
Candidate::Local { path, label } => {
|
||||
(RecentSection { id: RECENT_LOCAL_ID.into(), label: "Local".into() }, path, label)
|
||||
}
|
||||
Candidate::Remote(r) => {
|
||||
let (section, label) = parse_remote_recent(r);
|
||||
(section, r.location.clone(), label)
|
||||
}
|
||||
};
|
||||
let item = RecentItem { path, label, section: Some(section.clone()) };
|
||||
if let Some((_, members)) = groups.iter_mut().find(|(id, _)| *id == section.id) {
|
||||
members.push(item);
|
||||
} else {
|
||||
groups.push((section.id, vec![item]));
|
||||
}
|
||||
}
|
||||
groups.into_iter().flat_map(|(_, members)| members).collect()
|
||||
}
|
||||
|
||||
/// A menu entry for a menu bar drawn by the frontend (Windows title bar).
|
||||
@@ -1201,13 +1300,30 @@ pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec<
|
||||
Entry::RecentProjects if recent.is_empty() => {
|
||||
out.push(MenuNode::Placeholder { id: "recent.none".into(), label: "No Recent Projects".into() })
|
||||
}
|
||||
Entry::RecentProjects => out.extend(recent.iter().map(|r| MenuNode::Action {
|
||||
id: OPEN_RECENT_ACTION.into(),
|
||||
label: r.label.clone(),
|
||||
hint: None,
|
||||
arg: Some(r.path.clone()),
|
||||
checked: None,
|
||||
})),
|
||||
Entry::RecentProjects => {
|
||||
let mut current_section: Option<&str> = None;
|
||||
for r in recent {
|
||||
if let Some(sec) = &r.section
|
||||
&& current_section != Some(sec.id.as_str())
|
||||
{
|
||||
if current_section.is_some() {
|
||||
out.push(MenuNode::Separator);
|
||||
}
|
||||
out.push(MenuNode::Placeholder {
|
||||
id: sec.id.clone(),
|
||||
label: config.label(&sec.id, &sec.label),
|
||||
});
|
||||
current_section = Some(sec.id.as_str());
|
||||
}
|
||||
out.push(MenuNode::Action {
|
||||
id: OPEN_RECENT_ACTION.into(),
|
||||
label: r.label.clone(),
|
||||
hint: None,
|
||||
arg: Some(r.path.clone()),
|
||||
checked: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::ops::Channel;
|
||||
use base64::Engine;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, IpcPath, SharedSink};
|
||||
use ide_notebook::kernel::{KernelManager, KernelOutput};
|
||||
use ide_notebook::kernel::{KernelManager, KernelOutput, KernelTarget};
|
||||
use ide_notebook::{NotebookDocument, NotebookEdit, NotebookSnapshot};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -45,11 +45,12 @@ fn parse_variables(reply: &serde_json::Value) -> IdeResult<Vec<NotebookVariable>
|
||||
let rows = &reply["rows"];
|
||||
if rows["status"] != "ok" {
|
||||
let reason = rows["evalue"].as_str().unwrap_or("no result");
|
||||
return Err(IdeError::unavailable(format!("could not read the kernel's variables: {reason}")));
|
||||
return Err(IdeError::new(ErrorKind::Protocol, format!("could not read the kernel's variables: {reason}")));
|
||||
}
|
||||
// The value is a base64 str, so its text/plain is that text in quotes.
|
||||
let text = rows["data"]["text/plain"].as_str().unwrap_or_default().trim_matches(['\'', '"']);
|
||||
let bad = |error: String| IdeError::unavailable(format!("could not read the kernel's variables: {error}"));
|
||||
let bad =
|
||||
|error: String| IdeError::new(ErrorKind::Protocol, format!("could not read the kernel's variables: {error}"));
|
||||
let json = base64::engine::general_purpose::STANDARD.decode(text).map_err(|e| bad(e.to_string()))?;
|
||||
serde_json::from_slice(&json).map_err(|e| bad(e.to_string()))
|
||||
}
|
||||
@@ -355,13 +356,49 @@ impl NotebookService {
|
||||
if document.state.lock().active.is_some() {
|
||||
return Err(IdeError::unavailable("notebook is running"));
|
||||
}
|
||||
let expressions = HashMap::from([("rows".to_owned(), "_openidea_variables()".to_owned())]);
|
||||
let expressions = HashMap::from([("rows".to_owned(), r#"globals().pop("_openidea_variables")()"#.to_owned())]);
|
||||
match self.kernels.inspect(&document.path, VARIABLES, expressions).await? {
|
||||
Some(reply) => parse_variables(&reply).map(Some),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the debugger of the notebook's kernel, starting `target` first (or replacing a
|
||||
/// kernel of another target). Also returns the notebook's code cells as (URI, source), read
|
||||
/// when called, and the prefix of its cell URIs: what Debug Cell needs (see
|
||||
/// `ide_notebook::kernel::debug`).
|
||||
pub(crate) async fn debugger(
|
||||
&self,
|
||||
id: &str,
|
||||
target: KernelTarget,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<(ide_notebook::kernel::KernelDebugger, impl Fn() -> Vec<(String, String)> + Send + 'static, String)>
|
||||
{
|
||||
let document = self.resolve(id)?;
|
||||
if document.state.lock().active.is_some() {
|
||||
return Err(IdeError::unavailable("notebook is running"));
|
||||
}
|
||||
// The drop-down's kernel, which may not be the one running yet.
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
result = self.kernels.start(&document.path, target) => result?,
|
||||
}
|
||||
let debugger = self.kernels.debugger(&document.path)?;
|
||||
let prefix = ide_lsp::cell_uri(&document.path, "");
|
||||
// Read again on each use: cells are added and edited while the session runs.
|
||||
let cells = move || {
|
||||
let Ok(snapshot) = snapshot(&document) else { return Vec::new() };
|
||||
snapshot
|
||||
.cells
|
||||
.into_iter()
|
||||
.filter(|cell| cell.cell_type == "code")
|
||||
.map(|cell| (ide_lsp::cell_uri(&document.path, &cell.id), cell.source))
|
||||
.collect()
|
||||
};
|
||||
Ok((debugger, cells, prefix))
|
||||
}
|
||||
|
||||
pub(crate) fn admit(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -374,7 +411,7 @@ impl NotebookService {
|
||||
pub(crate) async fn execute(
|
||||
self: &Arc<Self>,
|
||||
admission: ExecutionAdmission,
|
||||
python: PathBuf,
|
||||
target: KernelTarget,
|
||||
on_output: Channel<NotebookOutputEvent>,
|
||||
) -> IdeResult<NotebookSnapshot> {
|
||||
let document = admission.guard.document.clone();
|
||||
@@ -383,7 +420,7 @@ impl NotebookService {
|
||||
tokio::spawn(async move {
|
||||
let ExecutionAdmission { guard, generation, plan } = admission;
|
||||
let result =
|
||||
service.run_batch(document.clone(), generation, plan, python, guard.batch.clone(), on_output).await;
|
||||
service.run_batch(document.clone(), generation, plan, target, guard.batch.clone(), on_output).await;
|
||||
drop(guard);
|
||||
match result {
|
||||
Ok(()) => snapshot(&document),
|
||||
@@ -399,7 +436,7 @@ impl NotebookService {
|
||||
document: Arc<ManagedDocument>,
|
||||
generation: u64,
|
||||
plan: Vec<(String, String)>,
|
||||
python: PathBuf,
|
||||
target: KernelTarget,
|
||||
batch: Arc<Batch>,
|
||||
on_output: Channel<NotebookOutputEvent>,
|
||||
) -> IdeResult<()> {
|
||||
@@ -427,7 +464,7 @@ impl NotebookService {
|
||||
.kernels
|
||||
.execute(
|
||||
&document.path,
|
||||
&python,
|
||||
target.clone(),
|
||||
&source,
|
||||
batch.cancel.clone(),
|
||||
Arc::new(move |output: KernelOutput| {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
# Run silently on a notebook's kernel by the Jupyter Variables tool window; the IDE then
|
||||
# evaluates `_openidea_variables()` as a user expression. Same rows as the Python Console's.
|
||||
# Run silently on a notebook's kernel by the Jupyter Variables tool window. The IDE then
|
||||
# evaluates `globals().pop("_openidea_variables")()` as a user expression, which also takes
|
||||
# the function back out of the notebook's namespace. Same rows as the Python Console's.
|
||||
def _openidea_variables():
|
||||
import base64
|
||||
import collections
|
||||
import json
|
||||
import reprlib
|
||||
import types
|
||||
@@ -9,15 +11,33 @@ def _openidea_variables():
|
||||
shell = get_ipython() # noqa: F821 -- defined in every IPython namespace
|
||||
short = reprlib.Repr()
|
||||
short.maxstring = short.maxother = 200
|
||||
limit = short.maxother
|
||||
items = 100
|
||||
containers = (dict, list, tuple, set, frozenset, collections.deque)
|
||||
|
||||
def value_text(value):
|
||||
# reprlib shortens the exact builtin types itself; for anything else it builds the
|
||||
# full repr() and then cuts it. That is right for a subclass's own repr (a namedtuple,
|
||||
# an OrderedDict, a defaultdict), but costs seconds and gigabytes for a big one.
|
||||
kind = type(value)
|
||||
if isinstance(value, (str, bytes, bytearray)) and kind is not str and len(value) > limit:
|
||||
return repr(value[:limit]) + "..."
|
||||
if isinstance(value, containers) and kind not in containers and len(value) > items:
|
||||
return "<%s len=%d>" % (kind.__name__, len(value))
|
||||
return short.repr(value)
|
||||
|
||||
rows = []
|
||||
for name, value in list(shell.user_ns.items()):
|
||||
if name.startswith("_") or name in shell.user_ns_hidden or isinstance(value, types.ModuleType):
|
||||
if name.startswith("_") or name in shell.user_ns_hidden:
|
||||
continue
|
||||
try:
|
||||
text = short.repr(value)
|
||||
except Exception as error: # a broken __repr__ must not hide the other variables
|
||||
text = "<repr failed: %s>" % type(error).__name__
|
||||
rows.append({"name": name, "type": type(value).__name__, "value": text})
|
||||
if isinstance(value, types.ModuleType):
|
||||
continue
|
||||
kind = type(value).__name__
|
||||
text = value_text(value)
|
||||
except Exception as error: # a broken __repr__ or __class__ must not hide the other variables
|
||||
kind, text = "?", "<unavailable: %s>" % type(error).__name__
|
||||
rows.append({"name": name, "type": kind, "value": text})
|
||||
rows.sort(key=lambda row: row["name"])
|
||||
# Base64 so the expression's text/plain (a str repr) needs no unescaping.
|
||||
return base64.b64encode(json.dumps(rows).encode()).decode()
|
||||
@@ -7,10 +7,10 @@ use ide_agent::registry::{AgentRegistry, RegistryPaths};
|
||||
use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentModelCatalog,
|
||||
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
|
||||
CopilotAuthStatus, CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource,
|
||||
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
|
||||
RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
|
||||
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentRecoveryReport, AgentSkillMode, AgentSkillPolicy,
|
||||
AgentSkillState, AgentTask, CopilotAuthStatus, CustomAgentInput, ExternalSession, InstallRemoteSkillRequest,
|
||||
LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput,
|
||||
McpTransport, NewAgentTask, RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
|
||||
};
|
||||
use ide_command::command;
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -144,12 +144,18 @@ fn prepare_login_launch_env(
|
||||
env: &mut std::collections::BTreeMap<String, String>,
|
||||
host_has: impl Fn(&str) -> bool,
|
||||
) {
|
||||
if !is_remote {
|
||||
return;
|
||||
}
|
||||
let has_non_empty = |env: &std::collections::BTreeMap<String, String>, key: &str| {
|
||||
env.get(key).is_some_and(|v| !v.is_empty()) || host_has(key)
|
||||
};
|
||||
// Skip `gh`'s `termenv` OSC 11 background-color probe during interactive login (`gh auth login`
|
||||
// renders no markdown); if an OSC 11 reply arrives late over a PTY or SSH link, `survey` aborts
|
||||
// with `unexpected escape sequence from terminal: ['\x1b' ']']`.
|
||||
if target_is_gh && !has_non_empty(env, "GLAMOUR_STYLE") {
|
||||
env.insert("GLAMOUR_STYLE".into(), "notty".into());
|
||||
}
|
||||
if !is_remote {
|
||||
return;
|
||||
}
|
||||
// `openidea-server` spawns sign-in commands in a real PTY even inside WSL, dev containers,
|
||||
// and `--web`, where `SSH_*` variables are absent; mark the session remote so CLIs such as
|
||||
// `copilot login` choose OAuth device-code sign-in over a remote-only loopback server.
|
||||
@@ -610,6 +616,74 @@ pub fn agent_cancel(host: &Host, window: &str, task: String, subagent: Option<St
|
||||
host.project(window)?.agents.cancel(&task, subagent)
|
||||
}
|
||||
|
||||
/// Resumes an interrupted task with a continuation turn (or immediately wakes a task waiting
|
||||
/// in the transient network outage retry loop).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_resume_task(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.resume(&task)).await
|
||||
}
|
||||
|
||||
/// Resumes all interrupted tasks in the project and returns their IDs.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_resume_all_interrupted(host: &Host, window: &str) -> IdeResult<Vec<String>> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.resume_all_interrupted()).await
|
||||
}
|
||||
|
||||
/// Clears a task's interrupted state without sending a continuation prompt.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_dismiss_interrupted(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.dismiss_interrupted(&task)).await
|
||||
}
|
||||
|
||||
/// Marks a task as read (`unread = false`) when viewed by the user.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_mark_read(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.mark_read(&task)).await
|
||||
}
|
||||
|
||||
/// Overrides the recovery / network auto-retry window (`None` = global default,
|
||||
/// `Some(0)` = Off / Ask, `Some(minutes)` = override) for `task`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_set_recovery_window(host: &Host, window: &str, task: String, minutes: Option<u32>) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.set_recovery_window(&task, minutes)).await
|
||||
}
|
||||
|
||||
/// Arms or clears the one-shot auto-resume flag on active/interrupted tasks before window close.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_set_auto_resume_once(host: &Host, window: &str, tasks: Vec<String>, enabled: bool) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || {
|
||||
agents.set_auto_resume_once(&tasks, enabled);
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Wakes any task waiting in the transient network outage loop so reachability is probed now.
|
||||
#[command(trust = always)]
|
||||
pub fn agent_poke_network(host: &Host, window: &str) -> IdeResult<()> {
|
||||
host.project(window)?.agents.poke_network();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reconciles interrupted tasks once per `AgentManager` incarnation according to the user's
|
||||
/// recovery policy and safety guardrails.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_reconcile_interrupted(host: &Host, window: &str) -> IdeResult<AgentRecoveryReport> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || Ok(agents.reconcile_interrupted())).await
|
||||
}
|
||||
|
||||
/// Stops one of the task's background tasks.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_stop_background(host: &Host, window: &str, task: String, background: String) -> IdeResult<()> {
|
||||
@@ -1602,25 +1676,36 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn prepare_login_launch_env_marks_remote_sessions_for_device_code_auth() {
|
||||
let mut desktop_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(false, true, &mut desktop_env, |_| false);
|
||||
assert!(desktop_env.is_empty());
|
||||
let mut desktop_agent_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(false, false, &mut desktop_agent_env, |_| false);
|
||||
assert!(desktop_agent_env.is_empty());
|
||||
|
||||
let mut desktop_gh_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(false, true, &mut desktop_gh_env, |_| false);
|
||||
assert_eq!(desktop_gh_env.get("GLAMOUR_STYLE").map(String::as_str), Some("notty"));
|
||||
assert!(!desktop_gh_env.contains_key("REMOTE_CONTAINERS"));
|
||||
assert!(!desktop_gh_env.contains_key("GH_BROWSER"));
|
||||
|
||||
let mut remote_agent_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, false, &mut remote_agent_env, |_| false);
|
||||
assert_eq!(remote_agent_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
|
||||
assert!(!remote_agent_env.contains_key("GH_BROWSER"));
|
||||
assert!(!remote_agent_env.contains_key("GLAMOUR_STYLE"));
|
||||
|
||||
let mut remote_gh_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, true, &mut remote_gh_env, |_| false);
|
||||
assert_eq!(remote_gh_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
|
||||
assert_eq!(remote_gh_env.get("GH_BROWSER").map(String::as_str), Some("true"));
|
||||
assert_eq!(remote_gh_env.get("GLAMOUR_STYLE").map(String::as_str), Some("notty"));
|
||||
|
||||
// Preserves existing SSH/remote indicators and explicit browser settings.
|
||||
// Preserves existing SSH/remote indicators, browser settings, and GLAMOUR_STYLE.
|
||||
let mut ssh_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, true, &mut ssh_env, |k| matches!(k, "SSH_CONNECTION" | "BROWSER"));
|
||||
prepare_login_launch_env(true, true, &mut ssh_env, |k| {
|
||||
matches!(k, "SSH_CONNECTION" | "BROWSER" | "GLAMOUR_STYLE")
|
||||
});
|
||||
assert!(!ssh_env.contains_key("REMOTE_CONTAINERS"));
|
||||
assert!(!ssh_env.contains_key("GH_BROWSER"));
|
||||
assert!(!ssh_env.contains_key("GLAMOUR_STYLE"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1639,6 +1724,7 @@ ide_command::domain!(
|
||||
agent_copilot_auth_status,
|
||||
agent_create,
|
||||
agent_delete,
|
||||
agent_dismiss_interrupted,
|
||||
agent_entries,
|
||||
agent_external_sessions,
|
||||
agent_fork,
|
||||
@@ -1648,6 +1734,7 @@ ide_command::domain!(
|
||||
agent_hermes_profiles,
|
||||
agent_import_session,
|
||||
agent_login_spawn,
|
||||
agent_mark_read,
|
||||
agent_mcp_discover_sources,
|
||||
agent_mcp_import,
|
||||
agent_mcp_import_selected,
|
||||
@@ -1657,25 +1744,31 @@ ide_command::domain!(
|
||||
agent_mcp_save_json,
|
||||
agent_mcp_set_enabled,
|
||||
agent_mcp_test,
|
||||
agent_poke_network,
|
||||
agent_preview_copilot_models,
|
||||
agent_probe,
|
||||
agent_prompt,
|
||||
agent_providers,
|
||||
agent_reconcile_interrupted,
|
||||
agent_refresh_models,
|
||||
agent_registry_install,
|
||||
agent_registry_list,
|
||||
agent_registry_remove,
|
||||
agent_rename,
|
||||
agent_respond,
|
||||
agent_resume_all_interrupted,
|
||||
agent_resume_task,
|
||||
agent_rollback,
|
||||
agent_rollback_changes,
|
||||
agent_send_queued_now,
|
||||
agent_set_additional_args,
|
||||
agent_set_auto_resume_once,
|
||||
agent_set_command,
|
||||
agent_shell,
|
||||
agent_set_config,
|
||||
agent_set_env,
|
||||
agent_set_mcp_overrides,
|
||||
agent_set_recovery_window,
|
||||
agent_set_skill_overrides,
|
||||
agent_skills_browse,
|
||||
agent_skills_install,
|
||||
|
||||
@@ -329,6 +329,20 @@ pub async fn db_table_details(
|
||||
db.table_details(&id, &schema, &table).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_catalog_table_details(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
catalog: String,
|
||||
schema: String,
|
||||
table: String,
|
||||
) -> IdeResult<TableDetails> {
|
||||
// Columns and keys in an attached DuckDB catalog on the source session.
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.catalog_table_details(&id, &catalog, &schema, &table).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_table_grants(
|
||||
host: &Host,
|
||||
@@ -657,6 +671,41 @@ pub async fn db_table_page(
|
||||
result
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_catalog_table_page(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
id: String,
|
||||
catalog: String,
|
||||
schema: String,
|
||||
table: String,
|
||||
filter: Option<String>,
|
||||
sort: Vec<SortKey>,
|
||||
offset: u32,
|
||||
limit: u32,
|
||||
) -> IdeResult<TablePage> {
|
||||
// One read-only page from the explicit DuckDB catalog on the source session.
|
||||
let db = host.project(window)?.db.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = db
|
||||
.catalog_table_page(
|
||||
&id,
|
||||
&catalog,
|
||||
&schema,
|
||||
&table,
|
||||
filter.as_deref(),
|
||||
&sort,
|
||||
offset.into(),
|
||||
limit.max(1).into(),
|
||||
&cancel,
|
||||
)
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_apply_edits(
|
||||
host: &Host,
|
||||
@@ -788,6 +837,8 @@ ide_command::domain!(
|
||||
db_consoles,
|
||||
db_create_database,
|
||||
db_database_catalog,
|
||||
db_catalog_table_details,
|
||||
db_catalog_table_page,
|
||||
db_databases,
|
||||
db_ddl,
|
||||
db_disconnect,
|
||||
|
||||
@@ -62,8 +62,16 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
python.as_deref(),
|
||||
config.cwd.as_deref(),
|
||||
);
|
||||
let plots = super::plots::prepare(host, &project);
|
||||
super::python::prepare_debug(&mut config, &paths, plots.as_ref())?;
|
||||
let conda = super::python::conda_prefix(&host.config_dir, &project, python.as_deref(), config.cwd.as_deref());
|
||||
let plots = super::plots::prepare(host, &project).await;
|
||||
// The debuggee inherits the IDE's environment as a run started in its folder does.
|
||||
let dir = config.cwd.as_deref().map(|c| c.to_path_buf()).unwrap_or_else(|| project.root.clone());
|
||||
super::python::prepare_debug(
|
||||
&mut config,
|
||||
&paths,
|
||||
plots.as_ref().map(|p| (p, dir.as_path())),
|
||||
conda.as_deref(),
|
||||
)?;
|
||||
}
|
||||
let label = window;
|
||||
let (sink, flush_output) = output::coalescing_sink(host.window_sink(label));
|
||||
|
||||
@@ -56,6 +56,20 @@ pub async fn doc_save_as(host: &Host, window: &str, doc: DocId, path: PathBuf) -
|
||||
.await
|
||||
}
|
||||
|
||||
/// Copies the current buffer, including unsaved edits, without changing the source; false for the source itself.
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_copy_as(host: &Host, window: &str, doc: DocId, path: PathBuf) -> IdeResult<bool> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || {
|
||||
let copied = project.documents.copy_as(doc, &path)?;
|
||||
if let Some(dir) = path.parent().filter(|_| project.light) {
|
||||
project.watch_light_dir(dir);
|
||||
}
|
||||
Ok(copied)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Applies a CodeMirror change set; returns the new version. Rejects with
|
||||
/// `outOfSync` when `base_version` is stale; the UI then calls `doc_snapshot`.
|
||||
#[command(trust = always, desktop_body = async)]
|
||||
@@ -141,6 +155,7 @@ mod tests;
|
||||
ide_command::domain!(
|
||||
doc:
|
||||
doc_close,
|
||||
doc_copy_as,
|
||||
doc_edit,
|
||||
doc_open,
|
||||
doc_open_untitled,
|
||||
|
||||
@@ -111,6 +111,36 @@ async fn dirty_document_keeps_edits_and_warns_once() {
|
||||
assert!(f.document_events().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn save_as_copies_the_current_buffer_and_leaves_the_source_on_disk() {
|
||||
let f = Fixture::new();
|
||||
let original = f.open(&f.path).await;
|
||||
doc_edit(
|
||||
&f.host,
|
||||
"main",
|
||||
original.id,
|
||||
original.version,
|
||||
ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "local ".into() }] },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let target = f.outside.with_extension("copy.txt");
|
||||
std::fs::write(&target, "old\n").unwrap();
|
||||
|
||||
assert!(doc_copy_as(&f.host, "main", original.id, target.clone()).await.unwrap());
|
||||
|
||||
assert_eq!(std::fs::read_to_string(&f.path).unwrap(), "original\n");
|
||||
assert_eq!(std::fs::read_to_string(&target).unwrap(), "local original\n");
|
||||
let source = f.project.documents.snapshot(original.id).unwrap();
|
||||
assert_eq!(source.path, f.path);
|
||||
assert_eq!(source.text, "local original\n");
|
||||
assert!(source.dirty);
|
||||
let copy = f.open(&target).await;
|
||||
assert_ne!(copy.id, original.id);
|
||||
assert_eq!(copy.text, "local original\n");
|
||||
assert!(!copy.dirty);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn deleted_document_keeps_its_buffer_and_other_documents_still_reload() {
|
||||
let f = Fixture::new();
|
||||
|
||||
@@ -158,24 +158,28 @@ pub async fn fs_read_dir(host: &Host, window: &str, path: PathBuf) -> IdeResult<
|
||||
// Runs on the blocking pool: on a network share (`\\wsl.localhost`) every stat is slow.
|
||||
let project = host.project(window);
|
||||
host.blocking(move || {
|
||||
let excludes = project
|
||||
.map(|p| {
|
||||
// An attached project's folders follow its own exclusions.
|
||||
let root = p.root_of(&path);
|
||||
let globs = p.exclude_globs_in(&root);
|
||||
// `read_dir` matches relative to the enclosing repository: re-anchor
|
||||
// root patterns (`/build`) when the project is a repo subfolder.
|
||||
let repo = root.ancestors().find(|d| d.join(".git").exists());
|
||||
match repo.and_then(|r| root.strip_prefix(r).ok()).filter(|rel| !rel.as_os_str().is_empty()) {
|
||||
Some(rel) => {
|
||||
let rel = rel.to_string_lossy().replace('\\', "/");
|
||||
globs.into_iter().map(|g| if g.starts_with('/') { format!("/{rel}{g}") } else { g }).collect()
|
||||
}
|
||||
None => globs,
|
||||
let Ok(p) = project else { return ide_vfs::read_dir(&path, &[]) };
|
||||
// An attached project's folders follow its own exclusions.
|
||||
let root = p.root_of(&path);
|
||||
let globs = p.exclude_globs_in(&root);
|
||||
// `read_dir` matches relative to the enclosing repository: re-anchor
|
||||
// root patterns (`/build`) when the project is a repo subfolder. The
|
||||
// watcher already found the project folder's repository; on a network
|
||||
// share each `.git` probe up the tree is a round trip.
|
||||
let repo = if root == p.root && p.watcher.root() == p.root {
|
||||
p.watcher.repo_root().map(Path::to_path_buf)
|
||||
} else {
|
||||
root.ancestors().find(|d| d.join(".git").exists()).map(Path::to_path_buf)
|
||||
};
|
||||
let excludes =
|
||||
match repo.as_deref().and_then(|r| root.strip_prefix(r).ok()).filter(|rel| !rel.as_os_str().is_empty()) {
|
||||
Some(rel) => {
|
||||
let rel = rel.to_string_lossy().replace('\\', "/");
|
||||
globs.into_iter().map(|g| if g.starts_with('/') { format!("/{rel}{g}") } else { g }).collect()
|
||||
}
|
||||
})
|
||||
.unwrap_or_default();
|
||||
ide_vfs::read_dir(&path, &excludes)
|
||||
None => globs,
|
||||
};
|
||||
p.watcher.read_dir(&path, &excludes)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
//! GitHub pull requests (`ide-github`, through the `gh` CLI) for the project of the window.
|
||||
//!
|
||||
//! Runs on the project host (`Host` locally, `openidea-server` in a remote window) so remote
|
||||
//! SSH / WSL / dev-container projects use the remote host's `gh` CLI, repository, and
|
||||
//! project-scoped `GH_TOKEN`.
|
||||
|
||||
use super::{Channel, blocking};
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult, RequestId};
|
||||
use ide_github::{
|
||||
CreatePullRequest, GhAccountRepos, GhApiRequest, GhAvailability, PrDiffRevisions, PrListQuery, PrReviewComment,
|
||||
PullRequestDetails, PullRequestSummary, ReviewEvent,
|
||||
};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The working directory of gh: the project repository `repo` names, else the project's
|
||||
/// primary repository (a folder holding several repositories is not one itself).
|
||||
fn root(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<PathBuf> {
|
||||
let project = host.project(window)?;
|
||||
let repos = project.repos();
|
||||
match repo {
|
||||
Some(at) => match repos.at_root(&at) {
|
||||
Some(r) => Ok(r.root().to_path_buf()),
|
||||
None => Err(IdeError::unavailable(format!("{} is not a git repository of the project", at.display()))),
|
||||
},
|
||||
None => Ok(repos.primary().map_or_else(|| project.root.clone(), |r| r.root().to_path_buf())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits `VcsChanged` after operations that move HEAD or refs (checkout, push).
|
||||
fn vcs_changed(host: &Host, window: &str, root: &Path) {
|
||||
if let Ok(p) = host.project(window) {
|
||||
p.sink.emit(ide_core::IdeEvent::VcsChanged { root: ide_core::IpcPath(root.to_path_buf()) });
|
||||
}
|
||||
}
|
||||
|
||||
/// The repositories of the account gh is signed in to ("Get from Version Control" › GitHub); needs no project.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn gh_account_repos() -> IdeResult<GhAccountRepos> {
|
||||
blocking(|| Ok(ide_github::account_repositories())).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_availability(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<GhAvailability> {
|
||||
let project = host.project(window)?;
|
||||
let root = root(host, window, repo)?;
|
||||
blocking(move || {
|
||||
crate::github_auth::apply_to_project(&project);
|
||||
Ok(ide_github::availability(&root))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_pr_list(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
query: PrListQuery,
|
||||
) -> IdeResult<Vec<PullRequestSummary>> {
|
||||
let root = root(host, window, repo)?;
|
||||
blocking(move || ide_github::list(&root, &query)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_pr_view(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
number: u32,
|
||||
) -> IdeResult<PullRequestDetails> {
|
||||
let root = root(host, window, repo)?;
|
||||
blocking(move || ide_github::view(&root, number)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_pr_review_comments(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
number: u32,
|
||||
) -> IdeResult<Vec<PrReviewComment>> {
|
||||
let root = root(host, window, repo)?;
|
||||
blocking(move || ide_github::review_comments(&root, number)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_pr_checkout(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
request: RequestId,
|
||||
number: u32,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let root = root(host, window, repo)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let dir = root.clone();
|
||||
let result = blocking(move || {
|
||||
ide_github::checkout(&dir, number, &cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
vcs_changed(host, window, &root);
|
||||
result
|
||||
}
|
||||
|
||||
/// Creates a pull request from the current branch (pushing it first when asked); returns its URL.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_pr_create(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
request: RequestId,
|
||||
pr: CreatePullRequest,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<String> {
|
||||
let root = root(host, window, repo)?;
|
||||
let git = host.project(window)?.git_executable();
|
||||
let cancel = host.begin_request(request);
|
||||
let dir = root.clone();
|
||||
let result = blocking(move || {
|
||||
ide_vcs::with_git_executable(git.as_deref(), || {
|
||||
ide_github::create(&dir, &pr, &cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
vcs_changed(host, window, &root);
|
||||
result
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_pr_review(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
number: u32,
|
||||
event: ReviewEvent,
|
||||
body: String,
|
||||
) -> IdeResult<()> {
|
||||
let root = root(host, window, repo)?;
|
||||
blocking(move || ide_github::submit_review(&root, number, event, &body)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_pr_comment(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
number: u32,
|
||||
body: String,
|
||||
) -> IdeResult<()> {
|
||||
let root = root(host, window, repo)?;
|
||||
blocking(move || ide_github::add_comment(&root, number, &body)).await
|
||||
}
|
||||
|
||||
/// A GitHub GraphQL / REST call through `gh api`; returns the response body.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn gh_api(host: &Host, window: &str, repo: Option<PathBuf>, request: GhApiRequest) -> IdeResult<String> {
|
||||
let root = root(host, window, repo)?;
|
||||
blocking(move || ide_github::api(&root, &request)).await
|
||||
}
|
||||
|
||||
/// Fetches what is missing to diff a pull request locally; returns the revisions to compare.
|
||||
#[command(trust = trusted)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn gh_pr_prepare_diff(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
request: RequestId,
|
||||
number: u32,
|
||||
head_oid: String,
|
||||
base_oid: String,
|
||||
base_ref: String,
|
||||
name_with_owner: String,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<PrDiffRevisions> {
|
||||
let root = root(host, window, repo)?;
|
||||
let git = host.project(window)?.git_executable();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let output = |line: String| {
|
||||
let _ = on_output.send(line);
|
||||
};
|
||||
ide_vcs::with_git_executable(git.as_deref(), || {
|
||||
ide_github::prepare_diff(&root, number, &head_oid, &base_oid, &base_ref, &name_with_owner, &cancel, &output)
|
||||
})
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
github:
|
||||
gh_account_repos,
|
||||
gh_api,
|
||||
gh_availability,
|
||||
gh_pr_checkout,
|
||||
gh_pr_comment,
|
||||
gh_pr_create,
|
||||
gh_pr_list,
|
||||
gh_pr_prepare_diff,
|
||||
gh_pr_review,
|
||||
gh_pr_review_comments,
|
||||
gh_pr_view,
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::root;
|
||||
use crate::catalogue::TrustClass;
|
||||
use crate::rpc::Dispatcher;
|
||||
use crate::{Host, HostConfig};
|
||||
use ide_core::error::ErrorKind;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn test_host(base: &Path) -> Host {
|
||||
Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("local"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(|_| {})),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registers_github_commands_on_the_remote_rpc_dispatcher() {
|
||||
let dispatcher = Dispatcher::standard();
|
||||
assert_eq!(dispatcher.trust("gh_account_repos"), Some(TrustClass::OutsideRestricted));
|
||||
for name in [
|
||||
"gh_api",
|
||||
"gh_availability",
|
||||
"gh_pr_checkout",
|
||||
"gh_pr_comment",
|
||||
"gh_pr_create",
|
||||
"gh_pr_list",
|
||||
"gh_pr_prepare_diff",
|
||||
"gh_pr_review",
|
||||
"gh_pr_review_comments",
|
||||
"gh_pr_view",
|
||||
] {
|
||||
assert_eq!(dispatcher.trust(name), Some(TrustClass::Trusted), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authorizes_account_repos_without_a_project_and_scopes_repo_lookup_to_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let host = test_host(dir.path());
|
||||
assert!(host.authorize("main", TrustClass::OutsideRestricted).is_ok());
|
||||
let err = host.authorize("main", TrustClass::Trusted).unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::NotFound);
|
||||
|
||||
let proj_dir = dir.path().join("repo");
|
||||
std::fs::create_dir_all(&proj_dir).unwrap();
|
||||
host.open_project("main", &proj_dir).unwrap();
|
||||
assert_eq!(root(&host, "main", None).unwrap(), dunce::canonicalize(&proj_dir).unwrap());
|
||||
let outsider = root(&host, "main", Some(dir.path().join("other"))).unwrap_err();
|
||||
assert_eq!(outsider.kind, ErrorKind::Unavailable);
|
||||
}
|
||||
}
|
||||
@@ -84,7 +84,7 @@ pub(crate) async fn resolve_launch(
|
||||
let build = policy != BuildPolicy::NoBuild;
|
||||
let full = policy == BuildPolicy::Rebuild;
|
||||
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, external, mut delegated, is_maven, non_java, served) = {
|
||||
let (model, external, mut delegated, is_maven, non_java, served, needs_cleanup) = {
|
||||
let scope = scope.clone();
|
||||
let launches = launches.clone();
|
||||
let module = module.clone();
|
||||
@@ -95,16 +95,11 @@ pub(crate) async fn resolve_launch(
|
||||
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
|
||||
let is_maven = is_maven_module(root, &model, &module);
|
||||
let served = served_by_service(root, &model, &scope.settings, &module);
|
||||
let delegated = build
|
||||
&& delegates_to_external_build(
|
||||
is_maven,
|
||||
policy,
|
||||
non_java,
|
||||
cache::has_record(root, &scope.cache, &module),
|
||||
prefer_maven,
|
||||
);
|
||||
let needs_cleanup = build && is_maven && cache::needs_cleanup(root, &scope.cache, &model, &module, test);
|
||||
let delegated =
|
||||
build && delegates_to_external_build(is_maven, policy, non_java, needs_cleanup, prefer_maven);
|
||||
let external = non_java || delegated;
|
||||
(std::sync::Arc::new(model), external, delegated, is_maven, non_java, served)
|
||||
(std::sync::Arc::new(model), external, delegated, is_maven, non_java, served, needs_cleanup)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
@@ -117,7 +112,7 @@ pub(crate) async fn resolve_launch(
|
||||
// the launch debugs with java-debug, whose HotSwap reloads what jdtls compiles (ecj's
|
||||
// classes differ from javac's: lambda names). jdtls keeps building for its diagnostics
|
||||
// either way.
|
||||
if served && !non_java && !debug {
|
||||
if served && !non_java && !debug && !needs_cleanup {
|
||||
let built = {
|
||||
let (service, data_dir, scope, model, module, cancel, events) = (
|
||||
host.java_build.clone(),
|
||||
@@ -806,7 +801,7 @@ fn joining_launches(
|
||||
is_maven,
|
||||
o.policy,
|
||||
compile::launch_has_non_java_sources(root, model, &o.module, test),
|
||||
cache::has_record(root, cache_dir, &o.module),
|
||||
is_maven && cache::needs_cleanup(root, cache_dir, model, &o.module, test),
|
||||
prefer_maven,
|
||||
)
|
||||
})
|
||||
@@ -820,10 +815,10 @@ fn delegates_to_external_build(
|
||||
is_maven: bool,
|
||||
policy: BuildPolicy,
|
||||
non_java: bool,
|
||||
has_record: bool,
|
||||
needs_cleanup: bool,
|
||||
prefer_maven: bool,
|
||||
) -> bool {
|
||||
is_maven && (prefer_maven || policy == BuildPolicy::Rebuild || non_java || has_record)
|
||||
is_maven && (prefer_maven || policy == BuildPolicy::Rebuild || non_java || needs_cleanup)
|
||||
}
|
||||
|
||||
fn same_entry(a: &str, b: &str, windows: bool) -> bool {
|
||||
@@ -1288,6 +1283,54 @@ mod tests {
|
||||
assert!(!delegates_to_external_build(false, BuildPolicy::Automatic, false, false, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_builds_do_not_join_plain_java_launches_only_because_of_legacy_null_records() {
|
||||
use std::{fs, sync::Arc};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let cache_dir = root.join("cache");
|
||||
fs::write(
|
||||
root.join("pom.xml"),
|
||||
concat!(
|
||||
"<project><groupId>sample</groupId><artifactId>root</artifactId><version>1</version>",
|
||||
"<packaging>pom</packaging><modules><module>leader</module><module>plain</module>",
|
||||
"<module>dirty</module></modules></project>",
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
for name in ["leader", "plain", "dirty"] {
|
||||
let module = root.join(name);
|
||||
fs::create_dir_all(module.join("src/main/java")).unwrap();
|
||||
fs::write(module.join("src/main/java/Main.java"), "class Main {}").unwrap();
|
||||
fs::write(
|
||||
module.join("pom.xml"),
|
||||
format!(
|
||||
"<project><groupId>sample</groupId><artifactId>{name}</artifactId><version>1</version></project>"
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let records = cache_dir.join("java-launch/records").join(name);
|
||||
fs::create_dir_all(&records).unwrap();
|
||||
fs::write(records.join("main.json"), b"null").unwrap();
|
||||
}
|
||||
fs::create_dir_all(root.join("dirty/target/classes")).unwrap();
|
||||
fs::write(root.join("dirty/target/classes/Old.class"), "old-output").unwrap();
|
||||
let model = ide_build::load(root, &cache_dir, None);
|
||||
let waiting = ["plain", "dirty"]
|
||||
.into_iter()
|
||||
.map(|name| {
|
||||
Arc::new(cache::WaitingLaunch {
|
||||
module: root.join(name),
|
||||
test: false,
|
||||
policy: BuildPolicy::Automatic,
|
||||
events: None,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let joined = joining_launches(root, &cache_dir, &model, &root.join("leader"), false, waiting, false);
|
||||
assert_eq!(joined.iter().map(|launch| &launch.module).collect::<Vec<_>>(), [&root.join("dirty")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_external_compilation_does_not_erase_scoped_jdt_errors() {
|
||||
for (failure, expected) in
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
//! Immutable Maven outputs retained in the project cache, including across close/reopen.
|
||||
mod delegation;
|
||||
|
||||
use ide_build::compile::{self, BuildEvent, LaunchFingerprint};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use ide_run::BuildPolicy;
|
||||
@@ -127,8 +129,14 @@ fn record_path(root: &Path, cache: &Path, module: &Path, test: bool) -> Option<P
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn has_record(root: &Path, cache: &Path, module: &Path) -> bool {
|
||||
[false, true].into_iter().any(|test| record_path(root, cache, module, test).is_some_and(|record| record.is_file()))
|
||||
pub(super) fn needs_cleanup(
|
||||
root: &Path,
|
||||
cache: &Path,
|
||||
model: &ide_build::BuildModel,
|
||||
module: &Path,
|
||||
test: bool,
|
||||
) -> bool {
|
||||
delegation::required(root, cache, model, module, test)
|
||||
}
|
||||
|
||||
/// Where the build of a launch streams its console, messages and progress: the run
|
||||
@@ -233,6 +241,8 @@ struct Pending {
|
||||
record: PathBuf,
|
||||
before: Option<LaunchFingerprint>,
|
||||
previous: Option<Outputs>,
|
||||
non_java: bool,
|
||||
cleanup: bool,
|
||||
}
|
||||
|
||||
/// Owned by Project: running JVMs may still load superseded outputs until it drops.
|
||||
@@ -296,13 +306,13 @@ impl Session {
|
||||
// clean rebuild that replaces JDT's error-stub classes.
|
||||
let policy = if rebuild_on_jdt_errors { BuildPolicy::Rebuild } else { policy };
|
||||
let mut joined = Vec::new();
|
||||
let mut rebuild = policy == BuildPolicy::Rebuild;
|
||||
let mut rebuild = policy == BuildPolicy::Rebuild || lead.cleanup;
|
||||
let mut sinks: Vec<LaunchEvents> = events.into_iter().collect();
|
||||
for member in members {
|
||||
if let Err(pending) =
|
||||
self.prepare(root, model, &member.module, test, BuildPolicy::Make, &local_repo, cancel)?
|
||||
{
|
||||
rebuild |= member.rebuild_on_jdt_errors;
|
||||
rebuild |= member.rebuild_on_jdt_errors || pending.cleanup;
|
||||
sinks.extend(member.events);
|
||||
joined.push(pending);
|
||||
}
|
||||
@@ -366,6 +376,9 @@ impl Session {
|
||||
let snapshots = self.cache.join("java-launch/snapshots");
|
||||
let mut before = fingerprint(root, model, module, test, local_repo, cancel)?;
|
||||
let previous = fs::read(&record).ok().and_then(|bytes| serde_json::from_slice::<Outputs>(&bytes).ok());
|
||||
let non_java = compile::launch_has_non_java_sources(root, model, module, test);
|
||||
let needs_cleanup = needs_cleanup(root, &self.cache, model, module, test);
|
||||
let cleanup = needs_cleanup && !non_java;
|
||||
// Timestamp-incremental builders (Maven, the Kotlin plugin) skip sources whose
|
||||
// mtime did not advance. An external edit that preserves both length and mtime
|
||||
// invalidates the fingerprint but would still compile to nothing below, and the
|
||||
@@ -388,6 +401,7 @@ impl Session {
|
||||
}
|
||||
if let Some(outputs) = previous.as_ref()
|
||||
&& policy != BuildPolicy::Rebuild
|
||||
&& !cleanup
|
||||
&& let Some(maven) = &model.maven
|
||||
&& outputs.reusable(
|
||||
&before,
|
||||
@@ -405,14 +419,18 @@ impl Session {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
// Retain a non-reusable record even on failure, so removing the final mixed
|
||||
// source still delegates to Maven to clean its old classes on the next launch.
|
||||
fs::create_dir_all(record.parent().unwrap())?;
|
||||
fs::write(&record, b"null")?;
|
||||
// Preserve build ownership independently of the reusable snapshot. In particular,
|
||||
// a plain Java build that fails must not force delegation after the user disables it.
|
||||
delegation::remember(root, &self.cache, module, test, non_java || needs_cleanup)?;
|
||||
match fs::remove_file(&record) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
if let Some(previous) = &previous {
|
||||
self.unreferenced.push(previous.snapshot.clone());
|
||||
}
|
||||
Ok(Err(Pending { module: module.to_path_buf(), record, before, previous }))
|
||||
Ok(Err(Pending { module: module.to_path_buf(), record, before, previous, non_java, cleanup }))
|
||||
}
|
||||
|
||||
/// Copies the built outputs of a prepared module into a new snapshot and records it
|
||||
@@ -487,6 +505,10 @@ impl Session {
|
||||
write_record(&pending.record, &outputs)?;
|
||||
self.unreferenced.retain(|path| path != &outputs.snapshot);
|
||||
}
|
||||
if outputs.failure.is_none() && authoritative {
|
||||
let mixed = pending.non_java || compile::launch_has_non_java_sources(root, model, &pending.module, test);
|
||||
delegation::cleaned(root, &self.cache, &pending.module, test, mixed)?;
|
||||
}
|
||||
Ok(outputs)
|
||||
}
|
||||
}
|
||||
@@ -509,7 +531,7 @@ fn fingerprint(
|
||||
}
|
||||
}
|
||||
|
||||
fn write_record(record: &Path, outputs: &Outputs) -> IdeResult<()> {
|
||||
fn write_record(record: &Path, outputs: &impl Serialize) -> IdeResult<()> {
|
||||
fs::create_dir_all(record.parent().unwrap())?;
|
||||
let mut file = tempfile::NamedTempFile::new_in(record.parent().unwrap())?;
|
||||
serde_json::to_writer(file.as_file_mut(), outputs).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
@@ -530,7 +552,7 @@ impl Drop for Session {
|
||||
}
|
||||
|
||||
/// Clears the fingerprint of every launch record under `cache`, so no snapshot matches the
|
||||
/// sources any more. The records stay: their modules keep delegating to Maven.
|
||||
/// sources any more. Delegation ownership is stored separately and is not invalidated.
|
||||
fn forget_reusable_snapshots(cache: &Path) -> std::io::Result<()> {
|
||||
let records = cache.join("java-launch/records");
|
||||
if !records.try_exists()? {
|
||||
@@ -609,6 +631,231 @@ fn sweep(cache: &Path) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod delegation_tests {
|
||||
use super::*;
|
||||
|
||||
fn fixture(root: &Path, mixed: bool) -> ide_build::BuildModel {
|
||||
fs::write(
|
||||
root.join("pom.xml"),
|
||||
r#"<project><groupId>sample</groupId><artifactId>app</artifactId><version>1</version></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("src/main/java")).unwrap();
|
||||
fs::write(root.join("src/main/java/Main.java"), "java-source").unwrap();
|
||||
if mixed {
|
||||
fs::create_dir_all(root.join("src/main/kotlin")).unwrap();
|
||||
fs::write(root.join("src/main/kotlin/Extra.kt"), "mixed-source").unwrap();
|
||||
}
|
||||
// A synthetic Maven wrapper: no JDK, Maven installation or network required.
|
||||
#[cfg(windows)]
|
||||
fs::write(root.join("mvnw.cmd"), concat!(
|
||||
"@echo off\r\necho %*>>calls\r\n",
|
||||
"if exist fail-build exit /b 1\r\n",
|
||||
"for %%a in (%*) do if \"%%a\"==\"clean\" if exist target rmdir /s /q target\r\n",
|
||||
"if not exist target\\classes mkdir target\\classes\r\n",
|
||||
"copy /y src\\main\\java\\Main.java target\\classes\\Main.class >nul\r\n",
|
||||
"if exist src\\main\\kotlin\\Extra.kt copy /y src\\main\\kotlin\\Extra.kt target\\classes\\Extra.class >nul\r\n",
|
||||
"if exist edit-during-build echo changed>>src\\main\\java\\Main.java\r\n",
|
||||
"if exist block-record (\r\n",
|
||||
"if not exist cache\\java-launch\\records mkdir cache\\java-launch\\records\r\n",
|
||||
"if exist cache\\java-launch\\records\\main.json del /q cache\\java-launch\\records\\main.json\r\n",
|
||||
"mkdir cache\\java-launch\\records\\main.json\r\n",
|
||||
")\r\n",
|
||||
"exit /b 0\r\n",
|
||||
)).unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let script = root.join("mvnw");
|
||||
fs::write(&script, concat!(
|
||||
"#!/bin/sh\nset -e\nprintf '%s\\n' \"$*\" >> calls\n",
|
||||
"if [ -f fail-build ]; then exit 1; fi\n",
|
||||
"for arg in \"$@\"; do if [ \"$arg\" = clean ]; then rm -rf target; fi; done\n",
|
||||
"mkdir -p target/classes\ncp src/main/java/Main.java target/classes/Main.class\n",
|
||||
"if [ -f src/main/kotlin/Extra.kt ]; then cp src/main/kotlin/Extra.kt target/classes/Extra.class; fi\n",
|
||||
"if [ -f edit-during-build ]; then echo changed >> src/main/java/Main.java; fi\n",
|
||||
"if [ -f block-record ]; then\n",
|
||||
"mkdir -p cache/java-launch/records\nrm -f cache/java-launch/records/main.json\n",
|
||||
"mkdir cache/java-launch/records/main.json\nfi\n",
|
||||
)).unwrap();
|
||||
fs::set_permissions(script, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
ide_build::load(root, &root.join("cache"), None)
|
||||
}
|
||||
|
||||
fn legacy(root: &Path, test: bool, bytes: &[u8]) {
|
||||
let record = record_path(root, &root.join("cache"), root, test).unwrap();
|
||||
fs::create_dir_all(record.parent().unwrap()).unwrap();
|
||||
fs::write(record, bytes).unwrap();
|
||||
}
|
||||
|
||||
fn calls(root: &Path) -> Vec<String> {
|
||||
fs::read_to_string(root.join("calls")).unwrap_or_default().lines().map(str::to_owned).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_record_publication_keeps_new_and_previous_snapshots_until_session_drop() {
|
||||
for has_previous in [false, true] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root, false);
|
||||
let cache = root.join("cache");
|
||||
let cancel = CancellationToken::new();
|
||||
let mut session = Session::new(cache.clone());
|
||||
if has_previous {
|
||||
session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
}
|
||||
fs::write(root.join("src/main/java/Main.java"), "edited-java-source").unwrap();
|
||||
fs::write(root.join("block-record"), "").unwrap();
|
||||
let error = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap_err();
|
||||
// Reach publication, rather than accepting an earlier wrapper/build failure.
|
||||
assert!(!error.message.starts_with("Build failed:"), "{error:?}");
|
||||
assert!(cache.join("java-launch/records/main.json").is_dir());
|
||||
assert_eq!(session.unreferenced.len(), if has_previous { 2 } else { 1 });
|
||||
let snapshots = session.unreferenced.clone();
|
||||
assert_eq!(
|
||||
fs::read_to_string(snapshots.last().unwrap().join("0/Main.class")).unwrap(),
|
||||
"edited-java-source"
|
||||
);
|
||||
assert!(snapshots.iter().all(|p| p.join("0/Main.class").is_file()));
|
||||
drop(session);
|
||||
assert!(snapshots.iter().all(|p| !p.exists()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_record_without_outputs_does_not_keep_delegation() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let cache = root.join("cache");
|
||||
let model = fixture(root, false);
|
||||
legacy(root, false, b"null");
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
// The IDE's Java builder may produce outputs afterwards: migration must stick.
|
||||
fs::create_dir_all(root.join("target/classes")).unwrap();
|
||||
fs::write(root.join("target/classes/Main.class"), "java-output").unwrap();
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
assert!(calls(root).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_java_failures_and_unpublished_snapshots_do_not_require_maven() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root, false);
|
||||
let cache = root.join("cache");
|
||||
let cancel = CancellationToken::new();
|
||||
let mut session = Session::new(cache.clone());
|
||||
fs::write(root.join("fail-build"), "").unwrap();
|
||||
assert!(session.build(root, &model, root, BuildOptions::default(), None, &cancel).is_err());
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
fs::remove_file(root.join("fail-build")).unwrap();
|
||||
fs::write(root.join("edit-during-build"), "").unwrap();
|
||||
let outputs = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert!(outputs.fingerprint.is_none());
|
||||
assert!(!cache.join("java-launch/records/main.json").exists());
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
// A valid snapshot is also not a reason to override the user's build preference.
|
||||
fs::remove_file(root.join("edit-during-build")).unwrap();
|
||||
session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert!(cache.join("java-launch/records/main.json").is_file());
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_null_or_damaged_records_with_outputs_are_cleaned_once() {
|
||||
for bytes in [b"null".as_slice(), b"{invalid".as_slice()] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root, false);
|
||||
let cache = root.join("cache");
|
||||
legacy(root, false, bytes);
|
||||
fs::create_dir_all(root.join("target/classes")).unwrap();
|
||||
fs::write(root.join("target/classes/Old.class"), "unknown-old-output").unwrap();
|
||||
assert!(needs_cleanup(root, &cache, &model, root, false));
|
||||
let mut session = Session::new(cache.clone());
|
||||
session.build(root, &model, root, BuildOptions::default(), None, &CancellationToken::new()).unwrap();
|
||||
drop(session);
|
||||
assert!(!root.join("target/classes/Old.class").exists());
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
assert_eq!(calls(root).len(), 1);
|
||||
assert!(calls(root)[0].contains("clean"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legacy_reusable_snapshot_cannot_skip_pending_cleanup() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root, false);
|
||||
let cache = root.join("cache");
|
||||
let cancel = CancellationToken::new();
|
||||
let mut session = Session::new(cache.clone());
|
||||
let before = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
// Simulate a successful record written before ownership was tracked separately.
|
||||
fs::remove_file(cache.join("java-launch/delegation/main.json")).unwrap();
|
||||
assert!(needs_cleanup(root, &cache, &model, root, false));
|
||||
let after = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert_ne!(before.snapshot, after.snapshot);
|
||||
assert_eq!(calls(root).len(), 2);
|
||||
assert!(calls(root)[1].contains("clean"));
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_cleanup_survives_failure_and_reopen_then_releases_delegation() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root, true);
|
||||
let cache = root.join("cache");
|
||||
let cancel = CancellationToken::new();
|
||||
let mut session = Session::new(cache.clone());
|
||||
session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert!(root.join("target/classes/Extra.class").is_file());
|
||||
fs::remove_file(root.join("src/main/kotlin/Extra.kt")).unwrap();
|
||||
fs::write(root.join("fail-build"), "").unwrap();
|
||||
assert!(session.build(root, &model, root, BuildOptions::default(), None, &cancel).is_err());
|
||||
drop(session);
|
||||
assert!(needs_cleanup(root, &cache, &model, root, false));
|
||||
fs::remove_file(root.join("fail-build")).unwrap();
|
||||
let mut session = Session::new(cache.clone());
|
||||
session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert!(!root.join("target/classes/Extra.class").exists());
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
assert_eq!(calls(root).len(), 3);
|
||||
assert!(calls(root)[1..].iter().all(|call| call.contains("clean")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cleanup_does_not_force_a_main_launch_and_a_clean_test_build_releases_both_modes() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root, false);
|
||||
let cache = root.join("cache");
|
||||
legacy(root, true, b"null");
|
||||
fs::create_dir_all(root.join("target/test-classes")).unwrap();
|
||||
fs::write(root.join("target/test-classes/OldTest.class"), "old-test-output").unwrap();
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
assert!(needs_cleanup(root, &cache, &model, root, true));
|
||||
delegation::remember(root, &cache, root, false, true).unwrap();
|
||||
let mut session = Session::new(cache.clone());
|
||||
session
|
||||
.build(
|
||||
root,
|
||||
&model,
|
||||
root,
|
||||
BuildOptions { test: true, ..Default::default() },
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, false));
|
||||
assert!(!needs_cleanup(root, &cache, &model, root, true));
|
||||
assert!(!root.join("target/test-classes/OldTest.class").exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -864,7 +1111,7 @@ mod tests {
|
||||
// Build › Rebuild cleans the outputs and compiles again.
|
||||
fs::remove_file(root.join("target/classes/Stale.class")).unwrap();
|
||||
session.forget_reusable_snapshots();
|
||||
assert!(has_record(root, &root.join("cache"), root));
|
||||
assert!(needs_cleanup(root, &root.join("cache"), &model, root, false));
|
||||
let next = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert_ne!(next.snapshot, first.snapshot);
|
||||
assert!(!next.snapshot.join("0/Stale.class").exists());
|
||||
@@ -943,7 +1190,7 @@ mod tests {
|
||||
assert_ne!(rebuilt.snapshot, updated.snapshot);
|
||||
fs::write(root.join("src/main/kotlin/broken"), "broken").unwrap();
|
||||
assert!(build().is_err());
|
||||
assert_eq!(fs::read(cache.join("java-launch/records/main.json")).unwrap(), b"null");
|
||||
assert!(!cache.join("java-launch/records/main.json").exists());
|
||||
fs::remove_file(root.join("src/main/kotlin/broken")).unwrap();
|
||||
assert_ne!(rebuilt.snapshot, build().unwrap().snapshot, "a failed build invalidates success");
|
||||
cancel.cancel();
|
||||
@@ -1097,11 +1344,16 @@ mod tests {
|
||||
let model = fixture(root);
|
||||
let script = root.join("mvnw");
|
||||
let mut text = fs::read_to_string(&script).unwrap();
|
||||
text.push_str("rm cache/java-launch/records/main.json\nmkdir cache/java-launch/records/main.json\n");
|
||||
// Snapshot invalidation no longer writes a null record or creates its parent.
|
||||
// Arrange a publish failure independently of that earlier implementation detail.
|
||||
text.push_str("mkdir -p cache/java-launch/records\nrm -f cache/java-launch/records/main.json\nmkdir cache/java-launch/records/main.json\n");
|
||||
fs::write(script, text).unwrap();
|
||||
let cache = root.join("cache");
|
||||
let mut session = Session::new(cache.clone());
|
||||
assert!(session.build(root, &model, root, BuildOptions::default(), None, &CancellationToken::new()).is_err());
|
||||
let error =
|
||||
session.build(root, &model, root, BuildOptions::default(), None, &CancellationToken::new()).unwrap_err();
|
||||
assert!(!error.message.starts_with("Build failed:"), "{error:?}");
|
||||
assert!(cache.join("java-launch/records/main.json").is_dir());
|
||||
assert_eq!(session.unreferenced.len(), 1);
|
||||
let snapshot = session.unreferenced[0].clone();
|
||||
assert!(snapshot.join("0/Main.class").is_file());
|
||||
@@ -1123,7 +1375,7 @@ mod tests {
|
||||
let outputs =
|
||||
session.build(root, &model, root, BuildOptions::default(), None, &CancellationToken::new()).unwrap();
|
||||
assert!(outputs.fingerprint.is_none());
|
||||
assert_eq!(fs::read(cache.join("java-launch/records/main.json")).unwrap(), b"null");
|
||||
assert!(!cache.join("java-launch/records/main.json").exists());
|
||||
assert!(outputs.snapshot.join("0/Main.class").is_file());
|
||||
drop(session);
|
||||
assert!(!outputs.snapshot.exists());
|
||||
@@ -1265,9 +1517,9 @@ mod tests {
|
||||
let first = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
fs::remove_file(root.join("src/main/kotlin/Main.kt")).unwrap();
|
||||
assert!(!compile::launch_has_non_java_sources(root, &model, root, false));
|
||||
assert!(has_record(root, &cache, root));
|
||||
assert!(needs_cleanup(root, &cache, &model, root, false));
|
||||
assert!(session.build(root, &model, root, BuildOptions::default(), None, &cancel).is_err());
|
||||
assert!(has_record(root, &cache, root));
|
||||
assert!(needs_cleanup(root, &cache, &model, root, false));
|
||||
fs::write(root.join("src/main/kotlin/Main.kt"), "restored").unwrap();
|
||||
let restored = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert_ne!(first.snapshot, restored.snapshot);
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//! Build ownership is independent of whether a launch snapshot can be reused.
|
||||
use super::{record_path, write_record};
|
||||
use ide_build::{BuildModel, compile};
|
||||
use ide_core::IdeResult;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct State {
|
||||
/// External outputs may contain classes that JDT cannot remove after the final
|
||||
/// Kotlin/Groovy/Scala source is deleted. Only a successful clean clears this.
|
||||
needs_cleanup: bool,
|
||||
}
|
||||
|
||||
fn state_path(root: &Path, cache: &Path, module: &Path, test: bool) -> Option<PathBuf> {
|
||||
Some(cache.join("java-launch/delegation").join(module.strip_prefix(root).ok()?).join(if test {
|
||||
"test.json"
|
||||
} else {
|
||||
"main.json"
|
||||
}))
|
||||
}
|
||||
|
||||
/// A test launch also uses main outputs; a main launch does not use test outputs.
|
||||
pub(super) fn required(root: &Path, cache: &Path, model: &BuildModel, module: &Path, test: bool) -> bool {
|
||||
mode_required(root, cache, model, module, false) || (test && mode_required(root, cache, model, module, true))
|
||||
}
|
||||
|
||||
fn mode_required(root: &Path, cache: &Path, model: &BuildModel, module: &Path, test: bool) -> bool {
|
||||
let Some(state) = state_path(root, cache, module, test) else { return false };
|
||||
match fs::read(&state) {
|
||||
Ok(bytes) => {
|
||||
// A damaged ownership marker must not silently abandon pending cleanup.
|
||||
return serde_json::from_slice::<State>(&bytes).map_or(true, |state| state.needs_cleanup);
|
||||
}
|
||||
Err(e) if e.kind() == ErrorKind::NotFound => {}
|
||||
Err(_) => return true,
|
||||
}
|
||||
let Some(record) = record_path(root, cache, module, test).filter(|p| p.is_file()) else { return false };
|
||||
let Some(maven) = &model.maven else { return false };
|
||||
// Old records (including `null`) did not record why Maven owned the outputs.
|
||||
// If outputs remain, clean once rather than guessing that they are all Java.
|
||||
// Persist even a negative migration: subsequent JDT output must not turn an
|
||||
// already ignored legacy record back into a reason to delegate.
|
||||
let needs_cleanup = compile::maven_launch_output_dirs(root, maven, module, test).iter().any(|dir| dir.is_dir());
|
||||
let publish = || -> std::io::Result<()> {
|
||||
fs::create_dir_all(state.parent().unwrap())?;
|
||||
let mut file = tempfile::NamedTempFile::new_in(state.parent().unwrap())?;
|
||||
serde_json::to_writer(file.as_file_mut(), &State { needs_cleanup })?;
|
||||
// Another launch may already have migrated or started building this mode.
|
||||
file.persist_noclobber(&state).map_err(|e| e.error)?;
|
||||
Ok(())
|
||||
};
|
||||
match publish() {
|
||||
Ok(()) => needs_cleanup,
|
||||
Err(e) if e.kind() == ErrorKind::AlreadyExists => mode_required(root, cache, model, module, test),
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, path = %record.display(), "Cannot migrate Java launch delegation state");
|
||||
needs_cleanup
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Called before invalidating a snapshot or running an external build. A plain
|
||||
/// Java failure records `false`; it must not override a later delegateBuild=false.
|
||||
pub(super) fn remember(root: &Path, cache: &Path, module: &Path, test: bool, needs_cleanup: bool) -> IdeResult<()> {
|
||||
if let Some(path) = state_path(root, cache, module, test) {
|
||||
write_record(&path, &State { needs_cleanup })?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn cleaned(root: &Path, cache: &Path, module: &Path, test: bool, mixed: bool) -> IdeResult<()> {
|
||||
remember(root, cache, module, test, mixed)?;
|
||||
if test && !mixed {
|
||||
// A clean test build includes the main outputs and their reactor dependencies.
|
||||
remember(root, cache, module, false, false)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -17,6 +17,7 @@ pub mod docker;
|
||||
pub mod env;
|
||||
pub mod flutter;
|
||||
pub mod fs;
|
||||
pub mod github;
|
||||
pub mod heap;
|
||||
pub mod history;
|
||||
pub mod host_metrics;
|
||||
@@ -27,17 +28,19 @@ pub mod lsp;
|
||||
pub mod maven_placeholder;
|
||||
pub mod nav;
|
||||
pub mod notebook;
|
||||
mod plots;
|
||||
pub mod plots;
|
||||
pub mod project;
|
||||
pub mod pytest_fixtures;
|
||||
mod python;
|
||||
pub mod python_stubs;
|
||||
pub mod refactor;
|
||||
pub mod routes;
|
||||
pub mod rst;
|
||||
pub mod run;
|
||||
pub mod scaffold;
|
||||
pub mod sdk;
|
||||
pub mod search;
|
||||
pub mod settings_sync;
|
||||
pub mod spell;
|
||||
pub mod ssh;
|
||||
pub mod stream_trace;
|
||||
@@ -47,6 +50,7 @@ pub mod thread_dump;
|
||||
pub mod tools;
|
||||
pub mod vcs;
|
||||
pub mod web;
|
||||
pub mod xcode_bsp;
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
@@ -94,6 +98,7 @@ ide_command::domains!(
|
||||
env: crate::ops::env,
|
||||
flutter: crate::ops::flutter,
|
||||
fs: crate::ops::fs,
|
||||
github: crate::ops::github,
|
||||
heap: crate::ops::heap,
|
||||
history: crate::ops::history,
|
||||
host_metrics: crate::ops::host_metrics,
|
||||
@@ -105,6 +110,7 @@ ide_command::domains!(
|
||||
mcp_reports: crate::mcp::reports,
|
||||
nav: crate::ops::nav,
|
||||
notebook: crate::ops::notebook,
|
||||
plots: crate::ops::plots,
|
||||
plugins_commands: crate::plugins::commands,
|
||||
plugins_commit: crate::plugins::commit,
|
||||
plugins_index_ops: crate::plugins::index_ops,
|
||||
@@ -113,6 +119,7 @@ ide_command::domains!(
|
||||
plugins_views: crate::plugins::views,
|
||||
project: crate::ops::project,
|
||||
refactor: crate::ops::refactor,
|
||||
rst: crate::ops::rst,
|
||||
run: crate::ops::run,
|
||||
run_commands: crate::ops::run::commands,
|
||||
scaffold: crate::ops::scaffold,
|
||||
@@ -130,6 +137,7 @@ ide_command::domains!(
|
||||
vcs: crate::ops::vcs,
|
||||
vcs_commands: crate::ops::vcs::commands,
|
||||
web: crate::ops::web,
|
||||
xcode_bsp: crate::ops::xcode_bsp,
|
||||
);
|
||||
|
||||
/// A blocking task that panicked or was cancelled, as the error a command returns.
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
use super::blocking;
|
||||
use super::pytest_fixtures::{PytestFixtureAt, PytestFixtureUsages, fixture_at, fixture_usages, rename_fixture};
|
||||
use super::pytest_fixtures::{
|
||||
PytestFixtureAt, PytestFixtureRename, PytestFixtureTarget, PytestFixtureUsages, fixture_at, fixture_target,
|
||||
fixture_usages, rename_fixture,
|
||||
};
|
||||
use super::python_stubs::{
|
||||
PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path,
|
||||
};
|
||||
use crate::Host;
|
||||
use crate::Project;
|
||||
use ide_command::command;
|
||||
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos, RequestId, WorkspaceEdit};
|
||||
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos, RequestId};
|
||||
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
|
||||
use ide_language::{CSS_VARIABLE, FileReference, WebReference};
|
||||
use ide_workspace::file_refs::{self, PathCompletion};
|
||||
@@ -522,8 +525,30 @@ pub async fn nav_pytest_fixture_usages(
|
||||
result
|
||||
}
|
||||
|
||||
/// The pytest fixture at `pos` (its definition, a place asking for it, or a read of such a
|
||||
/// parameter in a function body), without searching the project: what Rename renames.
|
||||
#[command(trust = always)]
|
||||
pub async fn nav_pytest_fixture_target(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
) -> IdeResult<Option<PytestFixtureTarget>> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if snap.large || snap.language.as_str() != "python" {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(fixture_target(&project, &syntax, &snap.path, &snap.text, pos))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Rename of the pytest fixture at `pos`: its definition, every place that gets it and the
|
||||
/// uses of those parameters in their functions. Cancellable.
|
||||
/// reads of those parameters in their functions; or the parameter or fixture the new name
|
||||
/// would clash with. Cancellable.
|
||||
#[command(trust = always)]
|
||||
pub async fn nav_pytest_fixture_rename(
|
||||
host: &Host,
|
||||
@@ -532,19 +557,19 @@ pub async fn nav_pytest_fixture_rename(
|
||||
pos: Pos,
|
||||
new_name: String,
|
||||
request: RequestId,
|
||||
) -> IdeResult<WorkspaceEdit> {
|
||||
) -> IdeResult<PytestFixtureRename> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
let token = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
let mut edit =
|
||||
let mut renamed =
|
||||
rename_fixture(&project, &syntax, &snap.path, &snap.text, pos, &new_name, &|| token.is_cancelled())?;
|
||||
if token.is_cancelled() {
|
||||
return Err(ide_core::IdeError::cancelled());
|
||||
}
|
||||
project.documents.prepare_workspace_edit(&mut edit)?;
|
||||
Ok(edit)
|
||||
project.documents.prepare_workspace_edit(&mut renamed.edit)?;
|
||||
Ok(renamed)
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
@@ -565,6 +590,7 @@ ide_command::domain!(
|
||||
nav_index_definitions,
|
||||
nav_inheritance,
|
||||
nav_pytest_fixture_rename,
|
||||
nav_pytest_fixture_target,
|
||||
nav_pytest_fixture_usages,
|
||||
nav_pytest_fixtures,
|
||||
nav_python_stubs,
|
||||
|
||||
@@ -4,6 +4,7 @@ pub use crate::notebook::NotebookOutputEvent;
|
||||
use crate::ops::Channel;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult, RequestId};
|
||||
use ide_notebook::kernel::{KernelSpec, KernelTarget, RemoteKernel, kernel_specs, normalize_server_url};
|
||||
use ide_notebook::{NotebookEdit, NotebookSnapshot};
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -122,8 +123,23 @@ pub async fn notebook_execute(
|
||||
let _request = RequestGuard { host, request, cancel: cancel.clone() };
|
||||
// Reserve the WHOLE batch and capture source before asynchronous discovery.
|
||||
let admission = project.notebooks.admit(&id, cells, cancel.clone())?;
|
||||
let target = kernel_target(host, &project, python, &cancel).await?;
|
||||
project.notebooks.execute(admission, target, on_output).await
|
||||
}
|
||||
|
||||
/// The kernel the notebook's drop-down chose: an interpreter (the project's when `None`) or
|
||||
/// `<server>#<kernel spec>` of a saved Jupyter server.
|
||||
async fn kernel_target(
|
||||
host: &Host,
|
||||
project: &crate::Project,
|
||||
python: Option<String>,
|
||||
cancel: &ide_core::CancellationToken,
|
||||
) -> IdeResult<KernelTarget> {
|
||||
let selected = match python {
|
||||
Some(path) if path.trim().is_empty() => return Err(IdeError::invalid("select a Python interpreter")),
|
||||
Some(kernel) if kernel.starts_with("http://") || kernel.starts_with("https://") => {
|
||||
return Ok(KernelTarget::Remote(remote_kernel(host, &kernel)?));
|
||||
}
|
||||
Some(path) => PathBuf::from(path),
|
||||
None => {
|
||||
let root = project.root.clone();
|
||||
@@ -142,8 +158,92 @@ pub async fn notebook_execute(
|
||||
};
|
||||
// Do not canonicalize this path: resolving a venv symlink to base Python
|
||||
// changes sys.prefix and executes in the wrong environment.
|
||||
let python = if selected.is_absolute() { selected } else { project.root.join(selected) };
|
||||
project.notebooks.execute(admission, python, on_output).await
|
||||
Ok(KernelTarget::Local(if selected.is_absolute() { selected } else { project.root.join(selected) }))
|
||||
}
|
||||
|
||||
/// Debug Cell: a debug session named `name` on the notebook's kernel, starting the kernel
|
||||
/// when none runs. The caller then runs the cell; ending the session leaves the kernel and
|
||||
/// its state running.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn notebook_debug_start(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
python: Option<String>,
|
||||
name: String,
|
||||
just_my_code: bool,
|
||||
) -> IdeResult<ide_core::DebugSessionId> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let cancel = project.closed.child_token();
|
||||
let target = kernel_target(host, &project, python, &cancel).await?;
|
||||
let (debugger, cells, notebook_cells) = project.notebooks.debugger(&id, target, cancel).await?;
|
||||
let (reader, writer) = tokio::io::split(ide_notebook::kernel::debug::dap_stream(debugger, cells));
|
||||
let io = ide_dap::adapter::AdapterIo {
|
||||
launch_after_configuration: false,
|
||||
reader: Box::new(reader),
|
||||
writer: Box::new(writer),
|
||||
child: None,
|
||||
port: None,
|
||||
stderr: Default::default(),
|
||||
program_output: None,
|
||||
};
|
||||
let owner = ide_dap::SessionOwner::new(host.owner_window(window), host.window_sink(window));
|
||||
let arguments = serde_json::json!({ "justMyCode": just_my_code });
|
||||
host.debugger.start_over(io, name, ide_dap::NOTEBOOK_ADAPTER.into(), arguments, owner, Some(notebook_cells)).await
|
||||
}
|
||||
|
||||
/// A kernel choice on a Jupyter server, `<server base URL>#<kernel spec>`, with its saved token.
|
||||
fn remote_kernel(host: &Host, choice: &str) -> IdeResult<RemoteKernel> {
|
||||
let (base, spec) = choice
|
||||
.split_once('#')
|
||||
.filter(|(_, spec)| !spec.is_empty())
|
||||
.ok_or_else(|| IdeError::invalid("select a kernel of the Jupyter server"))?;
|
||||
let token = host.jupyter_tokens.get(base).ok_or_else(|| {
|
||||
IdeError::unavailable(format!("connect to the Jupyter server {base} again: its token is not saved"))
|
||||
})?;
|
||||
Ok(RemoteKernel { base: base.to_owned(), token, spec: spec.to_owned() })
|
||||
}
|
||||
|
||||
/// A Jupyter server notebooks can run on.
|
||||
#[derive(serde::Serialize, specta::Type)]
|
||||
pub struct JupyterServer {
|
||||
/// Base URL, ending in `/`.
|
||||
pub url: String,
|
||||
pub kernels: Vec<KernelSpec>,
|
||||
}
|
||||
|
||||
/// Checks `url` and `token` against the server and saves them. A `?token=` in the URL
|
||||
/// (as JupyterLab prints it) is used when `token` is empty.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn jupyter_server_add(host: &Host, window: &str, url: String, token: String) -> IdeResult<JupyterServer> {
|
||||
host.require_trust(window)?;
|
||||
let (url, in_url) = normalize_server_url(&url)?;
|
||||
let token = if token.trim().is_empty() { in_url.unwrap_or_default() } else { token.trim().to_owned() };
|
||||
let kernels = kernel_specs(&url, &token).await?;
|
||||
host.jupyter_tokens.set(&url, &token)?;
|
||||
Ok(JupyterServer { url, kernels })
|
||||
}
|
||||
|
||||
/// The saved servers and their kernel specs; a server that cannot be reached has none.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn jupyter_servers(host: &Host, window: &str) -> IdeResult<Vec<JupyterServer>> {
|
||||
host.require_trust(window)?;
|
||||
let servers = host.jupyter_tokens.keys().into_iter().map(|url| async move {
|
||||
let kernels = match host.jupyter_tokens.get(&url) {
|
||||
Some(token) => kernel_specs(&url, &token).await.unwrap_or_default(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
JupyterServer { url, kernels }
|
||||
});
|
||||
Ok(futures::future::join_all(servers).await)
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub fn jupyter_server_remove(host: &Host, window: &str, url: String) -> IdeResult<()> {
|
||||
let _ = window;
|
||||
host.jupyter_tokens.delete(&url);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct RequestGuard<'a> {
|
||||
@@ -162,8 +262,12 @@ impl Drop for RequestGuard<'_> {
|
||||
|
||||
ide_command::domain!(
|
||||
notebook:
|
||||
jupyter_server_add,
|
||||
jupyter_server_remove,
|
||||
jupyter_servers,
|
||||
notebook_cell_docs,
|
||||
notebook_close,
|
||||
notebook_debug_start,
|
||||
notebook_edit,
|
||||
notebook_execute,
|
||||
notebook_get,
|
||||
|
||||
@@ -2,25 +2,37 @@
|
||||
//! [`ide_run::plots`]) reach the window as [`IdeEvent::PlotAdded`].
|
||||
use crate::Host;
|
||||
use crate::project::Project;
|
||||
use ide_core::IdeEvent;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeEvent, IdeResult, SharedSink};
|
||||
use ide_run::plots::Plots;
|
||||
use notify::{RecursiveMode, Watcher};
|
||||
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The backend and plots folder for a Python run of `project`, installed and watched on first use;
|
||||
/// `None` when Settings › Python turns the tool window off.
|
||||
pub(crate) fn prepare(host: &Host, project: &Project) -> Option<Plots> {
|
||||
/// The backend and plots folder for a Python run of `project`, installed and watched on first use
|
||||
/// (off the async runtime: the first use empties the folder); `None` when Settings › Python turns
|
||||
/// the tool window off.
|
||||
pub(crate) async fn prepare(host: &Host, project: &Arc<Project>) -> Option<Plots> {
|
||||
if !project.settings.effective().languages.python.show_plots_in_tool_window {
|
||||
return None;
|
||||
}
|
||||
let plots = Plots { backend: host.local_data_dir.join("matplotlib-backend"), dir: project.cache_dir.join("plots") };
|
||||
match ide_run::plots::install(&plots.backend).and_then(|()| watch(project, &plots.dir)) {
|
||||
Ok(()) => Some(plots),
|
||||
Err(e) => {
|
||||
let (project, target) = (project.clone(), plots.clone());
|
||||
let ready = super::blocking_value(move || {
|
||||
ide_run::plots::install(&target.backend).and_then(|()| watch(&project, &target.dir))
|
||||
})
|
||||
.await;
|
||||
match ready {
|
||||
Ok(Ok(())) => Some(plots),
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!("cannot set up the Plots tool window in {}: {e}", plots.dir.display());
|
||||
None
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("cannot set up the Plots tool window: {}", e.message);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,8 +44,13 @@ fn watch(project: &Project, dir: &Path) -> io::Result<()> {
|
||||
// Figures of an earlier session are not shown again.
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let sink = project.sink.clone();
|
||||
// Every event of a finished PNG is sent (create, rename, modify); the window keeps each path once.
|
||||
*slot = Some(watch_dir(dir, project.sink.clone())?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sends `PlotAdded` for each finished figure in `dir`. A file can be reported more than once
|
||||
/// (created, renamed, modified); the window lists each path once.
|
||||
fn watch_dir(dir: &Path, sink: SharedSink) -> io::Result<RecommendedWatcher> {
|
||||
let mut watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
|
||||
for path in res.map(|e| e.paths).unwrap_or_default() {
|
||||
if is_plot(&path) && path.is_file() {
|
||||
@@ -43,8 +60,7 @@ fn watch(project: &Project, dir: &Path) -> io::Result<()> {
|
||||
})
|
||||
.map_err(io::Error::other)?;
|
||||
watcher.watch(dir, RecursiveMode::NonRecursive).map_err(io::Error::other)?;
|
||||
*slot = Some(watcher);
|
||||
Ok(())
|
||||
Ok(watcher)
|
||||
}
|
||||
|
||||
/// A finished figure: the backend writes `.<name>.png` first, then renames it.
|
||||
@@ -53,9 +69,32 @@ fn is_plot(path: &Path) -> bool {
|
||||
&& path.file_name().is_some_and(|n| !n.to_string_lossy().starts_with('.'))
|
||||
}
|
||||
|
||||
/// Deletes figures the Plots tool window dropped; only figures in this project's plots folder.
|
||||
#[command(trust = always)]
|
||||
pub async fn plots_delete(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<()> {
|
||||
let dir = host.project(window)?.cache_dir.join("plots");
|
||||
super::blocking_value(move || delete(&dir, &paths)).await
|
||||
}
|
||||
|
||||
/// Paths are compared canonicalized: the watcher reports real paths, and the cache folder may be
|
||||
/// reached through a symlink.
|
||||
fn delete(dir: &Path, paths: &[PathBuf]) {
|
||||
let Ok(dir) = dunce::canonicalize(dir) else { return };
|
||||
let in_dir = |p: &Path| p.parent().and_then(|d| dunce::canonicalize(d).ok()).is_some_and(|d| d == dir);
|
||||
for path in paths.iter().filter(|p| is_plot(p) && in_dir(p)) {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
plots:
|
||||
plots_delete,
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[test]
|
||||
fn only_finished_pngs_are_plots() {
|
||||
@@ -63,4 +102,45 @@ mod tests {
|
||||
assert!(!is_plot(Path::new("/c/plots/.1-2-0.png")));
|
||||
assert!(!is_plot(Path::new("/c/plots/notes.txt")));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn deletes_only_finished_figures_in_the_plots_folder_through_a_symlink() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let real = tmp.path().join("real");
|
||||
std::fs::create_dir_all(real.join("plots")).unwrap();
|
||||
std::fs::create_dir_all(real.join("other")).unwrap();
|
||||
std::os::unix::fs::symlink(&real, tmp.path().join("link")).unwrap();
|
||||
let files = [real.join("plots/1-2-0.png"), real.join("plots/.1-2-1.png"), real.join("other/1-2-2.png")];
|
||||
for f in &files {
|
||||
std::fs::write(f, b"png").unwrap();
|
||||
}
|
||||
let reported: Vec<_> = files.iter().map(|f| dunce::canonicalize(f).unwrap()).collect();
|
||||
delete(&tmp.path().join("link/plots"), &reported);
|
||||
assert_eq!(files.map(|f| f.exists()), [false, true, true]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_a_figure_once_it_is_renamed_into_place() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let sink: SharedSink = Arc::new(move |e: IdeEvent| {
|
||||
let _ = tx.send(e);
|
||||
});
|
||||
let _watch = watch_dir(&dir, sink).unwrap();
|
||||
std::fs::write(dir.join(".1-2-0.png"), b"png").unwrap();
|
||||
std::fs::rename(dir.join(".1-2-0.png"), dir.join("1-2-0.png")).unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
let mut seen = Vec::new();
|
||||
while Instant::now() < deadline {
|
||||
if let Ok(IdeEvent::PlotAdded { path }) = rx.recv_timeout(Duration::from_millis(200)) {
|
||||
seen.push(path);
|
||||
} else if !seen.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(!seen.is_empty(), "no PlotAdded event");
|
||||
assert!(seen.iter().all(|p| p.ends_with("1-2-0.png") && !p.ends_with(".1-2-0.png")), "{seen:?}");
|
||||
}
|
||||
}
|
||||
@@ -149,7 +149,8 @@ pub fn settings_set(
|
||||
|
||||
/// Effective source / test / resource / excluded roots of the window's project:
|
||||
/// auto-detected from build files, overridden by Settings › Project Structure.
|
||||
#[command(trust = always)]
|
||||
/// Off the UI thread: Gradle source roots may walk the project for builds, slow on a share.
|
||||
#[command(trust = always, desktop_body = spawn)]
|
||||
pub fn project_roots(host: &Host, window: &str) -> IdeResult<ide_workspace::ProjectRoots> {
|
||||
Ok(host.project(window)?.roots())
|
||||
}
|
||||
@@ -492,7 +493,10 @@ pub fn set_settings(
|
||||
|| key.starts_with("inspections.")
|
||||
|| key == "files"
|
||||
|| key == "files.composeFileOverrides"
|
||||
|| key.starts_with("files.composeFileOverrides.");
|
||||
|| key.starts_with("files.composeFileOverrides.")
|
||||
// JSON Schema Mappings reach the JSON and YAML servers as settings.
|
||||
|| key == "jsonSchemas"
|
||||
|| key.starts_with("jsonSchemas.");
|
||||
let toolchain = ["languages", "tools", "languageServers", "projectStructure"]
|
||||
.iter()
|
||||
.any(|k| key == *k || key.starts_with(&format!("{k}.")));
|
||||
|
||||
@@ -133,8 +133,62 @@ impl Scope {
|
||||
out.push((file, m));
|
||||
}
|
||||
}
|
||||
out
|
||||
// A fixture imported into a project module is that module's own, right after it.
|
||||
let mut layers = Vec::with_capacity(out.len());
|
||||
for (file, m) in out {
|
||||
let imported =
|
||||
if is_project_file(project, &file) { self.imported(project, syntax, &file, &m) } else { Vec::new() };
|
||||
layers.push((file, m));
|
||||
layers.extend(imported);
|
||||
}
|
||||
layers
|
||||
}
|
||||
|
||||
/// The fixtures `module` (the file `path`) imports, one layer per module imported from, each
|
||||
/// named as it is bound here.
|
||||
fn imported(&self, project: &Project, syntax: &Syntax, path: &Path, module: &PytestModule) -> Vec<Layer> {
|
||||
let mut out: Vec<(PathBuf, PytestModule)> = Vec::new();
|
||||
for import in &module.imports {
|
||||
let Some(file) = import_file(&import.module, path, &self.search) else { continue };
|
||||
let Some(from) = module_of(project, syntax, &file) else { continue };
|
||||
let picked = from.fixtures.iter().filter(|f| f.class.is_none()).filter_map(|f| {
|
||||
let star = import.name == "*" && !f.function.starts_with('_');
|
||||
if !star && f.function != import.name {
|
||||
return None;
|
||||
}
|
||||
// pytest takes the name a fixture is bound to, unless `name=` gives one.
|
||||
let name = if f.by_argument || star { f.name.clone() } else { import.alias.clone() };
|
||||
Some(ide_language::PytestFixture { name, ..f.clone() })
|
||||
});
|
||||
let picked: Vec<_> = picked.collect();
|
||||
if picked.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match out.iter_mut().find(|(p, _)| *p == file) {
|
||||
Some((_, m)) => m.fixtures.extend(picked),
|
||||
None => out.push((file, PytestModule { fixtures: picked, ..Default::default() })),
|
||||
}
|
||||
}
|
||||
out.into_iter().map(|(p, m)| (p, Arc::new(m))).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The file of `module` imported from `path`: relative (`.fixtures`, `..`) from its folder, else
|
||||
/// from the import search path.
|
||||
fn import_file(module: &str, path: &Path, search: &[PathBuf]) -> Option<PathBuf> {
|
||||
let rest = module.trim_start_matches('.');
|
||||
let dots = module.len() - rest.len();
|
||||
if dots == 0 {
|
||||
return module_file(module, search);
|
||||
}
|
||||
let mut base = path.parent()?;
|
||||
for _ in 1..dots {
|
||||
base = base.parent()?;
|
||||
}
|
||||
if rest.is_empty() {
|
||||
return Some(base.join("__init__.py")).filter(|p| p.is_file());
|
||||
}
|
||||
module_file(rest, &[base.to_path_buf()])
|
||||
}
|
||||
|
||||
/// A fixture definition: its file and the range of its name there.
|
||||
@@ -143,16 +197,30 @@ struct Definition {
|
||||
name: String,
|
||||
path: PathBuf,
|
||||
selection: Range,
|
||||
/// Named by its function (no `name=`): renaming it renames the function.
|
||||
function_name: bool,
|
||||
}
|
||||
|
||||
impl Definition {
|
||||
fn of(path: &Path, fixture: &ide_language::PytestFixture) -> Self {
|
||||
Self {
|
||||
name: fixture.name.clone(),
|
||||
path: path.to_path_buf(),
|
||||
selection: fixture.selection,
|
||||
function_name: !fixture.by_argument,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where pytest finds the fixture `u` asks for, seen from `layers`.
|
||||
fn definition_of(layers: &[Layer], u: &ide_language::PytestFixtureUse) -> Option<Definition> {
|
||||
let modules: Vec<&PytestModule> = layers.iter().map(|(_, m)| m.as_ref()).collect();
|
||||
let (l, f) = resolve_fixture(&modules, &u.name, u.class.as_deref(), u.in_fixture.as_deref() == Some(&u.name))?;
|
||||
Some(Definition { name: u.name.clone(), path: layers[l].0.clone(), selection: modules[l].fixtures[f].selection })
|
||||
Some(Definition::of(&layers[l].0, &modules[l].fixtures[f]))
|
||||
}
|
||||
|
||||
/// The fixture at `pos` of `path`: the one defined there, or the one a test asks for there.
|
||||
/// The fixture at `pos` of `path` and the range of its name there: the one defined there, the
|
||||
/// one a test asks for there, or the one whose parameter a function body reads there.
|
||||
fn target_at(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
@@ -160,13 +228,50 @@ fn target_at(
|
||||
path: &Path,
|
||||
own: &Arc<PytestModule>,
|
||||
pos: Pos,
|
||||
) -> Option<Definition> {
|
||||
) -> Option<(Definition, Range)> {
|
||||
if let Some(f) = own.definition_at(pos) {
|
||||
let fixture = &own.fixtures[f];
|
||||
return Some(Definition { name: fixture.name.clone(), path: path.to_path_buf(), selection: fixture.selection });
|
||||
return Some((Definition::of(path, fixture), fixture.selection));
|
||||
}
|
||||
let usage = own.use_at(pos)?;
|
||||
definition_of(&scope.layers(project, syntax, path, own.clone()), usage)
|
||||
let (usage, range) = own.use_or_read_at(pos)?;
|
||||
Some((definition_of(&scope.layers(project, syntax, path, own.clone()), usage)?, range))
|
||||
}
|
||||
|
||||
/// The pytest fixture at a position, found without searching the project (for Rename to
|
||||
/// decide what it renames before asking for the new name).
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PytestFixtureTarget {
|
||||
pub name: String,
|
||||
/// The name at the position: a definition, a place asking for the fixture, or a read of
|
||||
/// such a parameter in a function body.
|
||||
pub range: Range,
|
||||
pub definition: Location,
|
||||
/// Defined in the project (not by a plugin or pytest): it may be renamed.
|
||||
pub in_project: bool,
|
||||
/// Named by its function (no `name=`): Python code may refer to the function too.
|
||||
pub function_name: bool,
|
||||
}
|
||||
|
||||
pub(crate) fn fixture_target(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
path: &Path,
|
||||
text: &str,
|
||||
pos: Pos,
|
||||
) -> Option<PytestFixtureTarget> {
|
||||
let own = Arc::new(syntax.pytest_module(&python(), text));
|
||||
if own.definition_at(pos).is_none() && own.use_or_read_at(pos).is_none() {
|
||||
return None;
|
||||
}
|
||||
let (target, range) = target_at(project, syntax, &Scope::new(project), path, &own, pos)?;
|
||||
Some(PytestFixtureTarget {
|
||||
name: target.name.clone(),
|
||||
range,
|
||||
in_project: is_project_file(project, &target.path),
|
||||
function_name: target.function_name,
|
||||
definition: Location { path: IpcPath::from(target.path), range: target.selection, uri: None },
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
@@ -174,8 +279,6 @@ fn target_at(
|
||||
pub struct PytestFixtureUsages {
|
||||
pub name: String,
|
||||
pub definition: Location,
|
||||
/// Defined in the project (not by a plugin or pytest): it may be renamed.
|
||||
pub in_project: bool,
|
||||
/// Every place that gets this fixture: parameters, `usefixtures` and `getfixturevalue` strings.
|
||||
pub usages: Vec<Location>,
|
||||
}
|
||||
@@ -183,9 +286,12 @@ pub struct PytestFixtureUsages {
|
||||
struct Usage {
|
||||
path: PathBuf,
|
||||
use_: ide_language::PytestFixtureUse,
|
||||
/// The modules its file sees, as `Scope::layers` gives them.
|
||||
layers: Arc<Vec<Layer>>,
|
||||
}
|
||||
|
||||
/// The fixture at `pos` of the Python document `path` / `text` and every place that gets it.
|
||||
/// The fixture at `pos` of the Python document `path` / `text` (a definition or a place asking
|
||||
/// for it) and every place that gets it.
|
||||
pub(crate) fn fixture_usages(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
@@ -194,10 +300,14 @@ pub(crate) fn fixture_usages(
|
||||
pos: Pos,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> IdeResult<Option<PytestFixtureUsages>> {
|
||||
let Some((target, usages)) = usages_of(project, syntax, path, text, pos, cancelled)? else { return Ok(None) };
|
||||
let own = Arc::new(syntax.pytest_module(&python(), text));
|
||||
// Find Usages on a read in a body stays the language server's (the parameter's uses).
|
||||
if own.definition_at(pos).is_none() && own.use_at(pos).is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some((target, usages)) = usages_of(project, syntax, path, own, pos, cancelled)? else { return Ok(None) };
|
||||
Ok(Some(PytestFixtureUsages {
|
||||
name: target.name.clone(),
|
||||
in_project: is_project_file(project, &target.path),
|
||||
definition: Location { path: IpcPath::from(target.path), range: target.selection, uri: None },
|
||||
usages: usages
|
||||
.into_iter()
|
||||
@@ -206,8 +316,17 @@ pub(crate) fn fixture_usages(
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PytestFixtureRename {
|
||||
pub edit: WorkspaceEdit,
|
||||
/// A parameter or fixture that already has the new name, which the rename would clash with
|
||||
/// (the edit is empty then).
|
||||
pub clash: Option<Location>,
|
||||
}
|
||||
|
||||
/// Rename of the fixture at `pos`: its definition (the `name=` string, else the function name),
|
||||
/// every place that gets it, and the uses of a renamed parameter in its function's body.
|
||||
/// every place that gets it, and the reads of a renamed parameter in its function's body.
|
||||
pub(crate) fn rename_fixture(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
@@ -216,13 +335,17 @@ pub(crate) fn rename_fixture(
|
||||
pos: Pos,
|
||||
new_name: &str,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> IdeResult<WorkspaceEdit> {
|
||||
let Some((target, usages)) = usages_of(project, syntax, path, text, pos, cancelled)? else {
|
||||
) -> IdeResult<PytestFixtureRename> {
|
||||
let own = Arc::new(syntax.pytest_module(&python(), text));
|
||||
let Some((target, usages)) = usages_of(project, syntax, path, own, pos, cancelled)? else {
|
||||
return Err(IdeError::invalid("No pytest fixture here"));
|
||||
};
|
||||
if !is_project_file(project, &target.path) {
|
||||
return Err(IdeError::invalid("The fixture is defined outside the project"));
|
||||
}
|
||||
if let Some(clash) = clash(project, syntax, &target, &usages, new_name) {
|
||||
return Ok(PytestFixtureRename { edit: WorkspaceEdit::default(), clash: Some(clash) });
|
||||
}
|
||||
let mut by_file: Vec<(PathBuf, Vec<TextEdit>)> = Vec::new();
|
||||
let mut edit = |file: &Path, range: Range| {
|
||||
let edits = match by_file.iter_mut().find(|(p, _)| p == file) {
|
||||
@@ -250,25 +373,53 @@ pub(crate) fn rename_fixture(
|
||||
FileEdit::Edit { path: IpcPath::from(p), edits, version: None }
|
||||
})
|
||||
.collect();
|
||||
Ok(WorkspaceEdit { files, preconditions: Vec::new() })
|
||||
Ok(PytestFixtureRename { edit: WorkspaceEdit { files, preconditions: Vec::new() }, clash: None })
|
||||
}
|
||||
|
||||
/// Where `new_name` is already taken: a name a function that gets the fixture already uses
|
||||
/// (a parameter, a name in its body), a fixture of that name a place that gets it sees (an
|
||||
/// override in a lower conftest, a class's own fixture), or another fixture of the definition's scope.
|
||||
fn clash(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
target: &Definition,
|
||||
usages: &[Usage],
|
||||
new_name: &str,
|
||||
) -> Option<Location> {
|
||||
for u in usages {
|
||||
if u.use_.taken.iter().any(|p| p == new_name) {
|
||||
return Some(Location { path: IpcPath::from(u.path.clone()), range: u.use_.range, uri: None });
|
||||
}
|
||||
}
|
||||
for u in usages {
|
||||
let modules: Vec<&PytestModule> = u.layers.iter().map(|(_, m)| m.as_ref()).collect();
|
||||
if let Some((l, f)) = resolve_fixture(&modules, new_name, u.use_.class.as_deref(), false) {
|
||||
return Some(Location {
|
||||
path: IpcPath::from(u.layers[l].0.clone()),
|
||||
range: modules[l].fixtures[f].selection,
|
||||
uri: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
let module = module_of(project, syntax, &target.path)?;
|
||||
let class = module.fixtures.iter().find(|f| f.selection == target.selection)?.class.clone();
|
||||
let other = module.fixtures.iter().find(|f| f.name == new_name && f.class == class)?;
|
||||
Some(Location { path: IpcPath::from(target.path.clone()), range: other.selection, uri: None })
|
||||
}
|
||||
|
||||
fn usages_of(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
path: &Path,
|
||||
text: &str,
|
||||
own: Arc<PytestModule>,
|
||||
pos: Pos,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> IdeResult<Option<(Definition, Vec<Usage>)>> {
|
||||
let own = Arc::new(syntax.pytest_module(&python(), text));
|
||||
if own.definition_at(pos).is_none() && own.use_at(pos).is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let scope = Scope::new(project);
|
||||
let Some(target) = target_at(project, syntax, &scope, path, &own, pos) else { return Ok(None) };
|
||||
let mut files = candidate_files(project, &target.path);
|
||||
if !files.iter().any(|f| f == path) && path.starts_with(&project.root) {
|
||||
let Some((target, _)) = target_at(project, syntax, &scope, path, &own, pos) else { return Ok(None) };
|
||||
let patterns = test_file_patterns(&project.root);
|
||||
let mut files = candidate_files(project, &target.path, &patterns);
|
||||
if !files.iter().any(|f| f == path) && is_project_file(project, path) {
|
||||
files.push(path.to_path_buf());
|
||||
}
|
||||
let mut usages = Vec::new();
|
||||
@@ -281,26 +432,58 @@ fn usages_of(
|
||||
if !module.uses.iter().any(|u| u.name == target.name) {
|
||||
continue;
|
||||
}
|
||||
let layers = scope.layers(project, syntax, &file, module.clone());
|
||||
let layers = Arc::new(scope.layers(project, syntax, &file, module.clone()));
|
||||
for u in module.uses.iter().filter(|u| u.name == target.name) {
|
||||
if definition_of(&layers, u).as_ref() == Some(&target) {
|
||||
usages.push(Usage { path: file.clone(), use_: u.clone() });
|
||||
usages.push(Usage { path: file.clone(), use_: u.clone(), layers: layers.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some((target, usages)))
|
||||
}
|
||||
|
||||
/// The files that may get a fixture defined in `definition`: that test module alone, the test
|
||||
/// modules and `conftest.py` files below a `conftest.py`, all of the project's for a plugin's.
|
||||
fn candidate_files(project: &Project, definition: &Path) -> Vec<PathBuf> {
|
||||
let in_project = is_project_file(project, definition);
|
||||
let is_conftest = definition.file_name().is_some_and(|n| n == "conftest.py");
|
||||
if in_project && !is_conftest {
|
||||
return vec![definition.to_path_buf()];
|
||||
/// Where the files that may get a fixture are.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum Searched<'a> {
|
||||
/// A test module's fixtures are its own.
|
||||
Itself,
|
||||
/// A `conftest.py`'s: the test files below its folder; any other module's (one that
|
||||
/// `pytest_plugins` loads or a conftest imports) and a plugin's: the whole project's.
|
||||
Below(&'a Path),
|
||||
}
|
||||
|
||||
fn searched<'a>(root: &'a Path, definition: &'a Path, in_project: bool, patterns: &[String]) -> Searched<'a> {
|
||||
let name = definition.file_name().and_then(|n| n.to_str()).unwrap_or_default();
|
||||
match () {
|
||||
_ if !in_project => Searched::Below(root),
|
||||
_ if name == "conftest.py" => Searched::Below(definition.parent().unwrap_or(root)),
|
||||
_ if is_test_module(name, patterns) => Searched::Itself,
|
||||
_ => Searched::Below(root),
|
||||
}
|
||||
}
|
||||
|
||||
/// The files that may get a fixture defined in `definition`, from the file index (or the disk,
|
||||
/// while the index is still being built).
|
||||
fn candidate_files(project: &Project, definition: &Path, patterns: &[String]) -> Vec<PathBuf> {
|
||||
let dir = match searched(&project.root, definition, is_project_file(project, definition), patterns) {
|
||||
Searched::Itself => return vec![definition.to_path_buf()],
|
||||
Searched::Below(dir) => dir,
|
||||
};
|
||||
let wanted = |rel: &Path| rel.file_name().and_then(|n| n.to_str()).is_some_and(|n| is_test_file(n, patterns));
|
||||
let mut files = project.index.files_matching(dir, wanted, MAX_FILES).unwrap_or_else(|| {
|
||||
ignore::WalkBuilder::new(dir)
|
||||
.build()
|
||||
.flatten()
|
||||
.map(|e| e.into_path())
|
||||
.filter(|p| p.strip_prefix(dir).is_ok_and(wanted))
|
||||
.take(MAX_FILES)
|
||||
.collect()
|
||||
});
|
||||
files.retain(|f| is_project_file(project, f));
|
||||
// A module `pytest_plugins` loads is searched too (it may use its own fixtures).
|
||||
if is_project_file(project, definition) && !files.iter().any(|f| f == definition) {
|
||||
files.push(definition.to_path_buf());
|
||||
}
|
||||
let dir = if in_project { definition.parent().unwrap_or(&project.root) } else { &project.root };
|
||||
let mut files = project.index.files_matching(dir, is_test_file, MAX_FILES).unwrap_or_default();
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
@@ -313,11 +496,127 @@ fn is_project_file(project: &Project, path: &Path) -> bool {
|
||||
path.starts_with(&project.root) && !path.components().any(|c| c.as_os_str() == "site-packages")
|
||||
}
|
||||
|
||||
/// `test_*.py`, `*_test.py` and `conftest.py`: the files pytest collects or loads.
|
||||
fn is_test_file(rel: &Path) -> bool {
|
||||
let Some(name) = rel.file_name().and_then(|n| n.to_str()) else { return false };
|
||||
let Some(stem) = name.strip_suffix(".py") else { return false };
|
||||
stem == "conftest" || stem.starts_with("test_") || stem.ends_with("_test")
|
||||
/// The test modules pytest collects (`python_files`, default `test_*.py` and `*_test.py`) and
|
||||
/// `conftest.py`, which it loads.
|
||||
fn is_test_file(name: &str, patterns: &[String]) -> bool {
|
||||
name == "conftest.py" || is_test_module(name, patterns)
|
||||
}
|
||||
|
||||
fn is_test_module(name: &str, patterns: &[String]) -> bool {
|
||||
patterns.iter().any(|p| glob_match(p, name))
|
||||
}
|
||||
|
||||
/// `python_files` from the project's pytest configuration (the first of `pytest.toml`,
|
||||
/// `.pytest.toml`, `pytest.ini`, `.pytest.ini`, `pyproject.toml`, `tox.ini`, `setup.cfg` that
|
||||
/// pytest takes), else pytest's default.
|
||||
fn test_file_patterns(root: &Path) -> Vec<String> {
|
||||
let read = |name: &str| std::fs::read_to_string(root.join(name)).ok();
|
||||
// `Some(value)` when the file is the configuration; `value` is None without `python_files`.
|
||||
let from_ini = |text: String, section: &str, always: bool| -> Option<Option<String>> {
|
||||
let mut found: Option<Option<String>> = always.then_some(None);
|
||||
let (mut inside, mut continued) = (false, false);
|
||||
for raw in text.lines() {
|
||||
let line = raw.trim();
|
||||
if continued && raw.starts_with([' ', '\t']) && !line.is_empty() {
|
||||
if !line.starts_with(['#', ';'])
|
||||
&& let Some(Some(value)) = &mut found
|
||||
{
|
||||
value.push(' ');
|
||||
value.push_str(line);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
continued = false;
|
||||
if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
|
||||
inside = name == section;
|
||||
if inside && found.is_none() {
|
||||
found = Some(None);
|
||||
}
|
||||
} else if inside
|
||||
&& let Some((key, value)) = line.split_once('=')
|
||||
&& key.trim() == "python_files"
|
||||
{
|
||||
found = Some(Some(value.trim().to_owned()));
|
||||
continued = true;
|
||||
}
|
||||
}
|
||||
found
|
||||
};
|
||||
let from_toml = |text: String, tables: &[&[&str]], always: bool| -> Option<Option<String>> {
|
||||
let table = text.parse::<toml::Table>().ok()?;
|
||||
let options = tables.iter().find_map(|path| {
|
||||
let mut at = table.get(path[0])?;
|
||||
for key in &path[1..] {
|
||||
at = at.get(*key)?;
|
||||
}
|
||||
Some(at)
|
||||
});
|
||||
let Some(options) = options else { return always.then_some(None) };
|
||||
Some(match options.get("python_files") {
|
||||
Some(toml::Value::String(s)) => Some(s.clone()),
|
||||
Some(toml::Value::Array(a)) => Some(a.iter().filter_map(|v| v.as_str()).collect::<Vec<_>>().join(" ")),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
// The first file pytest takes, in its order; a pytest.toml or pytest.ini counts even when empty.
|
||||
let pytest_toml = |t: String| from_toml(t, &[&["pytest"]], true);
|
||||
let pytest_ini = |t: String| from_ini(t, "pytest", true);
|
||||
let configured = read("pytest.toml")
|
||||
.and_then(pytest_toml)
|
||||
.or_else(|| read(".pytest.toml").and_then(pytest_toml))
|
||||
.or_else(|| read("pytest.ini").and_then(pytest_ini))
|
||||
.or_else(|| read(".pytest.ini").and_then(pytest_ini))
|
||||
.or_else(|| {
|
||||
read("pyproject.toml")
|
||||
.and_then(|t| from_toml(t, &[&["tool", "pytest", "ini_options"], &["tool", "pytest"]], false))
|
||||
})
|
||||
.or_else(|| read("tox.ini").and_then(|t| from_ini(t, "pytest", false)))
|
||||
.or_else(|| read("setup.cfg").and_then(|t| from_ini(t, "tool:pytest", false)))
|
||||
.flatten();
|
||||
match configured {
|
||||
Some(value) if !value.trim().is_empty() => value.split_whitespace().map(str::to_owned).collect(),
|
||||
_ => vec!["test_*.py".to_owned(), "*_test.py".to_owned()],
|
||||
}
|
||||
}
|
||||
|
||||
/// `fnmatch` with `*`, `?` and `[…]` / `[!…]` (ranges too), as pytest matches `python_files`
|
||||
/// against a file name.
|
||||
fn glob_match(pattern: &str, name: &str) -> bool {
|
||||
/// The class at the start of `p` (after `[`): whether it matches `c`, and its length with `]`.
|
||||
fn class(p: &[char], c: char) -> Option<(bool, usize)> {
|
||||
let negated = p.first() == Some(&'!');
|
||||
let mut i = usize::from(negated);
|
||||
let mut hit = false;
|
||||
// A `]` right after `[` or `[!` is a member.
|
||||
let start = i;
|
||||
while i < p.len() && (p[i] != ']' || i == start) {
|
||||
if i + 2 < p.len() && p[i + 1] == '-' && p[i + 2] != ']' {
|
||||
hit |= p[i] <= c && c <= p[i + 2];
|
||||
i += 3;
|
||||
} else {
|
||||
hit |= p[i] == c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
(i < p.len()).then_some((hit != negated, i + 1))
|
||||
}
|
||||
fn go(p: &[char], n: &[char]) -> bool {
|
||||
match p.split_first() {
|
||||
None => n.is_empty(),
|
||||
Some(('*', rest)) => (0..=n.len()).any(|i| go(rest, &n[i..])),
|
||||
Some(('?', rest)) => !n.is_empty() && go(rest, &n[1..]),
|
||||
Some(('[', rest))
|
||||
if let Some(&c) = n.first()
|
||||
&& let Some((hit, len)) = class(rest, c) =>
|
||||
{
|
||||
hit && go(&rest[len..], &n[1..])
|
||||
}
|
||||
Some((c, rest)) => n.first() == Some(c) && go(rest, &n[1..]),
|
||||
}
|
||||
}
|
||||
let p: Vec<char> = pattern.chars().collect();
|
||||
let n: Vec<char> = name.chars().collect();
|
||||
go(&p, &n)
|
||||
}
|
||||
|
||||
/// The `site-packages` of the project's interpreter: its virtualenv's, else its install prefix's.
|
||||
@@ -432,15 +731,71 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_files_are_the_ones_pytest_loads() {
|
||||
for (rel, expected) in [
|
||||
("tests/test_a.py", true),
|
||||
let default = vec!["test_*.py".to_owned(), "*_test.py".to_owned()];
|
||||
for (name, expected) in [
|
||||
("test_a.py", true),
|
||||
("a_test.py", true),
|
||||
("pkg/conftest.py", true),
|
||||
("pkg/helpers.py", false),
|
||||
("test_data.json", false),
|
||||
("conftest.py", true),
|
||||
("helpers.py", false),
|
||||
("test_a.json", false),
|
||||
] {
|
||||
assert_eq!(is_test_file(Path::new(rel)), expected, "{rel}");
|
||||
assert_eq!(is_test_file(name, &default), expected, "{name}");
|
||||
}
|
||||
let custom = vec!["check_*.py".to_owned(), "tests.py".to_owned()];
|
||||
assert!(is_test_file("check_cli.py", &custom) && is_test_file("tests.py", &custom));
|
||||
assert!(!is_test_file("test_a.py", &custom));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_python_files_from_the_first_pytest_configuration() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert_eq!(test_file_patterns(dir.path()), ["test_*.py", "*_test.py"]);
|
||||
std::fs::write(dir.path().join("setup.cfg"), "[tool:pytest]\npython_files = check_*.py\n").unwrap();
|
||||
assert_eq!(test_file_patterns(dir.path()), ["check_*.py"]);
|
||||
std::fs::write(
|
||||
dir.path().join("pyproject.toml"),
|
||||
"[tool.pytest.ini_options]\npython_files = [\"tests.py\", \"t_*.py\"]\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(test_file_patterns(dir.path()), ["tests.py", "t_*.py"]);
|
||||
// A pytest.ini section without python_files means pytest's default, even with the others.
|
||||
std::fs::write(dir.path().join("pytest.ini"), "[pytest]\naddopts = -q\n").unwrap();
|
||||
assert_eq!(test_file_patterns(dir.path()), ["test_*.py", "*_test.py"]);
|
||||
// pytest.toml comes first, its options in `[pytest]`.
|
||||
std::fs::write(dir.path().join("pytest.toml"), "[pytest]\npython_files = [\"spec_*.py\"]\n").unwrap();
|
||||
assert_eq!(test_file_patterns(dir.path()), ["spec_*.py"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_python_files_written_over_several_lines_and_in_any_pytest_table() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(
|
||||
dir.path().join("setup.cfg"),
|
||||
"[tool:pytest]\npython_files =\n check_*.py\n t_*.py\nx = 1\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(test_file_patterns(dir.path()), ["check_*.py", "t_*.py"]);
|
||||
// An empty pytest.ini still is the configuration: pytest's default.
|
||||
std::fs::write(dir.path().join("pytest.ini"), "").unwrap();
|
||||
assert_eq!(test_file_patterns(dir.path()), ["test_*.py", "*_test.py"]);
|
||||
std::fs::remove_file(dir.path().join("pytest.ini")).unwrap();
|
||||
// pytest 9's `[tool.pytest]` with native lists.
|
||||
std::fs::write(dir.path().join("pyproject.toml"), "[tool.pytest]\npython_files = [\"it_*.py\"]\n").unwrap();
|
||||
assert_eq!(test_file_patterns(dir.path()), ["it_*.py"]);
|
||||
assert!(glob_match("test_[ab].py", "test_a.py") && !glob_match("test_[!ab].py", "test_a.py"));
|
||||
assert!(glob_match("test_[!ab].py", "test_c.py") && !glob_match("test_[ab].py", "test_c.py"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fixture_is_searched_where_pytest_lets_tests_see_it() {
|
||||
let root = Path::new("/p");
|
||||
let default = vec!["test_*.py".to_owned(), "*_test.py".to_owned()];
|
||||
let at = |path: &'static str, in_project: bool| searched(root, Path::new(path), in_project, &default);
|
||||
assert_eq!(at("/p/tests/test_a.py", true), Searched::Itself);
|
||||
assert_eq!(at("/p/tests/conftest.py", true), Searched::Below(Path::new("/p/tests")));
|
||||
// A module that `pytest_plugins` loads, or that a conftest imports.
|
||||
assert_eq!(at("/p/tests/fixtures.py", true), Searched::Below(root));
|
||||
assert_eq!(at("/p/.venv/lib/python3.12/site-packages/_pytest/tmpdir.py", false), Searched::Below(root));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -30,13 +30,7 @@ pub(super) fn with_user_paths(
|
||||
command: Option<&str>,
|
||||
near: Option<&Path>,
|
||||
) -> Vec<PathBuf> {
|
||||
let named = command
|
||||
.filter(|c| ide_sdk::apply::is_python_command(c))
|
||||
.map(PathBuf::from)
|
||||
.filter(|p| p.is_absolute() && p.is_file())
|
||||
.map(|p| ide_core::project_roots::resolve(&project.root, &p));
|
||||
let python = named.or_else(|| super::sdk::effective_python(config_dir, project, near));
|
||||
if let Some(python) = python {
|
||||
if let Some(python) = launch_python(config_dir, project, command, near) {
|
||||
for path in ide_sdk::apply::interpreter_user_paths(&python, &project.settings.effective()) {
|
||||
if !paths.contains(&path) {
|
||||
paths.push(path);
|
||||
@@ -46,18 +40,40 @@ pub(super) fn with_user_paths(
|
||||
paths
|
||||
}
|
||||
|
||||
/// The interpreter a launch uses: `command` when it names a Python executable, else the
|
||||
/// interpreter of the project or workspace member at `near`.
|
||||
fn launch_python(config_dir: &Path, project: &Project, command: Option<&str>, near: Option<&Path>) -> Option<PathBuf> {
|
||||
let named = command
|
||||
.filter(|c| ide_sdk::apply::is_python_command(c))
|
||||
.map(PathBuf::from)
|
||||
.filter(|p| p.is_absolute() && p.is_file())
|
||||
.map(|p| ide_core::project_roots::resolve(&project.root, &p));
|
||||
named.or_else(|| super::sdk::effective_python(config_dir, project, near))
|
||||
}
|
||||
|
||||
/// The conda environment of the interpreter a launch uses ([`launch_python`]), to activate.
|
||||
pub(super) fn conda_prefix(
|
||||
config_dir: &Path,
|
||||
project: &Project,
|
||||
command: Option<&str>,
|
||||
near: Option<&Path>,
|
||||
) -> Option<PathBuf> {
|
||||
ide_sdk::apply::conda_env_prefix(&launch_python(config_dir, project, command, near)?)
|
||||
}
|
||||
|
||||
/// The interpreter a debugpy launch names (`"python": "<executable>"`), if it names one.
|
||||
pub(super) fn debug_python(config: &LaunchConfig) -> Option<String> {
|
||||
let extra: serde_json::Value = serde_json::from_str(config.extra_json.as_deref()?).ok()?;
|
||||
extra.get("python")?.as_str().map(str::to_owned)
|
||||
}
|
||||
|
||||
/// Adds the project's import paths, and the Plots tool window's backend (`plots`), to a debugpy
|
||||
/// launch's environment.
|
||||
/// Adds the project's import paths, and the Plots tool window's backend (`plots`, with the folder
|
||||
/// the debuggee starts in), to a debugpy launch's environment.
|
||||
pub(super) fn prepare_debug(
|
||||
config: &mut LaunchConfig,
|
||||
paths: &[PathBuf],
|
||||
plots: Option<&ide_run::plots::Plots>,
|
||||
plots: Option<(&ide_run::plots::Plots, &Path)>,
|
||||
conda: Option<&Path>,
|
||||
) -> IdeResult<()> {
|
||||
// Adapter-specific env takes precedence over the common launch fields in DAP.
|
||||
let mut extra: Option<serde_json::Value> = config.extra_json.as_deref().and_then(|s| serde_json::from_str(s).ok());
|
||||
@@ -76,18 +92,27 @@ pub(super) fn prepare_debug(
|
||||
let mut vars: BTreeMap<String, String> =
|
||||
object.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_owned()))).collect();
|
||||
let inherit = !vars.contains_key("PYTHONPATH");
|
||||
let user_set: std::collections::HashSet<String> = vars.keys().cloned().collect();
|
||||
ide_run::python_path::extend(&mut vars, paths, inherit)?;
|
||||
if let Some(plots) = plots {
|
||||
ide_run::plots::add(&mut vars, plots, true)?;
|
||||
if let Some(prefix) = conda {
|
||||
// debugpy hands this env to the debuggee: PATH must keep the inherited entries.
|
||||
ide_run::python_path::activate_conda(&mut vars, prefix, true, |k| user_set.contains(k))?;
|
||||
}
|
||||
if let Some((plots, dir)) = plots {
|
||||
ide_run::plots::add(&mut vars, plots, Some(dir))?;
|
||||
}
|
||||
for (key, value) in vars {
|
||||
object.insert(key, serde_json::json!(value));
|
||||
}
|
||||
config.extra_json = extra.map(|e| e.to_string());
|
||||
} else {
|
||||
let user_set: std::collections::HashSet<String> = config.env.keys().cloned().collect();
|
||||
ide_run::python_path::extend(&mut config.env, paths, true)?;
|
||||
if let Some(plots) = plots {
|
||||
ide_run::plots::add(&mut config.env, plots, true)?;
|
||||
if let Some(prefix) = conda {
|
||||
ide_run::python_path::activate_conda(&mut config.env, prefix, true, |k| user_set.contains(k))?;
|
||||
}
|
||||
if let Some((plots, dir)) = plots {
|
||||
ide_run::plots::add(&mut config.env, plots, Some(dir))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -97,6 +122,36 @@ pub(super) fn prepare_debug(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn debug_activates_the_interpreters_conda_environment() {
|
||||
let root = std::env::temp_dir().join("project");
|
||||
let prefix = std::env::temp_dir().join("miniforge3").join("envs").join("ds");
|
||||
let mut config = LaunchConfig {
|
||||
name: "Python".into(),
|
||||
adapter: "debugpy".into(),
|
||||
request: "launch".into(),
|
||||
program: None,
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: BTreeMap::new(),
|
||||
// A PYTHONPATH of its own must not cut PATH down to the environment's folders.
|
||||
extra_json: Some(
|
||||
serde_json::json!({"env": {"CONDA_DEFAULT_ENV": "mine", "PYTHONPATH": "src"}}).to_string(),
|
||||
),
|
||||
};
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None, Some(&prefix)).unwrap();
|
||||
let value: serde_json::Value = serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap();
|
||||
let env = &value["env"];
|
||||
assert_eq!(env["CONDA_PREFIX"], prefix.to_string_lossy().as_ref());
|
||||
assert_eq!(env["CONDA_DEFAULT_ENV"], "mine");
|
||||
let path = env.as_object().unwrap().iter().find(|(k, _)| k.eq_ignore_ascii_case("PATH")).unwrap().1;
|
||||
let path: Vec<_> = std::env::split_paths(path.as_str().unwrap()).collect();
|
||||
assert!(path[0].starts_with(&prefix), "{path:?}");
|
||||
let inherited = ide_run::system_env().into_iter().find(|(k, _)| k.eq_ignore_ascii_case("PATH")).unwrap().1;
|
||||
let system = std::env::split_paths(&inherited).next().unwrap();
|
||||
assert!(path.contains(&system), "{path:?} lacks {system:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_preserves_remote_paths_and_handles_null_env() {
|
||||
let root = std::env::temp_dir().join("project");
|
||||
@@ -111,11 +166,11 @@ mod tests {
|
||||
extra_json: Some(serde_json::json!({"env": null, "debugServer": "remote:5678"}).to_string()),
|
||||
};
|
||||
let before = config.extra_json.clone();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None).unwrap();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None, None).unwrap();
|
||||
assert_eq!(config.extra_json, before);
|
||||
assert!(config.env.is_empty());
|
||||
config.extra_json = Some(serde_json::json!({"env": null}).to_string());
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None).unwrap();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None, None).unwrap();
|
||||
let value: serde_json::Value = serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap();
|
||||
let paths = std::env::split_paths(value["env"]["PYTHONPATH"].as_str().unwrap()).collect::<Vec<_>>();
|
||||
assert_eq!(paths[0], root);
|
||||
@@ -137,7 +192,7 @@ mod tests {
|
||||
env: vars.clone(),
|
||||
extra_json: extra.then(|| serde_json::json!({"env": vars}).to_string()),
|
||||
};
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None).unwrap();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None, None).unwrap();
|
||||
let vars: BTreeMap<String, String> = if extra {
|
||||
let value: serde_json::Value = serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap();
|
||||
serde_json::from_value(value["env"].clone()).unwrap()
|
||||
@@ -147,4 +202,50 @@ mod tests {
|
||||
assert_eq!(std::env::split_paths(&vars["PYTHONPATH"]).collect::<Vec<_>>(), [root, vendor]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_adds_the_plots_backend_to_the_launch_env_unless_it_sets_one() {
|
||||
let root = std::env::temp_dir().join("project");
|
||||
if ide_core::process::host_var_os_in(&root, "MPLBACKEND").is_some() {
|
||||
eprintln!("skipped: this machine sets MPLBACKEND");
|
||||
return;
|
||||
}
|
||||
let plots = ide_run::plots::Plots { backend: root.join("backend"), dir: root.join("plots") };
|
||||
let launch = |extra: serde_json::Value, env: BTreeMap<String, String>| LaunchConfig {
|
||||
name: "Python".into(),
|
||||
adapter: "debugpy".into(),
|
||||
request: "launch".into(),
|
||||
program: Some("main.py".into()),
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env,
|
||||
extra_json: Some(extra.to_string()),
|
||||
};
|
||||
let env_of = |config: &LaunchConfig| -> serde_json::Value {
|
||||
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()["env"].clone()
|
||||
};
|
||||
|
||||
// The launch's own variables stay as they are, other values included.
|
||||
let mut config = launch(serde_json::json!({"env": {"DEBUG": "1", "LEVEL": 3}}), BTreeMap::new());
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), Some((&plots, &root)), None).unwrap();
|
||||
let env = env_of(&config);
|
||||
assert_eq!((env["DEBUG"].as_str(), env["LEVEL"].as_i64()), (Some("1"), Some(3)));
|
||||
assert_eq!(env["MPLBACKEND"], "module://openidea_matplotlib_backend");
|
||||
assert_eq!(env["OPENIDEA_PLOTS_DIR"], plots.dir.to_string_lossy().as_ref());
|
||||
let path: Vec<_> = std::env::split_paths(env["PYTHONPATH"].as_str().unwrap()).collect();
|
||||
// A PYTHONPATH this machine sets follows.
|
||||
assert_eq!(path[..2], [plots.backend.clone(), root.clone()]);
|
||||
|
||||
// A backend the launch names, in either environment field, is kept.
|
||||
let mut config = launch(serde_json::json!({"env": {"MPLBACKEND": "Agg"}}), BTreeMap::new());
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), Some((&plots, &root)), None).unwrap();
|
||||
let env = env_of(&config);
|
||||
assert_eq!(env["MPLBACKEND"], "Agg");
|
||||
assert!(env.get("OPENIDEA_PLOTS_DIR").is_none());
|
||||
let own = BTreeMap::from([("MPLBACKEND".into(), "TkAgg".into())]);
|
||||
let mut config = launch(serde_json::json!({}), own);
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), Some((&plots, &root)), None).unwrap();
|
||||
assert_eq!(config.env["MPLBACKEND"], "TkAgg");
|
||||
assert!(!config.env.contains_key("OPENIDEA_PLOTS_DIR"));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Spring Web mappings, source side: the project's Java and Kotlin files that could
|
||||
//! declare a route, with their text. The UI owns the annotation parser and the index
|
||||
//! it feeds, so this side stays a cheap scan.
|
||||
//! Web framework routes, source side: the project's files that could declare a route
|
||||
//! (Spring's Java and Kotlin, Flask's and FastAPI's Python), with their text. The UI owns
|
||||
//! the parsers and the index they feed, so this side stays a cheap scan.
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::IdeResult;
|
||||
@@ -24,26 +24,42 @@ pub struct RouteSource {
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// The files Spring mappings can live in: Java and Kotlin sources.
|
||||
fn declares_mappings(path: &Path) -> bool {
|
||||
matches!(path.extension().and_then(|e| e.to_str()), Some("java" | "kt" | "kts"))
|
||||
/// Which files a framework's routes can live in, and words one of which such a file names.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct RouteFiles {
|
||||
extensions: &'static [&'static str],
|
||||
words: &'static [&'static str],
|
||||
}
|
||||
|
||||
/// Files under `root` whose text names a mapping: `ignore` rules and `excludes`
|
||||
/// Spring mappings: Java and Kotlin sources that name a mapping annotation.
|
||||
pub(crate) const SPRING: RouteFiles = RouteFiles { extensions: &["java", "kt", "kts"], words: &["Mapping"] };
|
||||
/// Flask and FastAPI routes: Python sources that import either (blueprints, routers and the
|
||||
/// modules registering them all do).
|
||||
pub(crate) const PYTHON: RouteFiles = RouteFiles { extensions: &["py"], words: &["flask", "fastapi"] };
|
||||
|
||||
impl RouteFiles {
|
||||
fn declares_routes(&self, path: &Path) -> bool {
|
||||
path.extension().and_then(|e| e.to_str()).is_some_and(|e| self.extensions.contains(&e))
|
||||
// Installed packages (a virtualenv the ignore rules don't cover) declare their own examples.
|
||||
&& !path.components().any(|c| c.as_os_str() == "site-packages")
|
||||
}
|
||||
}
|
||||
|
||||
/// Files under `root` whose text names a route: `ignore` rules and `excludes`
|
||||
/// decide what counts, and the UI ranks the matches itself.
|
||||
pub(crate) fn sources_in(root: &Path, excludes: &[String]) -> Vec<RouteSource> {
|
||||
pub(crate) fn sources_in(root: &Path, excludes: &[String], kind: RouteFiles) -> Vec<RouteSource> {
|
||||
let found: Mutex<Vec<RouteSource>> = Mutex::new(Vec::new());
|
||||
let bytes = AtomicUsize::new(0);
|
||||
ide_vfs::walk_files(root, excludes, |path| {
|
||||
if !declares_mappings(path) || bytes.load(Ordering::Relaxed) >= MAX_BYTES {
|
||||
if !kind.declares_routes(path) || bytes.load(Ordering::Relaxed) >= MAX_BYTES {
|
||||
return;
|
||||
}
|
||||
if std::fs::metadata(path).map_or(true, |m| m.len() > MAX_FILE_BYTES) {
|
||||
return;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(path) else { return };
|
||||
// Only a file that names a mapping annotation is worth parsing.
|
||||
if !text.contains("Mapping") {
|
||||
// Only a file that names a mapping annotation (or imports the framework) is worth parsing.
|
||||
if !kind.words.iter().any(|w| text.contains(w)) {
|
||||
return;
|
||||
}
|
||||
let Ok(mut found) = found.lock() else { return };
|
||||
@@ -70,17 +86,31 @@ fn scan_roots(root: &Path, content_roots: Vec<PathBuf>) -> Vec<PathBuf> {
|
||||
/// Every mapping source of the project, for the request-path index. Walks the whole tree,
|
||||
/// so it runs on the blocking pool.
|
||||
pub async fn spring_route_sources(host: &Host, window: &str) -> IdeResult<Vec<RouteSource>> {
|
||||
route_sources(host, window, SPRING, "spring").await
|
||||
}
|
||||
|
||||
/// Every Flask / FastAPI source of the project, for the request-path index.
|
||||
pub async fn python_route_sources(host: &Host, window: &str) -> IdeResult<Vec<RouteSource>> {
|
||||
route_sources(host, window, PYTHON, "python").await
|
||||
}
|
||||
|
||||
async fn route_sources(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
kind: RouteFiles,
|
||||
label: &'static str,
|
||||
) -> IdeResult<Vec<RouteSource>> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || {
|
||||
let mut out = Vec::new();
|
||||
for root in scan_roots(&project.root, project.content_roots()) {
|
||||
out.extend(sources_in(&root, &project.search_excludes_in(&root)));
|
||||
out.extend(sources_in(&root, &project.search_excludes_in(&root), kind));
|
||||
}
|
||||
out.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
out.dedup_by(|a, b| a.path == b.path);
|
||||
match out.len() {
|
||||
0 => tracing::warn!("spring routes: no mapping source under {:?}", project.root),
|
||||
n => tracing::info!("spring routes: {n} mapping sources under {:?}", project.root),
|
||||
0 => tracing::debug!("{label} routes: no route source under {:?}", project.root),
|
||||
n => tracing::info!("{label} routes: {n} route sources under {:?}", project.root),
|
||||
}
|
||||
Ok(out)
|
||||
})
|
||||
@@ -106,10 +136,28 @@ mod tests {
|
||||
for (name, expected) in
|
||||
[("A.java", true), ("B.kt", true), ("C.kts", true), ("D.txt", false), ("pom.xml", false), ("noext", false)]
|
||||
{
|
||||
assert_eq!(declares_mappings(Path::new(name)), expected, "{name}");
|
||||
assert_eq!(SPRING.declares_routes(Path::new(name)), expected, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_sources_that_import_flask_or_fastapi_are_read_outside_installed_packages() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let write = |rel: &str, text: &str| {
|
||||
let path = tmp.path().join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
};
|
||||
write("app.py", "from flask import Flask\n");
|
||||
write("api/routers/items.py", "from fastapi import APIRouter\n");
|
||||
write("util.py", "import os\n");
|
||||
write("venv/lib/python3.12/site-packages/flask/app.py", "import flask\n");
|
||||
let files = sources_in(tmp.path(), &[], PYTHON);
|
||||
assert_eq!(files.len(), 2, "{:?}", files.iter().map(|f| &f.path).collect::<Vec<_>>());
|
||||
assert!(files[0].path.ends_with("api/routers/items.py"), "{:?}", files[0].path);
|
||||
assert!(files[1].path.ends_with("app.py"), "{:?}", files[1].path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_that_name_no_mapping_are_left_out() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -117,7 +165,7 @@ mod tests {
|
||||
std::fs::write(tmp.path().join("src/Ctl.java"), "class Ctl { @GetMapping(\"/a\") void a() {} }").unwrap();
|
||||
std::fs::write(tmp.path().join("src/Plain.java"), "class Plain { void a() {} }").unwrap();
|
||||
std::fs::write(tmp.path().join("src/Notes.txt"), "@GetMapping(\"/a\")").unwrap();
|
||||
let files = sources_in(tmp.path(), &[]);
|
||||
let files = sources_in(tmp.path(), &[], SPRING);
|
||||
assert_eq!(files.len(), 1, "{:?}", files.iter().map(|f| &f.path).collect::<Vec<_>>());
|
||||
assert!(files[0].path.ends_with("src/Ctl.java"), "{:?}", files[0].path);
|
||||
assert!(files[0].text.contains("@GetMapping"));
|
||||
@@ -130,7 +178,7 @@ mod tests {
|
||||
std::fs::create_dir_all(tmp.path().join("build")).unwrap();
|
||||
std::fs::write(tmp.path().join("module/src/A.java"), "@RequestMapping(\"/a\")").unwrap();
|
||||
std::fs::write(tmp.path().join("build/B.java"), "@RequestMapping(\"/b\")").unwrap();
|
||||
let files = sources_in(tmp.path(), &["build/**".to_owned()]);
|
||||
let files = sources_in(tmp.path(), &["build/**".to_owned()], SPRING);
|
||||
assert_eq!(files.len(), 1, "{:?}", files.iter().map(|f| &f.path).collect::<Vec<_>>());
|
||||
assert!(files[0].path.ends_with("module/src/A.java"), "{:?}", files[0].path);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
//! The reStructuredText preview: docutils, in the project's Python interpreter, turns the
|
||||
//! edited text into HTML, with everything that reads past the document turned off.
|
||||
|
||||
use crate::Host;
|
||||
use crate::ops::blocking;
|
||||
use ide_command::command;
|
||||
use ide_core::cli_process::{CliTool, Decoding, Input};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
const RENDER: &str = include_str!("rst_render.py");
|
||||
/// What the script prints when docutils can't be imported.
|
||||
const NO_DOCUTILS: &str = "no-docutils";
|
||||
const TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
/// `text`, the reStructuredText file `path` as edited, as the HTML body of its preview, with
|
||||
/// docutils' problems inline. Runs the project's Python interpreter, so needs a trusted project.
|
||||
/// Cancelling `request` (the text changed again) stops the interpreter.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn rst_preview(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
path: PathBuf,
|
||||
text: String,
|
||||
) -> IdeResult<String> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let config_dir = host.config_dir.clone();
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = blocking(move || {
|
||||
let python = super::sdk::effective_python(&config_dir, &project, path.parent()).ok_or_else(|| {
|
||||
IdeError::unavailable("Choose a Python interpreter for the project to preview reStructuredText.")
|
||||
})?;
|
||||
render(&python, &path, &text, Some(&cancel))
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
fn render(python: &Path, path: &Path, text: &str, cancel: Option<&CancellationToken>) -> IdeResult<String> {
|
||||
// `-c` puts the working directory first on `sys.path`: an empty one shadows nothing.
|
||||
let dir = tempfile::Builder::new()
|
||||
.prefix("openidea-rst-")
|
||||
.tempdir()
|
||||
.map_err(|e| IdeError::internal(format!("cannot create a folder to run docutils in: {e}")))?;
|
||||
let mut cmd = Command::new(python);
|
||||
// `-E`: `PYTHONPATH` and the like don't apply. The file name only appears in docutils'
|
||||
// messages: nothing is read relative to it.
|
||||
cmd.arg("-E").arg("-c").arg(RENDER).arg(path.file_name().unwrap_or(path.as_os_str()));
|
||||
cmd.current_dir(dir.path());
|
||||
let out = CliTool::new("Python", Decoding::Utf8Lossy).run_with_input(
|
||||
cmd,
|
||||
Some(Input::Threaded(text)),
|
||||
TIMEOUT,
|
||||
cancel,
|
||||
)?;
|
||||
if out.success {
|
||||
return Ok(out.stdout);
|
||||
}
|
||||
if out.stdout == NO_DOCUTILS {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"docutils is not installed for {}. Install it to preview reStructuredText.",
|
||||
python.display()
|
||||
)));
|
||||
}
|
||||
let last = out.stderr.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("docutils failed");
|
||||
Err(IdeError::internal(last.trim().to_owned()))
|
||||
}
|
||||
|
||||
ide_command::domain!(rst: rst_preview);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn python() -> Option<PathBuf> {
|
||||
["python3", "python"].into_iter().map(PathBuf::from).find(|p| Command::new(p).arg("--version").output().is_ok())
|
||||
}
|
||||
|
||||
fn has_docutils(python: &Path) -> bool {
|
||||
Command::new(python).args(["-c", "import docutils"]).status().is_ok_and(|s| s.success())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_without_reading_past_the_document() {
|
||||
let Some(python) = python().filter(|p| has_docutils(p)) else {
|
||||
eprintln!("skipped: no Python with docutils");
|
||||
return;
|
||||
};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let secret = dir.path().join("secret.txt");
|
||||
std::fs::write(&secret, "TOP-SECRET").unwrap();
|
||||
let text = format!(
|
||||
"Title\n=====\n\n*hi* ünï\n\n.. include:: {0}\n\n.. raw:: html\n\n <script>x()</script>\n\n\
|
||||
.. csv-table::\n :file: {0}\n\n.. image:: pic.png\n :scale: 50\n",
|
||||
secret.display()
|
||||
);
|
||||
let html = render(&python, &dir.path().join("doc.rst"), &text, None).unwrap();
|
||||
assert!(html.contains("<em>hi</em> ünï"), "{html}");
|
||||
assert!(!html.contains("TOP-SECRET"), "{html}");
|
||||
assert!(!html.contains("<script>"), "{html}");
|
||||
assert!(html.contains(""include" directive disabled"), "{html}");
|
||||
assert!(html.contains(""raw" directive disabled"), "{html}");
|
||||
assert!(html.contains(r#"src="pic.png""#), "{html}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn says_when_docutils_is_missing() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let Some(python) = python() else {
|
||||
eprintln!("skipped: no Python");
|
||||
return;
|
||||
};
|
||||
// A stand-in interpreter whose `import docutils` fails, wherever docutils is installed.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let fake = dir.path().join("python");
|
||||
let blocker = dir.path().join("block");
|
||||
std::fs::create_dir(&blocker).unwrap();
|
||||
std::fs::write(blocker.join("docutils.py"), "raise ImportError('blocked')\n").unwrap();
|
||||
// Drops `-E`, which would ignore the `PYTHONPATH` that blocks docutils.
|
||||
let script = format!(
|
||||
"#!/bin/sh\n[ \"$1\" = -E ] && shift\nPYTHONPATH='{}' exec '{}' \"$@\"\n",
|
||||
blocker.display(),
|
||||
python.display()
|
||||
);
|
||||
std::fs::write(&fake, script).unwrap();
|
||||
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let error = render(&fake, Path::new("doc.rst"), "x", None).unwrap_err();
|
||||
assert!(error.to_string().contains("docutils is not installed"), "{error}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn cancelling_stops_the_interpreter() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let slow = dir.path().join("python");
|
||||
std::fs::write(&slow, "#!/bin/sh\nsleep 30\n").unwrap();
|
||||
std::fs::set_permissions(&slow, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let later = cancel.clone();
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
later.cancel();
|
||||
});
|
||||
let started = std::time::Instant::now();
|
||||
let error = render(&slow, Path::new("doc.rst"), "x", Some(&cancel)).unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert!(started.elapsed() < Duration::from_secs(5));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
# Renders the reStructuredText on stdin (argv[1] names the file in messages) to the HTML body of its
|
||||
# preview on stdout. Nothing is read past the document: no included files, raw HTML, URLs
|
||||
# or docutils.conf, and no image is opened to size it. Problems show inline.
|
||||
import sys
|
||||
|
||||
try:
|
||||
import docutils.core
|
||||
except ImportError:
|
||||
sys.stdout.write("no-docutils")
|
||||
sys.exit(3)
|
||||
|
||||
source = sys.stdin.buffer.read().decode("utf-8", "replace")
|
||||
parts = docutils.core.publish_parts(
|
||||
source,
|
||||
source_path=sys.argv[1],
|
||||
writer_name="html5",
|
||||
settings_overrides={
|
||||
"_disable_config": True,
|
||||
"file_insertion_enabled": False,
|
||||
"raw_enabled": False,
|
||||
"image_loading": "link",
|
||||
"embed_stylesheet": False,
|
||||
"math_output": "MathML",
|
||||
"syntax_highlight": "none",
|
||||
"report_level": 2,
|
||||
"halt_level": 5,
|
||||
"warning_stream": False,
|
||||
"traceback": True,
|
||||
},
|
||||
)
|
||||
sys.stdout.buffer.write(parts["html_body"].encode("utf-8"))
|
||||
@@ -4,7 +4,7 @@ use ide_command::command;
|
||||
use ide_core::remote_settings::RunTargetKind;
|
||||
use ide_core::{IdeError, IdeResult, RunId};
|
||||
use ide_run::{OutputChunk, RunAttach, RunConfig, RunInfo, StartOptions};
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -439,6 +439,8 @@ async fn start_inner(
|
||||
python_paths: Vec::new(),
|
||||
ruby_reporter: None,
|
||||
plots: None,
|
||||
capture_junit_reports: false,
|
||||
conda_prefix: None,
|
||||
},
|
||||
sink,
|
||||
Box::new(move |c| on_output(c)),
|
||||
@@ -448,6 +450,10 @@ async fn start_inner(
|
||||
if target.kind != RunTargetKind::Ssh {
|
||||
// A local run of the docker CLI: the command is resolved in the container, and
|
||||
// this machine's toolchains and `PYTHONPATH` don't apply.
|
||||
let mut config = config;
|
||||
if ide_run::is_python_kind(&config.kind) {
|
||||
container_python_path(&mut config.env, &super::python::paths(&project), &project.root);
|
||||
}
|
||||
let config = container::prepare(host, &project.root, target, config).await?;
|
||||
let encoding = settings.console.encoding;
|
||||
let options = StartOptions {
|
||||
@@ -456,6 +462,8 @@ async fn start_inner(
|
||||
// A folder on this machine: not in the container.
|
||||
ruby_reporter: None,
|
||||
plots: None,
|
||||
capture_junit_reports: false,
|
||||
conda_prefix: None,
|
||||
};
|
||||
project.require_trust()?;
|
||||
return host.processes.start(
|
||||
@@ -467,7 +475,11 @@ async fn start_inner(
|
||||
);
|
||||
}
|
||||
let out = on_output.clone();
|
||||
return host.remote.run(&settings, &project.root, &config, sink.clone(), Box::new(move |c| out(c))).await;
|
||||
let debugpy = container::ide_debugpy(&host.data_dir);
|
||||
return host
|
||||
.remote
|
||||
.run(&settings, &project.root, &config, debugpy.as_deref(), sink.clone(), Box::new(move |c| out(c)))
|
||||
.await;
|
||||
}
|
||||
let mut config = config;
|
||||
let (root, settings, fallback) = settings_for(host, &project, &mut config)?;
|
||||
@@ -504,7 +516,7 @@ async fn start_inner(
|
||||
}
|
||||
// A Python configuration pointing at a missing interpreter fails in the depth of
|
||||
// process spawn otherwise; name the cause and the fix like PyCharm's "Invalid SDK".
|
||||
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "doctest" | "django-test");
|
||||
let is_python = ide_run::is_python_kind(&config.kind);
|
||||
if is_python && Path::new(&config.command).components().count() > 1 {
|
||||
let cwd = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
|
||||
let executable = ide_core::project_roots::resolve(&cwd, Path::new(&config.command));
|
||||
@@ -537,7 +549,17 @@ async fn start_inner(
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
if config.kind == "xcode-test" {
|
||||
let bundles = project.cache_dir.join("xcresult");
|
||||
config = host
|
||||
.blocking(move || {
|
||||
ide_run::xcode::prepare_test(&mut config, &bundles)?;
|
||||
Ok(config)
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
let mut python_paths = if *root != project.root { vec![root.clone()] } else { super::python::paths(&project) };
|
||||
let mut conda_prefix = None;
|
||||
if is_python {
|
||||
let near = ide_run::scope::owner(&project.root, &config);
|
||||
python_paths = super::python::with_user_paths(
|
||||
@@ -547,13 +569,16 @@ async fn start_inner(
|
||||
Some(&config.command),
|
||||
Some(&near),
|
||||
);
|
||||
conda_prefix = super::python::conda_prefix(&host.config_dir, &project, Some(&config.command), Some(&near));
|
||||
}
|
||||
let encoding = settings.console.encoding;
|
||||
let options = StartOptions {
|
||||
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
|
||||
python_paths,
|
||||
ruby_reporter: ruby_reporter_dir(host, &config),
|
||||
plots: if is_python { super::plots::prepare(host, &project) } else { None },
|
||||
plots: if is_python { super::plots::prepare(host, &project).await } else { None },
|
||||
capture_junit_reports: config.is_test && config.extras.test_runner.as_deref() == Some("jvm"),
|
||||
conda_prefix,
|
||||
};
|
||||
project.require_trust()?;
|
||||
if config.kind == "go" && matches!(config.args.first().map(String::as_str), Some("mod" | "work")) {
|
||||
@@ -692,6 +717,18 @@ pub use commands::*;
|
||||
#[cfg(test)]
|
||||
mod ownership_tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn source_roots_go_on_the_container_pythonpath() {
|
||||
let root = Path::new("/p");
|
||||
let mut env = std::collections::BTreeMap::from([("PYTHONPATH".to_owned(), "/opt/extra".to_owned())]);
|
||||
container_python_path(&mut env, &[root.into(), root.join("src"), "/home/u/lib".into()], root);
|
||||
assert_eq!(env["PYTHONPATH"], "/p:/p/src:/opt/extra", "outside the project: not mounted");
|
||||
let mut none = std::collections::BTreeMap::new();
|
||||
container_python_path(&mut none, &["/elsewhere".into()], root);
|
||||
assert!(none.is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn unlinked_builds_do_not_reappear_as_detected_application_configs() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
@@ -854,12 +891,63 @@ mod ownership_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The file here of a path a run in a container of `target` printed (`/app/main.py`, a
|
||||
/// `site-packages` module in a traceback): in a folder of the project the container mounts,
|
||||
/// or, when `target` is the project interpreter's, in the copy of its libraries. `None`: no
|
||||
/// such file.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn run_container_path(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: String,
|
||||
target: String,
|
||||
) -> IdeResult<Option<ide_core::IpcPath>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let settings = project.settings.effective();
|
||||
let Some(run_target) =
|
||||
settings.run_targets.iter().find(|t| t.id == target && t.kind != RunTargetKind::Ssh).cloned()
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let snapshots = crate::ops::sdk::container_python::snapshots_of(host, &project.root, &settings, &target);
|
||||
let (root, data_dir) = (project.root.clone(), host.data_dir.clone());
|
||||
host.blocking(move || {
|
||||
if !path.starts_with('/') {
|
||||
return Ok(None);
|
||||
}
|
||||
let library = snapshots
|
||||
.and_then(|dir| ide_sdk::container_python::current(&dir))
|
||||
.and_then(|(dir, snapshot)| ide_sdk::container_python::snapshot_file(&dir, &snapshot, &path));
|
||||
let file = library.filter(|f| f.is_file()).or_else(|| {
|
||||
let mounts = container::mounts(&data_dir, &root, &run_target).ok()?;
|
||||
ide_remote::docker::mounted_file(&path, &mounts).filter(|f| f.is_file())
|
||||
});
|
||||
Ok(file.map(Into::into))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The project's source roots on `PYTHONPATH` in a container, as a local run gets them:
|
||||
/// they are mounted with the project, and `container::prepare` maps their paths. The
|
||||
/// container's separator is `:`, whatever this machine's is.
|
||||
fn container_python_path(env: &mut std::collections::BTreeMap<String, String>, roots: &[PathBuf], root: &Path) {
|
||||
let mut paths: Vec<String> =
|
||||
roots.iter().filter(|p| p.starts_with(root)).map(|p| p.to_string_lossy().into_owned()).collect();
|
||||
if paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
paths.extend(env.get("PYTHONPATH").cloned());
|
||||
env.insert("PYTHONPATH".into(), paths.join(":"));
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
run:
|
||||
run_apply_settings,
|
||||
run_attach,
|
||||
run_close_stdin,
|
||||
run_configs,
|
||||
run_container_path,
|
||||
run_list,
|
||||
run_resize,
|
||||
run_save_configs,
|
||||
|
||||
@@ -22,6 +22,23 @@ pub async fn run_dotnet_resolve(host: &Host, window: &str, config: RunConfig, de
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// The tests of an `xcodebuild test` result bundle, as `xcresulttool` reports them (JSON).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn run_xcode_test_results(host: &Host, window: &str, bundle: std::path::PathBuf) -> IdeResult<String> {
|
||||
host.require_trust(window)?;
|
||||
if bundle.extension().is_none_or(|e| e != "xcresult") {
|
||||
return Err(IdeError::invalid("Not an Xcode result bundle"));
|
||||
}
|
||||
let mut cmd = tokio::process::Command::new("xcrun");
|
||||
cmd.args(["xcresulttool", "get", "test-results", "tests", "--compact", "--path"]).arg(&bundle);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
let out = cmd.output().await?;
|
||||
if !out.status.success() {
|
||||
return Err(IdeError::internal(String::from_utf8_lossy(&out.stderr).trim().to_owned()));
|
||||
}
|
||||
String::from_utf8(out.stdout).map_err(|e| IdeError::internal(e.to_string()))
|
||||
}
|
||||
|
||||
fn application_cache(project: &crate::project::Project, id: &str) -> std::path::PathBuf {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hash = std::collections::hash_map::DefaultHasher::new();
|
||||
@@ -177,18 +194,23 @@ pub async fn run_gradle_init_script(name: String, text: String) -> IdeResult<Str
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Results from the JUnit XML reports (Surefire, Failsafe, Gradle) of the module at
|
||||
/// `module` (relative to the project root) written since `since_ms` (Unix epoch, ms).
|
||||
/// Results from the JUnit XML reports (Surefire, Failsafe, Gradle) changed by `run`.
|
||||
/// Without a run id, read reports in `module` written since `since_ms` (Unix epoch, ms).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn run_test_reports(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
module: Option<std::path::PathBuf>,
|
||||
since_ms: f64,
|
||||
run: Option<ide_core::RunId>,
|
||||
) -> IdeResult<Vec<ide_run::junit::TestCaseReport>> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
let dir = module.map(|m| root.join(m)).unwrap_or(root);
|
||||
let since = std::time::UNIX_EPOCH + std::time::Duration::from_millis(since_ms.max(0.0) as u64);
|
||||
if let Some(run) = run {
|
||||
let processes = host.processes.clone();
|
||||
return crate::ops::blocking_value(move || processes.test_reports(run, &root, since)).await;
|
||||
}
|
||||
let dir = module.map(|m| root.join(m)).unwrap_or(root);
|
||||
tokio::task::spawn_blocking(move || ide_run::junit::read_reports(&ide_run::junit::report_dirs(&dir), since))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
@@ -426,6 +448,7 @@ ide_command::domain!(
|
||||
run_application_build,
|
||||
run_application_publish,
|
||||
run_dotnet_resolve,
|
||||
run_xcode_test_results,
|
||||
run_env_files,
|
||||
run_gradle_init_script,
|
||||
run_gradle_jvm_args_script,
|
||||
|
||||
@@ -6,16 +6,15 @@ use ide_core::remote_settings::{RunTarget, RunTargetKind};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_docker::DockerEndpoint;
|
||||
use ide_remote::docker::{
|
||||
ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, compose_container_root, container_config,
|
||||
container_name, default_container_root,
|
||||
ComposeService, ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, compose_container_root,
|
||||
compose_service, container_config, container_name, default_container_root,
|
||||
};
|
||||
use ide_remote::target::DEBUG_PARAM;
|
||||
use ide_run::RunConfig;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
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";
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// `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> {
|
||||
@@ -39,6 +38,7 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
|
||||
})?;
|
||||
let container_root = container_root(&endpoint, &root, &target)?;
|
||||
let file_env = env_files(&root, &config)?;
|
||||
let (service_env, service_ports) = server_context(&data_dir, &root, &target, &config);
|
||||
let name = container_name(&config.id, &unique());
|
||||
let debugging = if debug { Some(Debugging::prepare(&data_dir)?) } else { None };
|
||||
container_config(
|
||||
@@ -50,6 +50,8 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
|
||||
docker: &docker.to_string_lossy(),
|
||||
endpoint_env: &ide_docker::run_env(&endpoint),
|
||||
file_env: &file_env,
|
||||
service_env: &service_env,
|
||||
service_ports: &service_ports,
|
||||
name: &name,
|
||||
user: user(&root, &target),
|
||||
debug: debugging.as_ref().map(|d| ContainerDebug {
|
||||
@@ -86,6 +88,79 @@ pub(crate) fn container_root(endpoint: &DockerEndpoint, root: &Path, target: &Ru
|
||||
})
|
||||
}
|
||||
|
||||
/// Compose files `docker compose` reads when a target names none.
|
||||
const DEFAULT_COMPOSE_FILES: [&str; 8] = [
|
||||
"compose.yaml",
|
||||
"compose.yml",
|
||||
"docker-compose.yaml",
|
||||
"docker-compose.yml",
|
||||
"compose.override.yaml",
|
||||
"compose.override.yml",
|
||||
"docker-compose.override.yaml",
|
||||
"docker-compose.override.yml",
|
||||
];
|
||||
|
||||
type Mounts = Vec<(PathBuf, String)>;
|
||||
/// The modification times of the Compose files a result was read with.
|
||||
type Stamp = Vec<Option<SystemTime>>;
|
||||
|
||||
/// `docker compose config` per project and target, until a Compose file changes.
|
||||
type ServiceCache = HashMap<(PathBuf, String), (Stamp, ComposeService)>;
|
||||
static COMPOSE_SERVICES: LazyLock<Mutex<ServiceCache>> = LazyLock::new(Default::default);
|
||||
|
||||
/// The folders of the project a container of `target` mounts: `(folder here, folder in
|
||||
/// the container)`. A Compose service's come from `docker compose config` (cached).
|
||||
pub(crate) fn mounts(data_dir: &Path, root: &Path, target: &RunTarget) -> IdeResult<Mounts> {
|
||||
match target.container_root.trim() {
|
||||
"" if target.kind == RunTargetKind::Compose => {}
|
||||
"" => return Ok(vec![(root.to_path_buf(), default_container_root(root))]),
|
||||
folder => return Ok(vec![(root.to_path_buf(), folder.to_owned())]),
|
||||
}
|
||||
Ok(compose_service_of(data_dir, root, target)?.mounts.into_iter().map(|(s, t)| (PathBuf::from(s), t)).collect())
|
||||
}
|
||||
|
||||
/// What `docker compose config` says of `target`'s service (cached until a Compose file changes).
|
||||
fn compose_service_of(data_dir: &Path, root: &Path, target: &RunTarget) -> IdeResult<ComposeService> {
|
||||
let files: Vec<PathBuf> = if target.compose_files.iter().all(|f| f.trim().is_empty()) {
|
||||
DEFAULT_COMPOSE_FILES.iter().map(|f| root.join(f)).collect()
|
||||
} else {
|
||||
target.compose_files.iter().map(|f| root.join(f.trim())).collect()
|
||||
};
|
||||
let stamp: Stamp = files.iter().map(|f| std::fs::metadata(f).and_then(|m| m.modified()).ok()).collect();
|
||||
let key = (root.to_path_buf(), format!("{}\0{}\0{}", target.id, target.service, target.compose_files.join(";")));
|
||||
let cache = || COMPOSE_SERVICES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((seen, service)) = cache().get(&key)
|
||||
&& *seen == stamp
|
||||
{
|
||||
return Ok(service.clone());
|
||||
}
|
||||
let json = ide_docker::compose_config(&endpoint(data_dir, target)?, root, &target.compose_files)?;
|
||||
let service = compose_service(&json, target.service.trim())?;
|
||||
cache().insert(key, (stamp, service.clone()));
|
||||
Ok(service)
|
||||
}
|
||||
|
||||
/// Variables a development server in the container finds besides the configuration's: the
|
||||
/// Compose service's `environment` (and published ports), and the `.env` / `.flaskenv` of the
|
||||
/// folder it runs in. Best effort: a Compose file `docker compose config` can't read gives none.
|
||||
fn server_context(
|
||||
data_dir: &Path,
|
||||
root: &Path,
|
||||
target: &RunTarget,
|
||||
config: &RunConfig,
|
||||
) -> (BTreeMap<String, String>, Vec<(u16, u16)>) {
|
||||
let service = if target.kind == RunTargetKind::Compose {
|
||||
compose_service_of(data_dir, root, target).unwrap_or_default()
|
||||
} else {
|
||||
ComposeService::default()
|
||||
};
|
||||
let cwd = config.cwd.as_ref().map_or(root.to_path_buf(), |c| root.join(c));
|
||||
let dotenv: Vec<PathBuf> = [".env", ".flaskenv"].iter().map(|f| cwd.join(f)).filter(|f| f.is_file()).collect();
|
||||
let mut env = ide_run::envfile::load(&dotenv, &BTreeMap::new()).unwrap_or_default();
|
||||
env.extend(service.environment);
|
||||
(env, service.ports)
|
||||
}
|
||||
|
||||
/// What a debug run mounts and publishes.
|
||||
struct Debugging {
|
||||
port: u16,
|
||||
@@ -99,14 +174,18 @@ impl Debugging {
|
||||
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 })
|
||||
Ok(Self { port: free_port()?, bootstrap_dir, debugpy: ide_debugpy(data_dir) })
|
||||
}
|
||||
}
|
||||
|
||||
/// The managed install the local debugger falls back to (`ide_dap::adapter::prepare_debugpy`):
|
||||
/// the folder holding the `debugpy` package, when it is installed.
|
||||
pub(super) fn ide_debugpy(data_dir: &Path) -> Option<PathBuf> {
|
||||
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);
|
||||
lib.join("debugpy").join("__init__.py").is_file().then_some(lib)
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
|
||||
@@ -377,6 +377,7 @@ pub async fn sdk_python_hatch_envs(host: &Host, window: &str, request: RequestId
|
||||
|
||||
/// Creates a Python environment and streams its output through `on_output`.
|
||||
/// With Pipenv, `install_packages` also installs the packages declared in the project's `Pipfile`.
|
||||
/// With venv / uv, `system_site_packages` lets the environment see the base interpreter's packages.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn sdk_python_create_venv(
|
||||
@@ -386,13 +387,14 @@ pub async fn sdk_python_create_venv(
|
||||
base: PathBuf,
|
||||
location: PathBuf,
|
||||
install_packages: bool,
|
||||
system_site_packages: bool,
|
||||
request: RequestId,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<Sdk> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = blocking(move || {
|
||||
ide_sdk::python::create_venv(tool, &base, &location, install_packages, &cancel, &|line| {
|
||||
ide_sdk::python::create_venv(tool, &base, &location, install_packages, system_site_packages, &cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
@@ -432,7 +434,8 @@ pub async fn sdk_python_package_index(
|
||||
result
|
||||
}
|
||||
|
||||
/// Installs (`uninstall = false`) or removes a package; output streams through `on_output`.
|
||||
/// Installs (`uninstall = false`, in editable mode with `editable`) or removes a package; output
|
||||
/// streams through `on_output`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn sdk_python_pip(
|
||||
@@ -442,6 +445,7 @@ pub async fn sdk_python_pip(
|
||||
requirement: String,
|
||||
uninstall: bool,
|
||||
upgrade: bool,
|
||||
editable: bool,
|
||||
request: RequestId,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
@@ -455,7 +459,15 @@ pub async fn sdk_python_pip(
|
||||
if uninstall {
|
||||
ide_sdk::python::uninstall_package(&python, &requirement, &cancel, &send)
|
||||
} else {
|
||||
ide_sdk::python::install_package(&python, &requirement, upgrade, project_root.as_deref(), &cancel, &send)
|
||||
ide_sdk::python::install_package(
|
||||
&python,
|
||||
&requirement,
|
||||
upgrade,
|
||||
editable,
|
||||
project_root.as_deref(),
|
||||
&cancel,
|
||||
&send,
|
||||
)
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -93,6 +93,12 @@ pub(crate) fn configure_server(
|
||||
snapshots::configure_server(cfg, current.as_ref().map(|(d, s)| (d.as_path(), s)));
|
||||
}
|
||||
|
||||
/// The folder of `target`'s snapshots, when `target` is the project interpreter's
|
||||
/// (no file is read: [`snapshots::current`] reads it).
|
||||
pub(crate) fn snapshots_of(host: &Host, root: &Path, settings: &Settings, target: &str) -> Option<PathBuf> {
|
||||
(settings.languages.python.run_target() == Some(target)).then(|| Dirs::of(host).target(root, target))
|
||||
}
|
||||
|
||||
/// External Libraries: the snapshot's folders, named after the run target.
|
||||
pub(crate) fn library_group(host: &Host, root: &Path, settings: &Settings) -> Option<ide_sdk::libraries::LibraryGroup> {
|
||||
let target = settings.languages.python.run_target()?;
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
//! Settings › Settings Sync › Sync Now: merges this machine's IDE settings with the ones in the
|
||||
//! user's settings repository, pushes the result and applies it here.
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_vcs::settings_repo::{SettingsBranch, SettingsRepo};
|
||||
use ide_workspace::settings_sync::{self as sync, CATEGORIES, STORAGE_CATEGORIES};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value as Json;
|
||||
use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// How the first sync with a repository that already holds settings treats them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SettingsSyncMode {
|
||||
Merge,
|
||||
/// The repository's settings replace this machine's.
|
||||
ReplaceLocal,
|
||||
/// This machine's settings replace the repository's.
|
||||
ReplaceRemote,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SettingsSyncResult {
|
||||
/// The repository holds settings this machine never synced with: sync again with a mode.
|
||||
pub needs_choice: bool,
|
||||
/// Settings both sides changed, where this machine's value replaced the repository's.
|
||||
pub overwritten: Vec<String>,
|
||||
/// This machine's global settings changed.
|
||||
pub settings_changed: bool,
|
||||
/// Frontend storage categories that changed here: category → all its entries now.
|
||||
pub storage: BTreeMap<String, BTreeMap<String, String>>,
|
||||
/// Plugins other computers have and this one does not: id → name.
|
||||
pub plugins_elsewhere: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
type Storage = BTreeMap<String, BTreeMap<String, String>>;
|
||||
|
||||
/// One sync at a time, whichever window asks: they share the clone and the settings file.
|
||||
static RUNNING: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// The repository of the settings, and the categories that sync.
|
||||
fn repository(host: &Host, prompts: bool) -> IdeResult<Option<(SettingsRepo, Vec<&'static str>)>> {
|
||||
let config = host.global_settings.effective().settings_sync;
|
||||
let url = config.repository.trim();
|
||||
if url.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let repo = SettingsRepo::open(&host.data_dir.join("settings-sync"), url, prompts)?;
|
||||
Ok(Some((repo, CATEGORIES.into_iter().filter(|c| sync::enabled(&config, c)).collect())))
|
||||
}
|
||||
|
||||
/// What `category` syncs of this computer's settings `layer` and frontend `storage`.
|
||||
fn local_value(category: &str, layer: &Json, storage: &Storage) -> Json {
|
||||
if STORAGE_CATEGORIES.contains(&category) {
|
||||
let entries = storage.get(category).into_iter().flatten();
|
||||
sync::clean(category, &Json::Object(entries.map(|(k, v)| (k.clone(), Json::String(v.clone()))).collect()))
|
||||
} else {
|
||||
sync::clean(category, layer)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this computer's settings or plugin list differ from what it last synced. Reads only the local
|
||||
/// clone, so an automatic sync after a change that does not sync (a project setting) stays off
|
||||
/// the network.
|
||||
pub fn has_local_changes(host: &Host, storage: &Storage) -> IdeResult<bool> {
|
||||
let _running = RUNNING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Some((repo, enabled)) = repository(host, false)? else { return Ok(false) };
|
||||
let Some(synced) = repo.synced() else { return Ok(true) };
|
||||
let mut names: Vec<String> = enabled.iter().map(|c| sync::file_name(c)).collect();
|
||||
names.push(sync::PLUGINS_FILE.into());
|
||||
let files = repo.files(&synced, &names)?;
|
||||
if host.global_settings.effective().settings_sync.plugins
|
||||
&& let Some((text, _)) = merge_plugins(&files, &machine_id(host)?, storage)
|
||||
&& files.get(sync::PLUGINS_FILE) != Some(&text)
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
let layer = host.global_settings.global_layer()?;
|
||||
let empty = Json::Object(Default::default());
|
||||
Ok(enabled.iter().any(|c| local_value(c, &layer, storage) != sync::from_files(&files, c).unwrap_or(empty.clone())))
|
||||
}
|
||||
|
||||
/// `storage`: the frontend's syncable entries by category (`templates`, `macros`, `ui`), and
|
||||
/// the installed plugins (`plugins`: id → name).
|
||||
/// `mode`: `None` unless the user answered [`SettingsSyncResult::needs_choice`].
|
||||
/// `interactive`: whether git may ask for credentials (Sync Now) or must use saved ones.
|
||||
pub fn sync_now(
|
||||
host: &Host,
|
||||
storage: &Storage,
|
||||
mode: Option<SettingsSyncMode>,
|
||||
interactive: bool,
|
||||
) -> IdeResult<SettingsSyncResult> {
|
||||
let _running = RUNNING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Some((repo, enabled)) = repository(host, interactive)? else {
|
||||
return Err(IdeError::invalid("choose a settings repository first"));
|
||||
};
|
||||
let machine = host.global_settings.effective().settings_sync.plugins.then(|| machine_id(host)).transpose()?;
|
||||
let sync = |mode| sync_once(host, &repo, &enabled, storage, machine.as_deref(), mode);
|
||||
match sync(mode) {
|
||||
// Another machine pushed in between: merge with its settings too.
|
||||
Err(e) if e.kind == ErrorKind::OutOfSync => sync(mode),
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`sync::merge_plugins`] of the plugin list in `files` with this computer's from `storage`.
|
||||
fn merge_plugins(
|
||||
files: &BTreeMap<String, String>,
|
||||
machine: &str,
|
||||
storage: &Storage,
|
||||
) -> Option<(String, BTreeMap<String, String>)> {
|
||||
let local = storage.get("plugins").cloned().unwrap_or_default();
|
||||
sync::merge_plugins(files.get(sync::PLUGINS_FILE).map(String::as_str), machine, &local)
|
||||
}
|
||||
|
||||
/// This computer's id in the repository's plugin list: random, kept in the data directory.
|
||||
fn machine_id(host: &Host) -> IdeResult<String> {
|
||||
let file = host.data_dir.join("settings-sync-id");
|
||||
match std::fs::read_to_string(&file) {
|
||||
Ok(id) if !id.trim().is_empty() => Ok(id.trim().to_owned()),
|
||||
_ => {
|
||||
let id = uuid::Uuid::new_v4().to_string();
|
||||
ide_vfs::write_atomic(&file, id.as_bytes())?;
|
||||
Ok(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_once(
|
||||
host: &Host,
|
||||
repo: &SettingsRepo,
|
||||
enabled: &[&str],
|
||||
storage: &Storage,
|
||||
machine: Option<&str>,
|
||||
mode: Option<SettingsSyncMode>,
|
||||
) -> IdeResult<SettingsSyncResult> {
|
||||
let mut names: Vec<String> = CATEGORIES.iter().map(|c| sync::file_name(c)).collect();
|
||||
names.push(sync::PLUGINS_FILE.into());
|
||||
let branch = repo.fetch()?;
|
||||
let remote_files = match &branch.commit {
|
||||
Some(commit) => repo.files(commit, &names)?,
|
||||
None => BTreeMap::new(),
|
||||
};
|
||||
let base_files = repo.synced().map(|commit| repo.files(&commit, &names)).transpose()?;
|
||||
if base_files.is_none() && mode.is_none() && enabled.iter().any(|c| remote_files.contains_key(&sync::file_name(c)))
|
||||
{
|
||||
return Ok(SettingsSyncResult { needs_choice: true, ..Default::default() });
|
||||
}
|
||||
let layer = host.global_settings.global_layer()?;
|
||||
let mut result = SettingsSyncResult::default();
|
||||
let mut files = remote_files.clone();
|
||||
let mut layer_changes = Vec::new();
|
||||
for &category in enabled {
|
||||
let local = local_value(category, &layer, storage);
|
||||
let remote = sync::from_files(&remote_files, category);
|
||||
let name = sync::file_name(category);
|
||||
// A file that can't be read says nothing about the settings: only this computer's
|
||||
// replacing the repository's may overwrite it.
|
||||
if remote.is_none() && remote_files.contains_key(&name) && mode != Some(SettingsSyncMode::ReplaceRemote) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{name} in the settings repository is not valid; fix or delete it, then sync again"
|
||||
)));
|
||||
}
|
||||
let merged = match mode {
|
||||
Some(SettingsSyncMode::ReplaceLocal) => remote.unwrap_or_else(|| local.clone()),
|
||||
Some(SettingsSyncMode::ReplaceRemote) => local.clone(),
|
||||
Some(SettingsSyncMode::Merge) | None => {
|
||||
// A deleted file is not a removal of every setting: without it there is no base.
|
||||
let base = remote.as_ref().and(base_files.as_ref()).and_then(|files| sync::from_files(files, category));
|
||||
sync::merge3(base.as_ref(), Some(&local), remote.as_ref(), &mut Vec::new(), &mut result.overwritten)
|
||||
.unwrap_or_else(|| Json::Object(Default::default()))
|
||||
}
|
||||
};
|
||||
files.insert(sync::file_name(category), sync::to_file(&merged));
|
||||
if merged == local {
|
||||
continue;
|
||||
}
|
||||
if STORAGE_CATEGORIES.contains(&category) {
|
||||
let entries = serde_json::from_value(merged).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
result.storage.insert(category.to_owned(), entries);
|
||||
} else {
|
||||
layer_changes.extend(sync::local_changes(&layer, category, &local, &merged));
|
||||
}
|
||||
}
|
||||
if let Some(machine) = machine {
|
||||
match merge_plugins(&remote_files, machine, storage) {
|
||||
Some((text, elsewhere)) => {
|
||||
files.insert(sync::PLUGINS_FILE.into(), text);
|
||||
result.plugins_elsewhere = elsewhere;
|
||||
}
|
||||
None => {
|
||||
tracing::warn!("{} in the settings repository can't be read: plugins don't sync", sync::PLUGINS_FILE)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Check before anything leaves this machine that the merged settings load here.
|
||||
host.global_settings.apply_global_changes(&layer_changes, false)?;
|
||||
if files != remote_files {
|
||||
repo.publish(&branch, &files, "Sync settings")?;
|
||||
} else if let SettingsBranch { commit: Some(commit), .. } = &branch {
|
||||
repo.mark_synced(commit)?;
|
||||
}
|
||||
if !layer_changes.is_empty() {
|
||||
host.global_settings.apply_global_changes(&layer_changes, true)?;
|
||||
result.settings_changed = true;
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
@@ -175,6 +175,14 @@ pub struct VcsRoot {
|
||||
/// The history ends at a shallow boundary rather than at the initial commit.
|
||||
#[serde(default)]
|
||||
pub shallow: bool,
|
||||
/// The root `.gitattributes` tracks files with Git LFS.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub lfs: bool,
|
||||
/// Submodules (repository-relative) whose checkout was never initialized.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub uninitialized_submodules: Vec<String>,
|
||||
/// Remote availability is unknown in Restricted Mode or when config cannot be read.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
@@ -220,6 +228,12 @@ pub enum RemoteOp {
|
||||
UpdateSubmodule {
|
||||
parent: PathBuf,
|
||||
},
|
||||
/// Git › Pull LFS Objects.
|
||||
PullLfs,
|
||||
/// Git › Submodules › Initialize Submodules.
|
||||
InitSubmodules,
|
||||
/// Git › Submodules › Sync Submodule URLs.
|
||||
SyncSubmodules,
|
||||
/// Update Project › Reset to the Remote Branch.
|
||||
ResetToUpstream,
|
||||
Push {
|
||||
@@ -559,6 +573,13 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
head,
|
||||
head_commit,
|
||||
shallow: r.is_shallow().unwrap_or(false),
|
||||
lfs: r.uses_lfs(),
|
||||
uninitialized_submodules: r
|
||||
.uninitialized_submodules()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|path| ide_core::ipc_path::to_ipc(path))
|
||||
.collect(),
|
||||
has_remotes: trusted.then(|| r.has_remotes().ok()).flatten(),
|
||||
resolved_conflicts,
|
||||
}
|
||||
@@ -768,6 +789,73 @@ pub async fn vcs_block_history(
|
||||
result
|
||||
}
|
||||
|
||||
/// History for Selection summary: revision headers plus the initial diff batch
|
||||
/// (or all diffs for small selections/histories). Cancellable with `cancel_request(request)`.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_block_history_summary(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
path: PathBuf,
|
||||
text: Option<String>,
|
||||
lines: (u32, u32),
|
||||
) -> IdeResult<BlockHistorySummary> {
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = blocking(move || {
|
||||
let text = text.or_else(|| project.documents.text_of(&path));
|
||||
project.with_repo_of(&path, |r| {
|
||||
r.block_history_summary(&path, text.as_deref(), lines, project.vcs_encoding(&path, None)?, &cancel)
|
||||
})
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Diffs for up to four revisions of a selection history, walking from `anchor` with `--skip`.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_block_history_revisions(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
path: PathBuf,
|
||||
anchor: BlockHistoryAnchor,
|
||||
index: u32,
|
||||
commits: Vec<String>,
|
||||
) -> IdeResult<Vec<BlockRevision>> {
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = blocking(move || {
|
||||
project.with_repo_of(&path, |r| {
|
||||
r.block_history_revisions(&path, &anchor, index, &commits, project.vcs_encoding(&path, None)?, &cancel)
|
||||
})
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// The diffs of up to four revisions read from their spots ([`Repo::block_history_revisions_at`]).
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_block_history_revisions_at(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
path: PathBuf,
|
||||
spots: Vec<BlockRevisionSpot>,
|
||||
) -> IdeResult<Vec<BlockRevision>> {
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = blocking(move || {
|
||||
project
|
||||
.with_repo_of(&path, |r| r.block_history_revisions_at(&spots, project.vcs_encoding(&path, None)?, &cancel))
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_log(host: &Host, window: &str, repo: Option<PathBuf>, query: LogQuery) -> IdeResult<Vec<Commit>> {
|
||||
let project = LogAccess::new(host, window, repo.as_deref());
|
||||
@@ -1708,7 +1796,9 @@ pub async fn vcs_remote(
|
||||
| RemoteOp::PullFrom { .. }
|
||||
| RemoteOp::UpdateProjectBranch { .. }
|
||||
| RemoteOp::ResetToUpstream => Some("Git pull"),
|
||||
RemoteOp::UpdateSubmodule { .. } => Some("Git submodule update"),
|
||||
RemoteOp::UpdateSubmodule { .. } | RemoteOp::InitSubmodules => Some("Git submodule update"),
|
||||
RemoteOp::SyncSubmodules => Some("Git submodule sync"),
|
||||
RemoteOp::PullLfs => Some("Git LFS pull"),
|
||||
_ => None,
|
||||
};
|
||||
with_shelf_batch(&project, shelf_batch, || {
|
||||
@@ -1744,6 +1834,9 @@ pub async fn vcs_remote(
|
||||
RemoteOp::UpdateSubmodule { parent } => project.with_repo_at(Some(&parent), |parent| {
|
||||
r.update_from_superproject(parent, &cancel, &out).map(|()| None)
|
||||
}),
|
||||
RemoteOp::PullLfs => r.pull_lfs(&cancel, &out).map(|()| None),
|
||||
RemoteOp::InitSubmodules => r.init_submodules(&cancel, &out).map(|()| None),
|
||||
RemoteOp::SyncSubmodules => r.sync_submodules(&cancel, &out).map(|()| None),
|
||||
RemoteOp::ResetToUpstream => r.reset_to_upstream_with_tags(tags_mode, &cancel, &out).map(|()| None),
|
||||
RemoteOp::Push { force_with_lease, set_upstream, tags, force, no_verify } => r
|
||||
.push_with(PushOptions { force_with_lease, force, set_upstream, tags, no_verify }, &cancel, &out)
|
||||
@@ -1923,11 +2016,20 @@ pub async fn vcs_clone(
|
||||
}
|
||||
|
||||
/// `git init` in `dir` (VCS › Create Git Repository…): with the git of the window's project when
|
||||
/// it is trusted, the default one in a window without a project.
|
||||
/// it is trusted, the default one in a window without a project. The project's repositories are
|
||||
/// detected again before it returns, so the new one is known to the next command.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_init(host: &Host, window: &str, dir: PathBuf) -> IdeResult<()> {
|
||||
let git = host.project(window).ok().and_then(|p| p.git_executable());
|
||||
blocking(move || ide_vcs::with_git_executable(git.as_deref(), || ide_vcs::init(&dir))).await
|
||||
let project = host.project(window).ok();
|
||||
let git = project.as_ref().and_then(|p| p.git_executable());
|
||||
blocking(move || {
|
||||
ide_vcs::with_git_executable(git.as_deref(), || ide_vcs::init(&dir))?;
|
||||
if let Some(p) = project {
|
||||
p.refresh_repositories();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Settings › Git › Test: runs `git --version` on `path`, or on the auto-detected
|
||||
@@ -2002,6 +2104,33 @@ pub async fn vcs_gpg_signing_keys(
|
||||
result
|
||||
}
|
||||
|
||||
/// Lists SSH public keys from ssh-agent and `~/.ssh` for SSH commit signing.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_ssh_signing_keys(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: PathBuf,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Vec<SshSigningKey>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = blocking(move || project.with_repo_at(Some(&repo), |repo| repo.ssh_signing_keys(&cancel))).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Git LFS files of the repository still checked out as pointer files, and whether git-lfs runs.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_lfs_status(host: &Host, window: &str, repo: PathBuf, request: RequestId) -> IdeResult<LfsStatus> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = blocking(move || project.with_repo_at(Some(&repo), |repo| repo.lfs_status(&cancel))).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Updates the selected repository's Git config.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_edit_signing(host: &Host, window: &str, repo: PathBuf, edit: GitSigningEdit) -> IdeResult<()> {
|
||||
@@ -3179,6 +3308,9 @@ ide_command::domain!(
|
||||
vcs_apply_mapped_patch,
|
||||
vcs_blame,
|
||||
vcs_block_history,
|
||||
vcs_block_history_summary,
|
||||
vcs_block_history_revisions,
|
||||
vcs_block_history_revisions_at,
|
||||
vcs_branch_info,
|
||||
vcs_check_incoming,
|
||||
vcs_branches,
|
||||
@@ -3200,7 +3332,9 @@ ide_command::domain!(
|
||||
vcs_config_get,
|
||||
vcs_config_get_bool,
|
||||
vcs_signing_config,
|
||||
vcs_lfs_status,
|
||||
vcs_gpg_signing_keys,
|
||||
vcs_ssh_signing_keys,
|
||||
vcs_edit_signing,
|
||||
vcs_watch_commit_messages,
|
||||
vcs_set_user_identity,
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
//! Code insight for Xcode projects: sourcekit-lsp doesn't read `.xcodeproj` / `.xcworkspace`
|
||||
//! files, it gets their build settings from a Build Server Protocol server named in
|
||||
//! `.bsp/*.json` or the legacy `buildServer.json`. The IDE neither bundles nor installs a BSP
|
||||
//! server: it offers to run the one on `PATH` (xcode-build-server, sourcekit-xcode-bsp) to write
|
||||
//! the config, then restarts sourcekit-lsp.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// The generators, in order of preference, and their arguments for `container`.
|
||||
const TOOLS: [&str; 2] = ["xcode-build-server", "sourcekit-xcode-bsp"];
|
||||
|
||||
fn tool_args(tool: &str, container: &str) -> Vec<String> {
|
||||
if tool == "sourcekit-xcode-bsp" {
|
||||
// Detects the workspace or project in the working directory itself.
|
||||
return vec!["init".into()];
|
||||
}
|
||||
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
|
||||
// Without `-scheme` it binds the scheme built last.
|
||||
vec!["config".into(), flag.into(), container.into()]
|
||||
}
|
||||
|
||||
/// An Xcode project without a BSP config, at the project root.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct XcodeBspSetup {
|
||||
/// The `.xcworkspace` (preferred) or `.xcodeproj` the config is generated for.
|
||||
pub container: String,
|
||||
/// The generator found on `PATH`; `None`: neither is installed.
|
||||
pub tool: Option<String>,
|
||||
}
|
||||
|
||||
/// `name` is an Xcode bundle directly in the root, not a path or an option.
|
||||
fn is_container_name(name: &str) -> bool {
|
||||
!name.starts_with(['-', '.'])
|
||||
&& !name.contains(['/', '\\'])
|
||||
&& (name.ends_with(".xcworkspace") || name.ends_with(".xcodeproj"))
|
||||
}
|
||||
|
||||
/// The `.xcworkspace` (else `.xcodeproj`) at `root` when `root` has no BSP config.
|
||||
fn unconfigured_container(root: &Path) -> Option<String> {
|
||||
if root.join("buildServer.json").exists() || root.join(".bsp").is_dir() {
|
||||
return None;
|
||||
}
|
||||
let mut names: Vec<String> = std::fs::read_dir(root)
|
||||
.ok()?
|
||||
.flatten()
|
||||
.filter(|e| e.path().is_dir())
|
||||
.filter_map(|e| e.file_name().into_string().ok())
|
||||
.collect();
|
||||
names.sort();
|
||||
let find = |ext: &str| names.iter().find(|n| n.ends_with(ext)).cloned();
|
||||
find(".xcworkspace").or_else(|| find(".xcodeproj"))
|
||||
}
|
||||
|
||||
/// What the project root needs for code insight in its Xcode project; `None` when it has no
|
||||
/// Xcode project, or already has a BSP config.
|
||||
#[command(trust = trusted)]
|
||||
pub fn xcode_bsp_setup(host: &Host, window: &str) -> IdeResult<Option<XcodeBspSetup>> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
let Some(container) = unconfigured_container(&root) else { return Ok(None) };
|
||||
let search = ide_core::tool_path::search_path_in(&root);
|
||||
let tool =
|
||||
TOOLS.iter().find(|t| ide_core::tool_path::find_command(t, &search, &root).is_some()).map(|t| t.to_string());
|
||||
Ok(Some(XcodeBspSetup { container, tool }))
|
||||
}
|
||||
|
||||
/// Writes the BSP config at the project root with `tool`, then restarts the project's
|
||||
/// sourcekit-lsp so it reads it.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, container: String) -> IdeResult<()> {
|
||||
if !TOOLS.contains(&tool.as_str()) {
|
||||
return Err(IdeError::invalid(format!("not a BSP config generator: {tool}")));
|
||||
}
|
||||
if !is_container_name(&container) {
|
||||
return Err(IdeError::invalid(format!("not an Xcode workspace or project: {container}")));
|
||||
}
|
||||
let project = host.project(window)?;
|
||||
let root = project.root.clone();
|
||||
super::blocking(move || {
|
||||
let search = ide_core::tool_path::search_path_in(&root);
|
||||
let exe = ide_core::tool_path::find_command(&tool, &search, &root)
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{tool} is not installed")))?;
|
||||
let mut cmd = Command::new(exe);
|
||||
ide_core::process::prepare(&mut cmd)
|
||||
.args(tool_args(&tool, &container))
|
||||
.current_dir(&root)
|
||||
.env("PATH", &search)
|
||||
.stdin(Stdio::null());
|
||||
let out = cmd.output().map_err(|e| IdeError::unavailable(format!("{tool}: {e}")))?;
|
||||
if out.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let message = if stderr.trim().is_empty() { stdout } else { stderr };
|
||||
Err(IdeError::unavailable(format!("{tool} failed: {}", message.trim())))
|
||||
})
|
||||
.await?;
|
||||
for server in project.lsp.servers().into_iter().filter(|s| s.name == "sourcekit-lsp") {
|
||||
project.lsp.restart(server.id).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
ide_command::domain!(xcode_bsp: xcode_bsp_setup, xcode_bsp_generate);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn prefers_the_workspace_and_skips_configured_roots() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
assert_eq!(unconfigured_container(root), None);
|
||||
std::fs::create_dir(root.join("App.xcodeproj")).unwrap();
|
||||
assert_eq!(unconfigured_container(root).as_deref(), Some("App.xcodeproj"));
|
||||
std::fs::create_dir(root.join("App.xcworkspace")).unwrap();
|
||||
assert_eq!(unconfigured_container(root).as_deref(), Some("App.xcworkspace"));
|
||||
std::fs::create_dir(root.join(".bsp")).unwrap();
|
||||
assert_eq!(unconfigured_container(root), None);
|
||||
std::fs::remove_dir(root.join(".bsp")).unwrap();
|
||||
std::fs::write(root.join("buildServer.json"), "{}").unwrap();
|
||||
assert_eq!(unconfigured_container(root), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_the_container_to_xcode_build_server() {
|
||||
assert_eq!(tool_args("xcode-build-server", "A.xcworkspace"), ["config", "-workspace", "A.xcworkspace"]);
|
||||
assert_eq!(tool_args("xcode-build-server", "A.xcodeproj"), ["config", "-project", "A.xcodeproj"]);
|
||||
assert_eq!(tool_args("sourcekit-xcode-bsp", "A.xcodeproj"), ["init"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_only_bundle_names_in_the_root() {
|
||||
assert!(is_container_name("App.xcworkspace") && is_container_name("App.xcodeproj"));
|
||||
for bad in ["../App.xcodeproj", "sub/App.xcodeproj", "-scheme.xcodeproj", "App.swift", ".hidden.xcodeproj"] {
|
||||
assert!(!is_container_name(bad), "{bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -107,13 +107,14 @@ pub async fn plugin_set_ui_locale(plugins: &Arc<PluginHost>, tag: String) -> Ide
|
||||
|
||||
/// Workbench events from this window (only the kinds of `plugin_event_kinds`).
|
||||
#[command(trust = trusted)]
|
||||
pub fn plugin_post_events(
|
||||
pub async fn plugin_post_events(
|
||||
plugins: &Arc<PluginHost>,
|
||||
window: &str,
|
||||
events: Vec<WorkbenchEvent>,
|
||||
editor: Option<PluginEditor>,
|
||||
) {
|
||||
plugins.post_window_events(window, events, editor);
|
||||
let (plugins, window) = (plugins.clone(), window.to_owned());
|
||||
let _ = tokio::task::spawn_blocking(move || plugins.post_window_events(&window, events, editor)).await;
|
||||
}
|
||||
|
||||
/// Kinds of workbench events plugins want (re-fetch on `subscriptionsChanged`).
|
||||
@@ -157,13 +158,14 @@ pub fn plugin_answer_commit(plugins: &Arc<PluginHost>, request_id: String, answe
|
||||
/// The UI reports the focused editor's file (`editor-focused` events), with its
|
||||
/// caret so plugins can scope line labels without re-reading the document.
|
||||
#[command(trust = always)]
|
||||
pub fn plugin_set_active_file(
|
||||
pub async fn plugin_set_active_file(
|
||||
plugins: &Arc<PluginHost>,
|
||||
window: &str,
|
||||
path: Option<String>,
|
||||
#[default] editor: Option<PluginEditor>,
|
||||
) {
|
||||
plugins.set_active_file(window, path, editor);
|
||||
let (plugins, window) = (plugins.clone(), window.to_owned());
|
||||
let _ = tokio::task::spawn_blocking(move || plugins.set_active_file(&window, path, editor)).await;
|
||||
}
|
||||
|
||||
/// The invoking window's reply to a plugin command request.
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
//! Plugin documentation: Overview (`description` / `description-file`) and
|
||||
//! What's New (`change-notes` / `change-notes-file`), with per-locale
|
||||
//! translations from `locales/<tag>.json` and sibling `<stem>.<tag>.<ext>` files.
|
||||
|
||||
use ide_extension::{LOCALES_DIR, Manifest, Package, check_relative};
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Maximum size of a single Markdown documentation file referenced by a manifest.
|
||||
pub const MAX_PLUGIN_DOC: usize = 256 << 10;
|
||||
|
||||
/// Resolved Overview and What's New texts of a plugin package, plus the package
|
||||
/// files they reference.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct PluginDocs {
|
||||
pub description: String,
|
||||
pub change_notes: Option<String>,
|
||||
pub description_locales: BTreeMap<String, String>,
|
||||
pub change_notes_locales: BTreeMap<String, String>,
|
||||
/// Package-relative Markdown files referenced (base + localized siblings).
|
||||
pub files: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl PluginDocs {
|
||||
pub fn from_manifest(manifest: &Manifest) -> Self {
|
||||
Self {
|
||||
description: manifest.description.clone(),
|
||||
change_notes: manifest.change_notes.clone(),
|
||||
description_locales: BTreeMap::new(),
|
||||
change_notes_locales: BTreeMap::new(),
|
||||
files: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) 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()))
|
||||
}
|
||||
|
||||
fn is_markdown_path(path: &Path) -> bool {
|
||||
path.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.is_some_and(|e| e.eq_ignore_ascii_case("md") || e.eq_ignore_ascii_case("markdown"))
|
||||
}
|
||||
|
||||
fn read_markdown_file(pkg: &Package, path: &Path, what: &str) -> Result<String, String> {
|
||||
check_relative(path, what)?;
|
||||
if !is_markdown_path(path) {
|
||||
return Err(format!("{what} {:?}: must be a .md or .markdown file", path.display()));
|
||||
}
|
||||
let text = pkg.read_text(path)?;
|
||||
if text.len() > MAX_PLUGIN_DOC {
|
||||
return Err(format!("{}: larger than {} KiB", path.display(), MAX_PLUGIN_DOC >> 10));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// Discovers sibling `<stem>.<tag>.<ext>` Markdown files next to `base` (e.g.
|
||||
/// `description.zh-CN.md` next to `description.md`), validates each one, and
|
||||
/// returns `(tag -> text, relative_files)`.
|
||||
fn discover_localized_markdown(
|
||||
pkg: &Package,
|
||||
base: &Path,
|
||||
what: &str,
|
||||
) -> Result<(BTreeMap<String, String>, Vec<PathBuf>), String> {
|
||||
let Some(stem) = base.file_stem().and_then(|s| s.to_str()) else {
|
||||
return Ok((BTreeMap::new(), Vec::new()));
|
||||
};
|
||||
let Some(ext) = base.extension().and_then(|e| e.to_str()) else {
|
||||
return Ok((BTreeMap::new(), Vec::new()));
|
||||
};
|
||||
let parent_rel = base.parent().unwrap_or_else(|| Path::new(""));
|
||||
let parent_dir = pkg.dir.join(parent_rel);
|
||||
let Ok(entries) = std::fs::read_dir(&parent_dir) else {
|
||||
return Ok((BTreeMap::new(), Vec::new()));
|
||||
};
|
||||
let mut names: Vec<String> = entries.filter_map(|e| e.ok()?.file_name().into_string().ok()).collect();
|
||||
names.sort();
|
||||
|
||||
let prefix = format!("{stem}.");
|
||||
let suffix_len = ext.len() + 1; // ".<ext>"
|
||||
let mut localized = BTreeMap::new();
|
||||
let mut files = Vec::new();
|
||||
for name in names {
|
||||
if name.len() <= prefix.len() + suffix_len || !name.starts_with(&prefix) {
|
||||
continue;
|
||||
}
|
||||
let Some((before_ext, file_ext)) = name.rsplit_once('.') else {
|
||||
continue;
|
||||
};
|
||||
if !file_ext.eq_ignore_ascii_case(ext) {
|
||||
continue;
|
||||
}
|
||||
let Some(tag) = before_ext.strip_prefix(&prefix) else {
|
||||
continue;
|
||||
};
|
||||
if !locale_tag_ok(tag) {
|
||||
continue;
|
||||
}
|
||||
let rel = if parent_rel.as_os_str().is_empty() { PathBuf::from(&name) } else { parent_rel.join(&name) };
|
||||
let text = read_markdown_file(pkg, &rel, what)?;
|
||||
localized.insert(tag.to_owned(), text);
|
||||
files.push(rel);
|
||||
}
|
||||
Ok((localized, files))
|
||||
}
|
||||
|
||||
/// Reads valid `locales/<tag>.json` catalogs from `pkg` (malformed catalogs are
|
||||
/// ignored here and reported by `ui_points::locales` during `prepare`).
|
||||
fn read_locale_catalogs(pkg: &Package) -> BTreeMap<String, BTreeMap<String, String>> {
|
||||
let dir = Path::new(LOCALES_DIR);
|
||||
let Ok(entries) = std::fs::read_dir(pkg.dir.join(dir)) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let mut out = BTreeMap::new();
|
||||
for entry in entries.flatten() {
|
||||
let Ok(name) = entry.file_name().into_string() else { continue };
|
||||
let Some(tag) = name.strip_suffix(".json") else { continue };
|
||||
if !locale_tag_ok(tag) {
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = pkg.read_text(&dir.join(&name)) else { continue };
|
||||
let Ok(raw) = serde_json::from_str::<BTreeMap<String, Value>>(&text) else { continue };
|
||||
let catalog: BTreeMap<String, String> =
|
||||
raw.into_iter().filter_map(|(k, v)| v.as_str().map(|s| (k, s.to_owned()))).collect();
|
||||
out.insert(tag.to_owned(), catalog);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn lookup_translation<'a>(catalog: &'a BTreeMap<String, String>, source: &str) -> Option<&'a str> {
|
||||
if let Some(v) = catalog.get(source) {
|
||||
return Some(v.as_str());
|
||||
}
|
||||
let trimmed = source.trim();
|
||||
if trimmed != source {
|
||||
return catalog.get(trimmed).map(String::as_str);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Reads and validates a plugin package's Overview (`description` / `description-file`)
|
||||
/// and What's New (`change-notes` / `change-notes-file`), along with their
|
||||
/// per-locale translations from `locales/<tag>.json` and localized Markdown siblings.
|
||||
pub fn plugin_docs(pkg: &Package) -> Result<PluginDocs, String> {
|
||||
let mut files = Vec::new();
|
||||
let description = match &pkg.manifest.description_file {
|
||||
Some(path) => {
|
||||
let text = read_markdown_file(pkg, path, "description-file")?;
|
||||
files.push(path.clone());
|
||||
text
|
||||
}
|
||||
None => pkg.manifest.description.clone(),
|
||||
};
|
||||
let change_notes = match &pkg.manifest.change_notes_file {
|
||||
Some(path) => {
|
||||
let text = read_markdown_file(pkg, path, "change-notes-file")?;
|
||||
files.push(path.clone());
|
||||
Some(text).filter(|s| !s.trim().is_empty())
|
||||
}
|
||||
None => pkg.manifest.change_notes.clone(),
|
||||
};
|
||||
|
||||
let mut description_locales = BTreeMap::new();
|
||||
let mut change_notes_locales = BTreeMap::new();
|
||||
|
||||
for (tag, catalog) in read_locale_catalogs(pkg) {
|
||||
if !description.trim().is_empty()
|
||||
&& let Some(tr) = lookup_translation(&catalog, &description)
|
||||
{
|
||||
description_locales.insert(tag.clone(), tr.to_owned());
|
||||
}
|
||||
if let Some(notes) = &change_notes
|
||||
&& !notes.trim().is_empty()
|
||||
&& let Some(tr) = lookup_translation(&catalog, notes)
|
||||
{
|
||||
change_notes_locales.insert(tag.clone(), tr.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(path) = &pkg.manifest.description_file {
|
||||
let (localized, extra_files) = discover_localized_markdown(pkg, path, "description-file")?;
|
||||
description_locales.extend(localized);
|
||||
files.extend(extra_files);
|
||||
}
|
||||
if let Some(path) = &pkg.manifest.change_notes_file {
|
||||
let (localized, extra_files) = discover_localized_markdown(pkg, path, "change-notes-file")?;
|
||||
change_notes_locales.extend(localized);
|
||||
files.extend(extra_files);
|
||||
}
|
||||
|
||||
files.sort();
|
||||
files.dedup();
|
||||
Ok(PluginDocs { description, change_notes, description_locales, change_notes_locales, files })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pkg_with(dir: &Path, extra_toml: &str) -> Package {
|
||||
let src = format!(
|
||||
"id = \"acme.docs\"\nname = \"Docs\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.18\"\n{extra_toml}"
|
||||
);
|
||||
let manifest = Manifest::parse(&src).unwrap();
|
||||
Package::new(manifest, dir.to_path_buf())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_fields_and_locale_catalog_translations() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(tmp.path().join("locales")).unwrap();
|
||||
std::fs::write(
|
||||
tmp.path().join("locales/zh-CN.json"),
|
||||
r#"{
|
||||
"Plain description.": "纯文本描述。",
|
||||
"0.2.0 — fixes\n0.1.0 — init": "0.2.0 — 修复\n0.1.0 — 初始版本"
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let pkg = pkg_with(
|
||||
tmp.path(),
|
||||
"description = \"Plain description.\"\nchange-notes = \"\"\"\n0.2.0 — fixes\n0.1.0 — init\n\"\"\"\n",
|
||||
);
|
||||
let docs = plugin_docs(&pkg).unwrap();
|
||||
assert_eq!(docs.description, "Plain description.");
|
||||
assert_eq!(docs.description_locales.get("zh-CN").map(String::as_str), Some("纯文本描述。"));
|
||||
assert_eq!(docs.change_notes_locales.get("zh-CN").map(String::as_str), Some("0.2.0 — 修复\n0.1.0 — 初始版本"));
|
||||
assert!(docs.files.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markdown_files_and_localized_siblings_are_loaded_and_tracked() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(tmp.path().join("docs")).unwrap();
|
||||
std::fs::create_dir_all(tmp.path().join("locales")).unwrap();
|
||||
std::fs::write(tmp.path().join("docs/overview.md"), "# English Overview\n\n- Item 1\n").unwrap();
|
||||
std::fs::write(tmp.path().join("docs/overview.zh-CN.md"), "# 中文概览\n\n- 条目 1\n").unwrap();
|
||||
std::fs::write(tmp.path().join("docs/overview.fr.md"), "# Aperçu\n").unwrap();
|
||||
std::fs::write(tmp.path().join("CHANGELOG.md"), "## 1.0.0\n\n- Initial\n").unwrap();
|
||||
std::fs::write(tmp.path().join("CHANGELOG.zh-CN.md"), "## 1.0.0\n\n- 首发\n").unwrap();
|
||||
// Sibling localized .md takes precedence over locales/<tag>.json for the same tag.
|
||||
std::fs::write(tmp.path().join("locales/zh-CN.json"), r##"{ "# English Overview\n\n- Item 1": "from json" }"##)
|
||||
.unwrap();
|
||||
|
||||
let pkg =
|
||||
pkg_with(tmp.path(), "description-file = \"docs/overview.md\"\nchange-notes-file = \"CHANGELOG.md\"\n");
|
||||
let docs = plugin_docs(&pkg).unwrap();
|
||||
assert_eq!(docs.description, "# English Overview\n\n- Item 1\n");
|
||||
assert_eq!(docs.description_locales.get("zh-CN").map(String::as_str), Some("# 中文概览\n\n- 条目 1\n"));
|
||||
assert_eq!(docs.description_locales.get("fr").map(String::as_str), Some("# Aperçu\n"));
|
||||
assert_eq!(docs.change_notes.as_deref(), Some("## 1.0.0\n\n- Initial\n"));
|
||||
assert_eq!(docs.change_notes_locales.get("zh-CN").map(String::as_str), Some("## 1.0.0\n\n- 首发\n"));
|
||||
assert_eq!(
|
||||
docs.files,
|
||||
vec![
|
||||
PathBuf::from("CHANGELOG.md"),
|
||||
PathBuf::from("CHANGELOG.zh-CN.md"),
|
||||
PathBuf::from("docs/overview.fr.md"),
|
||||
PathBuf::from("docs/overview.md"),
|
||||
PathBuf::from("docs/overview.zh-CN.md"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_non_markdown_non_utf8_and_oversized_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
// Missing file
|
||||
let missing = pkg_with(tmp.path(), "description-file = \"missing.md\"\n");
|
||||
assert!(plugin_docs(&missing).unwrap_err().contains("no such file"));
|
||||
|
||||
// Non-markdown extension
|
||||
std::fs::write(tmp.path().join("notes.txt"), "hello").unwrap();
|
||||
let bad_ext = pkg_with(tmp.path(), "change-notes-file = \"notes.txt\"\n");
|
||||
assert!(plugin_docs(&bad_ext).unwrap_err().contains(".md or .markdown"));
|
||||
|
||||
// Invalid UTF-8 in localized sibling
|
||||
std::fs::write(tmp.path().join("description.md"), "# OK\n").unwrap();
|
||||
std::fs::write(tmp.path().join("description.zh-CN.md"), [0xff, 0xfe, 0xfd]).unwrap();
|
||||
let bad_utf8 = pkg_with(tmp.path(), "description-file = \"description.md\"\n");
|
||||
assert!(plugin_docs(&bad_utf8).unwrap_err().contains("not UTF-8"));
|
||||
std::fs::remove_file(tmp.path().join("description.zh-CN.md")).unwrap();
|
||||
|
||||
// Oversized file
|
||||
let huge = "a".repeat(MAX_PLUGIN_DOC + 1);
|
||||
std::fs::write(tmp.path().join("CHANGELOG.md"), huge).unwrap();
|
||||
let oversized = pkg_with(tmp.path(), "change-notes-file = \"CHANGELOG.md\"\n");
|
||||
assert!(plugin_docs(&oversized).unwrap_err().contains("larger than"));
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,8 @@ mod console_rules;
|
||||
mod database;
|
||||
mod dependencies;
|
||||
pub(crate) mod diagnostics;
|
||||
pub mod endpoints;
|
||||
pub mod docs;
|
||||
mod endpoints;
|
||||
mod event_paths;
|
||||
mod execution;
|
||||
mod external_watch;
|
||||
@@ -65,6 +66,7 @@ mod websocket;
|
||||
|
||||
pub use api::{CredentialSecretStore, FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
|
||||
pub use build_graph::{BuildGraph, GradleModule};
|
||||
pub use docs::{MAX_PLUGIN_DOC, PluginDocs, plugin_docs};
|
||||
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,
|
||||
@@ -229,12 +231,17 @@ struct LoadedPlugin {
|
||||
pkg: Package,
|
||||
/// Read at load so disabled and failed plugins show it too.
|
||||
icon: Option<ide_extension::package::PluginIcon>,
|
||||
/// Resolved Overview / What's New docs and their locale variants.
|
||||
docs: PluginDocs,
|
||||
/// The manifest failed to parse: `pkg` is a placeholder.
|
||||
invalid: bool,
|
||||
source: PluginSource,
|
||||
/// Project that owns a project plugin.
|
||||
dev_root: Option<PathBuf>,
|
||||
meta: Mutex<Meta>,
|
||||
/// Serializes starting and stopping this plugin's instance so `runtime`
|
||||
/// stays a leaf lock and never spans Wasm activation or host callbacks.
|
||||
activating: Mutex<()>,
|
||||
/// The running instance, on its own thread.
|
||||
runtime: Mutex<Option<Arc<Actor>>>,
|
||||
/// Event batches handed to the actor and not finished yet.
|
||||
@@ -591,12 +598,14 @@ impl PluginHost {
|
||||
self.plugins.write().insert(
|
||||
pending.id,
|
||||
Arc::new(LoadedPlugin {
|
||||
docs: PluginDocs::from_manifest(&manifest),
|
||||
pkg: Package::new(manifest, dir),
|
||||
icon: None,
|
||||
invalid: false,
|
||||
source: PluginSource::Installed,
|
||||
dev_root: None,
|
||||
meta: Mutex::new(meta),
|
||||
activating: Mutex::new(()),
|
||||
batches: Arc::default(),
|
||||
runtime: Mutex::new(None),
|
||||
}),
|
||||
@@ -948,11 +957,12 @@ impl PluginHost {
|
||||
};
|
||||
let needs_consent =
|
||||
grant.is_none() || publisher.is_none() || signer_changed || !capabilities.iter().all(answered);
|
||||
let docs = plugin_docs(&pkg).unwrap_or_else(|_| PluginDocs::from_manifest(m));
|
||||
Ok(InstallPreview {
|
||||
id: m.id.clone(),
|
||||
name: m.name.clone(),
|
||||
version: m.version.clone(),
|
||||
description: m.description.clone(),
|
||||
description: docs.description,
|
||||
authors: m.authors.clone(),
|
||||
has_code: m.wasm.is_some(),
|
||||
capabilities,
|
||||
@@ -1418,8 +1428,9 @@ impl PluginHost {
|
||||
install::remember_uninstall(&self.plugins_dir, &pending, plugin.dir())?;
|
||||
}
|
||||
// Retain registration for retry, but prevent concurrent on-demand activation.
|
||||
self.shared.block_prompts(id);
|
||||
{
|
||||
let _runtime = plugin.runtime.lock();
|
||||
let _activating = plugin.activating.lock();
|
||||
let mut meta = plugin.meta.lock();
|
||||
meta.uninstalling = true;
|
||||
meta.status = PluginStatus::Disabled;
|
||||
@@ -2204,8 +2215,9 @@ impl PluginHost {
|
||||
return;
|
||||
}
|
||||
let subs = self.shared.subscriptions.lock().clone();
|
||||
let plugins = self.plugins.read();
|
||||
let mut queues = self.queues.lock();
|
||||
let plugins: HashMap<String, Arc<LoadedPlugin>> =
|
||||
self.plugins.read().iter().map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
let mut accepted = Vec::new();
|
||||
for change in changes {
|
||||
let Some(p) = plugins.get(&change.plugin) else { continue };
|
||||
if self.shared.project_of(&change.client).as_deref() != Some(change.project.as_path())
|
||||
@@ -2215,14 +2227,21 @@ impl PluginHost {
|
||||
}
|
||||
let batch =
|
||||
ide_plugin::FilesChanged { project: Some(ide_core::ipc_path::to_ipc(&change.project)), ..change.batch };
|
||||
let queue = queues.entry((change.plugin, Some(change.client))).or_insert_with(|| EventQueue {
|
||||
accepted.push(((change.plugin, Some(change.client)), WorkbenchEvent::WatchedFilesChanged(batch)));
|
||||
}
|
||||
if accepted.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut queues = self.queues.lock();
|
||||
for (key, event) in accepted {
|
||||
let queue = queues.entry(key).or_insert_with(|| EventQueue {
|
||||
since: now,
|
||||
last_event: now,
|
||||
events: Vec::new(),
|
||||
files_source: None,
|
||||
});
|
||||
queue.last_event = now;
|
||||
files_changed::append(&mut queue.events, vec![WorkbenchEvent::WatchedFilesChanged(batch)]);
|
||||
files_changed::append(&mut queue.events, vec![event]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2236,15 +2255,14 @@ impl PluginHost {
|
||||
events: Vec<WorkbenchEvent>,
|
||||
source: Option<files_changed::Source>,
|
||||
) {
|
||||
let mut events = events;
|
||||
files_changed::retain_live(&mut events, source.as_ref());
|
||||
if events.is_empty() {
|
||||
return;
|
||||
}
|
||||
let subs = self.shared.subscriptions.lock().clone();
|
||||
let plugins: Vec<_> = self.plugins.read().values().cloned().collect();
|
||||
let now = Instant::now();
|
||||
let mut queues = self.queues.lock();
|
||||
let mut events = events;
|
||||
files_changed::retain_live(&mut events, source.as_ref());
|
||||
let mut per_plugin = Vec::new();
|
||||
for p in plugins {
|
||||
let wanted: Vec<WorkbenchEvent> = events
|
||||
.iter()
|
||||
@@ -2274,10 +2292,21 @@ impl PluginHost {
|
||||
})
|
||||
.collect();
|
||||
let wanted = Self::filter_path_events(&self.shared, &p, client, &wanted, &subs);
|
||||
if !wanted.is_empty() {
|
||||
per_plugin.push((p.id().to_owned(), wanted));
|
||||
}
|
||||
}
|
||||
if per_plugin.is_empty() {
|
||||
return;
|
||||
}
|
||||
let now = Instant::now();
|
||||
let mut queues = self.queues.lock();
|
||||
for (plugin_id, mut wanted) in per_plugin {
|
||||
files_changed::retain_live(&mut wanted, source.as_ref());
|
||||
if wanted.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let queue = queues.entry((p.id().to_owned(), client.map(str::to_owned))).or_insert_with(|| EventQueue {
|
||||
let queue = queues.entry((plugin_id, client.map(str::to_owned))).or_insert_with(|| EventQueue {
|
||||
since: now,
|
||||
last_event: now,
|
||||
events: Vec::new(),
|
||||
@@ -2324,21 +2353,34 @@ impl PluginHost {
|
||||
#[doc(hidden)]
|
||||
pub fn flush_events_at(&self, now: Instant) {
|
||||
self.queue_watched_changes(now);
|
||||
let running: BTreeSet<String> = self
|
||||
.plugins
|
||||
.read()
|
||||
.values()
|
||||
.filter(|p| p.runtime.lock().as_ref().is_some_and(|a| a.is_alive()))
|
||||
.map(|p| p.id().to_owned())
|
||||
.collect();
|
||||
let debounces: HashMap<String, Duration> = self
|
||||
.shared
|
||||
.subscriptions
|
||||
.lock()
|
||||
.paths
|
||||
.iter()
|
||||
.filter_map(|(id, p)| Some((id.clone(), p.get("files-changed")?.debounce?)))
|
||||
.collect();
|
||||
let due: Vec<(QueueKey, EventQueue)> = {
|
||||
let mut queues = self.queues.lock();
|
||||
let plugins = self.plugins.read();
|
||||
let subs = self.shared.subscriptions.lock();
|
||||
let mut due = Vec::new();
|
||||
let mut keys_to_remove = Vec::new();
|
||||
|
||||
for (key, q) in queues.iter_mut() {
|
||||
let (id, _client) = key;
|
||||
let running = plugins.get(id).is_some_and(|p| p.runtime.lock().as_ref().is_some_and(|a| a.is_alive()));
|
||||
let running = running.contains(id);
|
||||
let has_files = q.events.iter().any(|e| matches!(e, WorkbenchEvent::FilesChanged(_)));
|
||||
let has_scheduled = q.events.iter().any(|e| matches!(e, WorkbenchEvent::Scheduled));
|
||||
// Already debounced by the watcher, like project file changes.
|
||||
let has_watched = q.events.iter().any(|e| matches!(e, WorkbenchEvent::WatchedFilesChanged(_)));
|
||||
let debounce = subs.paths.get(id).and_then(|p| p.get("files-changed")).and_then(|f| f.debounce);
|
||||
let debounce = debounces.get(id).copied();
|
||||
|
||||
let (files_due, files_debouncing) = if has_files {
|
||||
if let Some(debounce) = debounce {
|
||||
@@ -2678,13 +2720,14 @@ impl PluginHost {
|
||||
/// Plugin languages for a remote project's server, with the programs each
|
||||
/// plugin was granted ([`remote::RemotePluginLanguages::sync`]).
|
||||
pub fn remote_languages(&self) -> Vec<remote::RemoteLanguage> {
|
||||
let plugins = self.plugins.read();
|
||||
let subjects: HashMap<String, Subject> =
|
||||
self.plugins.read().iter().map(|(id, p)| (id.clone(), p.subject())).collect();
|
||||
let ledger = self.ledger.lock();
|
||||
self.languages
|
||||
.with_owners()
|
||||
.into_iter()
|
||||
.map(|(plugin, language)| {
|
||||
let grant = plugins.get(&plugin).and_then(|p| ledger.get(&p.subject()).cloned());
|
||||
let grant = subjects.get(&plugin).and_then(|subject| ledger.get(subject).cloned());
|
||||
let granted = ide_language::plugin_point::required_capabilities(&language)
|
||||
.into_iter()
|
||||
.filter(|cap| grant.as_ref().is_some_and(|g| g.confirmed && g.has(cap)))
|
||||
@@ -2721,6 +2764,7 @@ impl PluginHost {
|
||||
.filter(|w| !dir.join(w).is_file())
|
||||
.map(|w| format!("{} is missing; build the plugin first", w.display())),
|
||||
};
|
||||
let docs = plugin_docs(&pkg).unwrap_or_else(|_| PluginDocs::from_manifest(&m));
|
||||
out.push(CatalogPlugin {
|
||||
has_code: m.wasm.is_some(),
|
||||
capabilities: m
|
||||
@@ -2732,10 +2776,12 @@ impl PluginHost {
|
||||
id: m.id,
|
||||
name: m.name,
|
||||
version: m.version,
|
||||
description: m.description,
|
||||
description: docs.description,
|
||||
description_locales: docs.description_locales,
|
||||
authors: m.authors,
|
||||
homepage: m.homepage,
|
||||
change_notes: m.change_notes,
|
||||
change_notes: docs.change_notes,
|
||||
change_notes_locales: docs.change_notes_locales,
|
||||
icon: plugin_icon(&pkg).ok().flatten(),
|
||||
path: dir.into(),
|
||||
problem,
|
||||
@@ -2747,8 +2793,13 @@ 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() {
|
||||
let (ids, actors): (Vec<String>, Vec<_>) = {
|
||||
let plugins = self.plugins.read();
|
||||
let ids = plugins.keys().cloned().collect();
|
||||
let actors = plugins.values().filter_map(|p| p.runtime.lock().take()).collect();
|
||||
(ids, actors)
|
||||
};
|
||||
for id in &ids {
|
||||
self.shared.block_prompts(id);
|
||||
self.stop_web_ptys(id);
|
||||
}
|
||||
@@ -2839,15 +2890,16 @@ 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.
|
||||
/// Validates the manifest's icon, docs and every declaration of `pkg`; the
|
||||
/// icon and doc files join the package files the declarations reference.
|
||||
fn prepare(&self, pkg: &Package) -> Result<ide_extension::PreparedSet, String> {
|
||||
plugin_icon(pkg)?;
|
||||
let docs = plugin_docs(pkg)?;
|
||||
let mut set = self.registry.prepare(pkg)?;
|
||||
check_setting_grants(pkg)?;
|
||||
for icon in [&pkg.manifest.icon, &pkg.manifest.icon_dark].into_iter().flatten() {
|
||||
if !set.files.contains(icon) {
|
||||
set.files.push(icon.clone());
|
||||
for file in [&pkg.manifest.icon, &pkg.manifest.icon_dark].into_iter().flatten().chain(&docs.files) {
|
||||
if !set.files.contains(file) {
|
||||
set.files.push(file.clone());
|
||||
}
|
||||
}
|
||||
Ok(set)
|
||||
@@ -2914,13 +2966,16 @@ impl PluginHost {
|
||||
// Installed copies don't change: their validated UI declarations are indexed.
|
||||
pkg = pkg.with_digest(digest.trim());
|
||||
}
|
||||
let docs = plugin_docs(&pkg).unwrap_or_else(|_| PluginDocs::from_manifest(&pkg.manifest));
|
||||
let plugin = Arc::new(LoadedPlugin {
|
||||
icon: plugin_icon(&pkg).ok().flatten(),
|
||||
docs,
|
||||
pkg,
|
||||
invalid,
|
||||
source,
|
||||
dev_root,
|
||||
meta: Mutex::new(Meta::new()),
|
||||
activating: Mutex::new(()),
|
||||
batches: Arc::default(),
|
||||
runtime: Mutex::new(None),
|
||||
});
|
||||
@@ -3045,99 +3100,111 @@ impl PluginHost {
|
||||
/// The plugin's running instance, instantiating and activating its code
|
||||
/// first if needed. Returns whether it was activated now.
|
||||
fn ensure_active(&self, plugin: &Arc<LoadedPlugin>, client: Option<&str>) -> IdeResult<(Arc<Actor>, bool)> {
|
||||
let mut runtime = plugin.runtime.lock();
|
||||
self.check_not_uninstalling(plugin)?;
|
||||
if let Some(actor) = runtime.as_ref() {
|
||||
if actor.is_alive() {
|
||||
return Ok((actor.clone(), false));
|
||||
for _ in 0..2 {
|
||||
self.check_not_uninstalling(plugin)?;
|
||||
let current = plugin.runtime.lock().clone();
|
||||
if let Some(actor) = current {
|
||||
if actor.is_alive() {
|
||||
return Ok((actor, false));
|
||||
}
|
||||
// Crashed while nobody was waiting for it.
|
||||
self.reap(plugin, &actor, client);
|
||||
}
|
||||
// Crashed while nobody was waiting for it.
|
||||
let actor = actor.clone();
|
||||
drop(runtime);
|
||||
self.reap(plugin, &actor, client);
|
||||
runtime = plugin.runtime.lock();
|
||||
if let Some(actor) = runtime.as_ref().filter(|a| a.is_alive()) {
|
||||
return Ok((actor.clone(), false));
|
||||
let activating = plugin.activating.lock();
|
||||
self.check_not_uninstalling(plugin)?;
|
||||
if !self.plugins.read().get(plugin.id()).is_some_and(|p| Arc::ptr_eq(p, plugin)) {
|
||||
return Err(IdeError::not_found(format!("no plugin {:?}", plugin.id())));
|
||||
}
|
||||
}
|
||||
if plugin.status() != PluginStatus::Inactive {
|
||||
return Err(IdeError::unavailable(format!("plugin {:?} cannot be activated", plugin.id())));
|
||||
}
|
||||
if let Some(wait) = plugin.meta.lock().retry_at.map(|at| at.saturating_duration_since(Instant::now()))
|
||||
&& !wait.is_zero()
|
||||
{
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"plugin {:?} crashed and restarts in {:.1}s",
|
||||
plugin.id(),
|
||||
wait.as_secs_f64()
|
||||
)));
|
||||
}
|
||||
let Some(wasm) = plugin.manifest().wasm.clone() else {
|
||||
return Err(IdeError::unavailable(format!("plugin {:?} has no code", plugin.id())));
|
||||
};
|
||||
let started = Instant::now();
|
||||
let granted = plugin.meta.lock().granted.clone();
|
||||
let api: Arc<dyn HostApi> = Arc::new(api::PluginApi { pkg: plugin.pkg.clone(), shared: self.shared.clone() });
|
||||
let setup = RuntimeSetup {
|
||||
plugin_id: plugin.id().to_owned(),
|
||||
version: plugin.manifest().version.clone(),
|
||||
granted,
|
||||
subject: plugin.subject(),
|
||||
host: api,
|
||||
limits: self.limits,
|
||||
};
|
||||
let instance = self
|
||||
.engine
|
||||
.compile_cached(&plugin.dir().join(wasm), &self.component_cache())
|
||||
.and_then(|component| Runtime::instantiate(&self.engine, &component, setup));
|
||||
let mut rt = match instance {
|
||||
Ok(rt) => rt,
|
||||
Err(e) => {
|
||||
drop(runtime);
|
||||
let current = plugin.runtime.lock().clone();
|
||||
if let Some(actor) = current {
|
||||
if actor.is_alive() {
|
||||
return Ok((actor, false));
|
||||
}
|
||||
drop(activating);
|
||||
self.reap(plugin, &actor, client);
|
||||
continue;
|
||||
}
|
||||
if plugin.status() != PluginStatus::Inactive {
|
||||
return Err(IdeError::unavailable(format!("plugin {:?} cannot be activated", plugin.id())));
|
||||
}
|
||||
if let Some(wait) = plugin.meta.lock().retry_at.map(|at| at.saturating_duration_since(Instant::now()))
|
||||
&& !wait.is_zero()
|
||||
{
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"plugin {:?} crashed and restarts in {:.1}s",
|
||||
plugin.id(),
|
||||
wait.as_secs_f64()
|
||||
)));
|
||||
}
|
||||
let Some(wasm) = plugin.manifest().wasm.clone() else {
|
||||
return Err(IdeError::unavailable(format!("plugin {:?} has no code", plugin.id())));
|
||||
};
|
||||
let started = Instant::now();
|
||||
let granted = plugin.meta.lock().granted.clone();
|
||||
let api: Arc<dyn HostApi> =
|
||||
Arc::new(api::PluginApi { pkg: plugin.pkg.clone(), shared: self.shared.clone() });
|
||||
let setup = RuntimeSetup {
|
||||
plugin_id: plugin.id().to_owned(),
|
||||
version: plugin.manifest().version.clone(),
|
||||
granted,
|
||||
subject: plugin.subject(),
|
||||
host: api,
|
||||
limits: self.limits,
|
||||
};
|
||||
let instance = self
|
||||
.engine
|
||||
.compile_cached(&plugin.dir().join(wasm), &self.component_cache())
|
||||
.and_then(|component| Runtime::instantiate(&self.engine, &component, setup));
|
||||
let mut rt = match instance {
|
||||
Ok(rt) => rt,
|
||||
Err(e) => {
|
||||
drop(activating);
|
||||
if let Some(message) = self.roll_back_failed_update(plugin, &e, client) {
|
||||
return Err(IdeError::unavailable(message));
|
||||
}
|
||||
self.fail(plugin, &e, client);
|
||||
return Err(IdeError::internal(format!("plugin {:?} {e}", plugin.id())));
|
||||
}
|
||||
};
|
||||
plugin.meta.lock().has_run_target_validation = rt.has_run_target_validation();
|
||||
let crash = match rt.activate() {
|
||||
Ok(_) => None,
|
||||
Err(CallError::Trap(e)) => Some(format!("activation {e}")),
|
||||
Err(CallError::Guest(e)) => {
|
||||
drop(activating);
|
||||
let e = format!("activation failed: {e}");
|
||||
if let Some(message) = self.roll_back_failed_update(plugin, &e, client) {
|
||||
return Err(IdeError::unavailable(message));
|
||||
}
|
||||
self.fail(plugin, &e, client);
|
||||
return Err(IdeError::internal(format!("plugin {:?} {e}", plugin.id())));
|
||||
}
|
||||
};
|
||||
if let Some(e) = crash {
|
||||
drop(activating);
|
||||
if let Some(message) = self.roll_back_failed_update(plugin, &e, client) {
|
||||
return Err(IdeError::unavailable(message));
|
||||
}
|
||||
self.fail(plugin, &e, client);
|
||||
self.crashed(plugin, &e, client);
|
||||
return Err(IdeError::internal(format!("plugin {:?} {e}", plugin.id())));
|
||||
}
|
||||
};
|
||||
plugin.meta.lock().has_run_target_validation = rt.has_run_target_validation();
|
||||
let crash = match rt.activate() {
|
||||
Ok(_) => None,
|
||||
Err(CallError::Trap(e)) => Some(format!("activation {e}")),
|
||||
Err(CallError::Guest(e)) => {
|
||||
drop(runtime);
|
||||
let e = format!("activation failed: {e}");
|
||||
if let Some(message) = self.roll_back_failed_update(plugin, &e, client) {
|
||||
return Err(IdeError::unavailable(message));
|
||||
}
|
||||
self.fail(plugin, &e, client);
|
||||
return Err(IdeError::internal(format!("plugin {:?} {e}", plugin.id())));
|
||||
}
|
||||
};
|
||||
if let Some(e) = crash {
|
||||
drop(runtime);
|
||||
if let Some(message) = self.roll_back_failed_update(plugin, &e, client) {
|
||||
return Err(IdeError::unavailable(message));
|
||||
}
|
||||
self.crashed(plugin, &e, client);
|
||||
return Err(IdeError::internal(format!("plugin {:?} {e}", plugin.id())));
|
||||
// An update's first start: confirmed.
|
||||
self.updates.lock().remove(plugin.id());
|
||||
let has_syntax = rt.has_syntax();
|
||||
let actor = match Actor::spawn(plugin.id(), rt) {
|
||||
Ok(a) => Arc::new(a),
|
||||
Err(e) => return Err(IdeError::internal(format!("plugin {:?}: {e}", plugin.id()))),
|
||||
};
|
||||
*plugin.runtime.lock() = Some(actor.clone());
|
||||
self.shared.allow_prompts(plugin.id());
|
||||
let mut meta = plugin.meta.lock();
|
||||
meta.status = PluginStatus::Active;
|
||||
meta.has_syntax = has_syntax;
|
||||
meta.stats.activations += 1;
|
||||
meta.stats.activation_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
return Ok((actor, true));
|
||||
}
|
||||
// An update's first start: confirmed.
|
||||
self.updates.lock().remove(plugin.id());
|
||||
let has_syntax = rt.has_syntax();
|
||||
let actor = match Actor::spawn(plugin.id(), rt) {
|
||||
Ok(a) => Arc::new(a),
|
||||
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;
|
||||
meta.stats.activations += 1;
|
||||
meta.stats.activation_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
Ok((actor, true))
|
||||
Err(IdeError::unavailable(format!("plugin {:?} stopped while activating; try again", plugin.id())))
|
||||
}
|
||||
|
||||
fn record_call(&self, plugin: &LoadedPlugin, elapsed: Duration, ok: bool, healthy: bool) {
|
||||
@@ -3213,6 +3280,9 @@ impl PluginHost {
|
||||
|
||||
/// Ends an idle instance; the plugin activates again on its next event.
|
||||
fn reclaim(&self, plugin: &LoadedPlugin, actor: &Arc<Actor>) -> bool {
|
||||
let Some(_activating) = plugin.activating.try_lock() else {
|
||||
return false;
|
||||
};
|
||||
{
|
||||
let mut runtime = plugin.runtime.lock();
|
||||
if !runtime.as_ref().is_some_and(|r| Arc::ptr_eq(r, actor)) || actor.is_busy() {
|
||||
@@ -3238,7 +3308,17 @@ impl PluginHost {
|
||||
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() {
|
||||
let actor = {
|
||||
let _activating = plugin.activating.lock();
|
||||
self.shared.block_prompts(plugin.id());
|
||||
let mut meta = plugin.meta.lock();
|
||||
if matches!(meta.status, PluginStatus::Active | PluginStatus::Inactive) {
|
||||
meta.status = PluginStatus::Disabled;
|
||||
}
|
||||
drop(meta);
|
||||
plugin.runtime.lock().take()
|
||||
};
|
||||
if let Some(actor) = actor {
|
||||
actor.stop(true);
|
||||
}
|
||||
self.registry.dispose_plugin(plugin.id());
|
||||
@@ -3503,10 +3583,12 @@ impl PluginHost {
|
||||
id: m.id.clone(),
|
||||
name: m.name.clone(),
|
||||
version: m.version.clone(),
|
||||
description: m.description.clone(),
|
||||
description: p.docs.description.clone(),
|
||||
description_locales: p.docs.description_locales.clone(),
|
||||
authors: m.authors.clone(),
|
||||
homepage: m.homepage.clone(),
|
||||
change_notes: m.change_notes.clone(),
|
||||
change_notes: p.docs.change_notes.clone(),
|
||||
change_notes_locales: p.docs.change_notes_locales.clone(),
|
||||
icon: p.icon.clone(),
|
||||
java_agent: self.java_agents.for_plugin(&m.id).map(|agent| {
|
||||
let pin = self
|
||||
@@ -3692,10 +3774,12 @@ fn placeholder_manifest(dir: &Path) -> Manifest {
|
||||
name,
|
||||
version: "0.0.0".into(),
|
||||
description: String::new(),
|
||||
description_file: None,
|
||||
authors: Vec::new(),
|
||||
homepage: None,
|
||||
license: None,
|
||||
change_notes: None,
|
||||
change_notes_file: None,
|
||||
declared_categories: Vec::new(),
|
||||
icon: None,
|
||||
icon_dark: None,
|
||||
@@ -3843,4 +3927,94 @@ mod tests {
|
||||
assert!(glob_match("src/**", "src/a/b"));
|
||||
assert!(glob_match("a?c", "abc") && !glob_match("a?c", "a/c"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_dispatch_does_not_deadlock_with_concurrent_activation() {
|
||||
struct TestWorkspace(PathBuf);
|
||||
impl PluginWorkspace for TestWorkspace {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
vec![self.0.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], _: bool) -> Result<u64, HostError> {
|
||||
Err(HostError::Failed("unused".into()))
|
||||
}
|
||||
fn trusted(&self, _: &Path) -> bool {
|
||||
true
|
||||
}
|
||||
fn project_of(&self, _: &str) -> Option<PathBuf> {
|
||||
Some(self.0.clone())
|
||||
}
|
||||
fn publish_diagnostics(&self, _: &str, _: &Path, _: Vec<ide_core::Diagnostic>) -> Result<(), HostError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::create_dir_all(root.join("config")).unwrap();
|
||||
let yaml = root.join("config/app.yaml");
|
||||
std::fs::write(&yaml, "a: 1\n").unwrap();
|
||||
|
||||
let host = Arc::new(
|
||||
PluginHost::new(root.join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(),
|
||||
);
|
||||
host.set_workspace(Some(Arc::new(TestWorkspace(root.clone()))));
|
||||
let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/path-events");
|
||||
host.install_from_dir(&fixture, &Consent::all()).unwrap();
|
||||
|
||||
let plugin = host.get("test.path-events").unwrap();
|
||||
let (actor, _) = host.ensure_active(&plugin, Some("main")).unwrap();
|
||||
assert!(host.reclaim(&plugin, &actor));
|
||||
|
||||
let (done_tx, done_rx) = std::sync::mpsc::channel();
|
||||
let runner_host = host.clone();
|
||||
std::thread::spawn(move || {
|
||||
let file = ide_core::ipc_path::to_ipc(&yaml);
|
||||
for _ in 0..20 {
|
||||
runner_host.post_window_events("main", vec![WorkbenchEvent::FileOpened(file.clone())], None);
|
||||
let barrier = std::sync::Barrier::new(3);
|
||||
std::thread::scope(|s| {
|
||||
s.spawn(|| {
|
||||
barrier.wait();
|
||||
let (actor, _) = runner_host.ensure_active(&plugin, Some("main")).unwrap();
|
||||
let _ = actor;
|
||||
});
|
||||
s.spawn(|| {
|
||||
barrier.wait();
|
||||
for _ in 0..50 {
|
||||
runner_host.flush_events();
|
||||
std::thread::yield_now();
|
||||
}
|
||||
});
|
||||
s.spawn(|| {
|
||||
barrier.wait();
|
||||
for _ in 0..20 {
|
||||
runner_host.post_window_events(
|
||||
"main",
|
||||
vec![WorkbenchEvent::FileOpened(file.clone())],
|
||||
None,
|
||||
);
|
||||
std::thread::yield_now();
|
||||
}
|
||||
});
|
||||
});
|
||||
assert!(runner_host.wait_events(Duration::from_secs(5)));
|
||||
let actor = plugin.runtime.lock().clone();
|
||||
if let Some(actor) = actor {
|
||||
let _ = runner_host.reclaim(&plugin, &actor);
|
||||
}
|
||||
}
|
||||
let _ = done_tx.send(());
|
||||
});
|
||||
|
||||
done_rx
|
||||
.recv_timeout(Duration::from_secs(10))
|
||||
.expect("concurrent ensure_active, flush_events, and post_window_events deadlocked");
|
||||
}
|
||||
}
|
||||
@@ -97,9 +97,13 @@ pub struct PluginInfo {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub description: String,
|
||||
#[serde(default)]
|
||||
pub description_locales: BTreeMap<String, String>,
|
||||
pub authors: Vec<String>,
|
||||
pub homepage: Option<String>,
|
||||
pub change_notes: Option<String>,
|
||||
#[serde(default)]
|
||||
pub change_notes_locales: BTreeMap<String, String>,
|
||||
pub icon: Option<PluginIcon>,
|
||||
/// The Java agent this plugin declares, and whether it is still approved.
|
||||
pub java_agent: Option<PluginJavaAgent>,
|
||||
@@ -207,9 +211,13 @@ pub struct CatalogPlugin {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub description: String,
|
||||
#[serde(default)]
|
||||
pub description_locales: BTreeMap<String, String>,
|
||||
pub authors: Vec<String>,
|
||||
pub homepage: Option<String>,
|
||||
pub change_notes: Option<String>,
|
||||
#[serde(default)]
|
||||
pub change_notes_locales: BTreeMap<String, String>,
|
||||
pub icon: Option<PluginIcon>,
|
||||
/// Package directory; install with `install_from_dir(path)`.
|
||||
pub path: ide_core::IpcPath,
|
||||
|
||||
@@ -141,6 +141,8 @@ impl Host {
|
||||
self.environment.direnv_opened(&root, &sink);
|
||||
}
|
||||
let settings = SettingsStore::load(&self.config_dir, Some(&root));
|
||||
// Builds may have changed while no watcher was looking.
|
||||
ide_build::gradle::forget_build_dirs(&root);
|
||||
let detected_roots = Arc::new(RwLock::new(ide_workspace::roots::detect(&root)));
|
||||
let member_excludes: MemberExcludes = Arc::new(RwLock::new(member_excludes(&settings, &root)));
|
||||
let excludes = exclude_globs(&root, &settings.effective(), &detected_roots.read(), &member_excludes.read());
|
||||
@@ -212,6 +214,7 @@ impl Host {
|
||||
let root = member.as_ref().unwrap_or(window_root);
|
||||
ide_sdk::apply::server_launch_overrides(cfg, &effective);
|
||||
ide_sdk::apply::configure_server(cfg, root, server_root, &effective);
|
||||
ide_sdk::json_schemas::configure(cfg, root, &effective.json_schemas);
|
||||
crate::ts_code_style::configure(cfg, server_root, &effective);
|
||||
ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir);
|
||||
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
|
||||
@@ -504,6 +507,7 @@ impl Host {
|
||||
// Build files / conventional folders changed: re-detect roots.
|
||||
let touched = changed.iter().chain(&batch.removed).filter_map(|p| p.strip_prefix(&root).ok());
|
||||
if touched.into_iter().any(ide_workspace::roots::affects_roots) {
|
||||
ide_build::gradle::forget_build_dirs(&root);
|
||||
let fresh = ide_workspace::roots::detect(&root);
|
||||
if *detected_roots.read() != fresh {
|
||||
// Detected excluded folders (`target`, `build`) leave the index too.
|
||||
@@ -837,6 +841,13 @@ impl Host {
|
||||
let settings = settings.clone();
|
||||
agents.set_new_task_approvals_hook(Arc::new(move || settings.effective().agents.new_task_approvals));
|
||||
}
|
||||
{
|
||||
let settings = settings.clone();
|
||||
agents.set_recovery_settings_hook(Arc::new(move || {
|
||||
let effective = settings.effective();
|
||||
(effective.agents.network_retry_window, effective.agents.resume_interrupted)
|
||||
}));
|
||||
}
|
||||
let approvals = self.mcp_approvals.clone();
|
||||
let secrets = self.agent_secrets.clone();
|
||||
let root = root.to_path_buf();
|
||||
|
||||
@@ -403,7 +403,7 @@ pub fn register(dispatcher: &mut Dispatcher, shell: Arc<WebShellState>) {
|
||||
("wsl_resolve", Always),
|
||||
("remote_current", Always),
|
||||
("plugin_market_url", Always),
|
||||
("clipboard_text", Trusted),
|
||||
("clipboard_text", Always),
|
||||
("clipboard_image", Always),
|
||||
] {
|
||||
dispatcher.add(null_opt, trust, |_| async move { Ok(Value::Null) });
|
||||
|
||||
@@ -169,6 +169,7 @@ fn signed(
|
||||
name: "Hello".into(),
|
||||
version: version.into(),
|
||||
description: String::new(),
|
||||
description_locales: Default::default(),
|
||||
authors: vec![],
|
||||
publisher: publisher.into(),
|
||||
download: out.file_name().unwrap().to_string_lossy().into_owned(),
|
||||
@@ -179,6 +180,7 @@ fn signed(
|
||||
icon: None,
|
||||
homepage: None,
|
||||
notes: None,
|
||||
notes_locales: Default::default(),
|
||||
downloads: None,
|
||||
featured: false,
|
||||
suggest: vec![],
|
||||
|
||||
@@ -116,7 +116,7 @@ async fn docker_targets_run_through_the_docker_cli() {
|
||||
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());
|
||||
debug.extras.params.insert("targetDebug".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];
|
||||
|
||||
@@ -240,7 +240,7 @@ async fn debugs_python_in_a_container() {
|
||||
|
||||
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());
|
||||
debug.extras.params.insert("targetDebug".into(), "true".into());
|
||||
let (_, out) = start(&host, debug).await;
|
||||
let mut ready = None;
|
||||
for _ in 0..1200 {
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
//! pytest fixture Find Usages and Rename (`nav_pytest_fixture_usages` / `_rename` / `_target`)
|
||||
//! on a project on disk: which files are searched, overrides left out, `pytest_plugins`
|
||||
//! modules, `python_files`, body reads and name clashes.
|
||||
|
||||
mod common;
|
||||
|
||||
use ide_core::{FileEdit, Pos};
|
||||
use ide_host::{Host, ops};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const WINDOW: &str = "main";
|
||||
|
||||
struct Opened {
|
||||
host: Arc<Host>,
|
||||
root: PathBuf,
|
||||
_tmp: tempfile::TempDir,
|
||||
}
|
||||
|
||||
const CONFTEST: &str = "\
|
||||
import pytest
|
||||
|
||||
pytest_plugins = [\"tests.fixtures\"]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tasks():
|
||||
return []
|
||||
|
||||
|
||||
@pytest.fixture(name=\"sample\")
|
||||
def sample_tasks(tasks):
|
||||
return tasks
|
||||
";
|
||||
|
||||
const FIXTURES: &str = "\
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db():
|
||||
return {}
|
||||
";
|
||||
|
||||
const TEST_A: &str = "\
|
||||
import pytest
|
||||
|
||||
|
||||
class TestOverride:
|
||||
@pytest.fixture
|
||||
def tasks(self, tasks):
|
||||
return tasks + [1]
|
||||
|
||||
def test_own(self, tasks):
|
||||
assert tasks
|
||||
|
||||
|
||||
def test_plain(tasks, db):
|
||||
done = [tasks for tasks in range(2)]
|
||||
assert tasks == [] and db == {} and done
|
||||
|
||||
|
||||
@pytest.mark.usefixtures(\"sample\")
|
||||
def test_sample(sample, request):
|
||||
assert request.getfixturevalue(\"tasks\") is sample
|
||||
|
||||
|
||||
class TestDb:
|
||||
@pytest.fixture
|
||||
def extra(self):
|
||||
return 0
|
||||
|
||||
def test_db(self, db):
|
||||
assert db == {}
|
||||
";
|
||||
|
||||
/// A module a conftest imports a fixture from (no `pytest_plugins`).
|
||||
const SHARED: &str = "\
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def item():
|
||||
return 1
|
||||
";
|
||||
|
||||
const SUB_CONFTEST: &str = "\
|
||||
import pytest
|
||||
from tests.shared import item
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def seed():
|
||||
return 0
|
||||
";
|
||||
|
||||
const TEST_C: &str = "\
|
||||
def test_c(item):
|
||||
assert item == 1
|
||||
|
||||
|
||||
def test_d(tasks):
|
||||
assert tasks == []
|
||||
";
|
||||
|
||||
const CHECK_B: &str = "\
|
||||
def test_b(db):
|
||||
assert db == {}
|
||||
";
|
||||
|
||||
async fn open() -> Opened {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("proj");
|
||||
let tests = root.join("tests");
|
||||
std::fs::create_dir_all(&tests).unwrap();
|
||||
std::fs::write(root.join("pytest.ini"), "[pytest]\npython_files = test_*.py check_*.py\n").unwrap();
|
||||
std::fs::write(tests.join("__init__.py"), "").unwrap();
|
||||
std::fs::write(tests.join("conftest.py"), CONFTEST).unwrap();
|
||||
std::fs::write(tests.join("fixtures.py"), FIXTURES).unwrap();
|
||||
std::fs::write(tests.join("test_a.py"), TEST_A).unwrap();
|
||||
std::fs::write(tests.join("check_b.py"), CHECK_B).unwrap();
|
||||
// Not collected by pytest: its `db` parameter is no fixture use.
|
||||
std::fs::write(tests.join("helpers.py"), "def helper(db):\n return db\n").unwrap();
|
||||
std::fs::write(tests.join("shared.py"), SHARED).unwrap();
|
||||
std::fs::create_dir_all(tests.join("sub")).unwrap();
|
||||
std::fs::write(tests.join("sub/__init__.py"), "").unwrap();
|
||||
std::fs::write(tests.join("sub/conftest.py"), SUB_CONFTEST).unwrap();
|
||||
std::fs::write(tests.join("sub/test_c.py"), TEST_C).unwrap();
|
||||
|
||||
let app = tmp.path().join("app");
|
||||
let host = Arc::new(Host::new(common::host_config(&app)));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
ops::project::open(&host, WINDOW, &root).await.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
let s = ops::nav::index_status(&host, WINDOW).unwrap();
|
||||
if !s.indexing && s.files > 0 {
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "indexing timed out; status: {s:?}");
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
Opened { host, root, _tmp: tmp }
|
||||
}
|
||||
|
||||
/// 0-based line and UTF-16 column of the first `needle` in `text`, `skip` characters in.
|
||||
fn pos_of(text: &str, needle: &str, skip: usize) -> Pos {
|
||||
let at = text.find(needle).unwrap_or_else(|| panic!("{needle:?} not found")) + skip;
|
||||
let line = text[..at].matches('\n').count();
|
||||
let col = at - text[..at].rfind('\n').map_or(0, |i| i + 1);
|
||||
Pos::new(line as u32, col as u32)
|
||||
}
|
||||
|
||||
fn short(root: &Path, l: &ide_core::Location) -> String {
|
||||
let path = l.path.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
|
||||
format!("{path}:{}", l.range.start.line + 1)
|
||||
}
|
||||
|
||||
fn request() -> ide_core::RequestId {
|
||||
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
|
||||
ide_core::RequestId(NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn finds_usages_where_pytest_would_inject_the_fixture() {
|
||||
let p = open().await;
|
||||
let conftest = ops::doc::doc_open(&p.host, WINDOW, p.root.join("tests/conftest.py")).await.unwrap().id;
|
||||
|
||||
// `tasks` from conftest.py: sample_tasks's parameter, the class fixture's overriding
|
||||
// parameter, test_plain and getfixturevalue; not test_own, which gets the class fixture.
|
||||
let found =
|
||||
ops::nav::nav_pytest_fixture_usages(&p.host, WINDOW, conftest, pos_of(CONFTEST, "def tasks", 4), request())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let mut usages: Vec<String> = found.usages.iter().map(|l| short(&p.root, l)).collect();
|
||||
usages.sort();
|
||||
assert_eq!(
|
||||
usages,
|
||||
[
|
||||
"tests/conftest.py:12",
|
||||
"tests/sub/test_c.py:5",
|
||||
"tests/test_a.py:13",
|
||||
"tests/test_a.py:20",
|
||||
"tests/test_a.py:6"
|
||||
]
|
||||
);
|
||||
|
||||
// `db` lives in a module `pytest_plugins` loads: the whole project is searched, including a
|
||||
// `python_files = check_*.py` module, but not helpers.py, which pytest doesn't collect.
|
||||
let fixtures = ops::doc::doc_open(&p.host, WINDOW, p.root.join("tests/fixtures.py")).await.unwrap().id;
|
||||
let found =
|
||||
ops::nav::nav_pytest_fixture_usages(&p.host, WINDOW, fixtures, pos_of(FIXTURES, "def db", 4), request())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let mut usages: Vec<String> = found.usages.iter().map(|l| short(&p.root, l)).collect();
|
||||
usages.sort();
|
||||
assert_eq!(usages, ["tests/check_b.py:1", "tests/test_a.py:13", "tests/test_a.py:28"]);
|
||||
|
||||
// `item` reaches tests/sub through the conftest's `from tests.shared import item`.
|
||||
let test_c = ops::doc::doc_open(&p.host, WINDOW, p.root.join("tests/sub/test_c.py")).await.unwrap().id;
|
||||
let at = ops::nav::nav_pytest_fixtures(&p.host, WINDOW, test_c, pos_of(TEST_C, "item", 0)).await.unwrap();
|
||||
let definition = at.reference.and_then(|r| r.definition).expect("item resolves");
|
||||
assert_eq!(short(&p.root, &definition), "tests/shared.py:5");
|
||||
let shared = ops::doc::doc_open(&p.host, WINDOW, p.root.join("tests/shared.py")).await.unwrap().id;
|
||||
let found = ops::nav::nav_pytest_fixture_usages(&p.host, WINDOW, shared, pos_of(SHARED, "def item", 4), request())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let usages: Vec<String> = found.usages.iter().map(|l| short(&p.root, l)).collect();
|
||||
assert_eq!(usages, ["tests/sub/test_c.py:1"]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn renames_the_fixture_its_requests_and_their_reads() {
|
||||
let p = open().await;
|
||||
let test_a = ops::doc::doc_open(&p.host, WINDOW, p.root.join("tests/test_a.py")).await.unwrap().id;
|
||||
|
||||
// Rename starts from a read in a body too: `tasks` in test_plain's assert.
|
||||
let at = pos_of(TEST_A, "assert tasks ==", 7);
|
||||
let target = ops::nav::nav_pytest_fixture_target(&p.host, WINDOW, test_a, at).await.unwrap().unwrap();
|
||||
assert_eq!((target.name.as_str(), short(&p.root, &target.definition)), ("tasks", "tests/conftest.py:7".into()));
|
||||
assert!(target.in_project && target.function_name);
|
||||
|
||||
// A clash with another parameter of a requesting function changes nothing.
|
||||
let clash = ops::nav::nav_pytest_fixture_rename(&p.host, WINDOW, test_a, at, "db".into(), request()).await.unwrap();
|
||||
assert!(clash.edit.files.is_empty());
|
||||
assert_eq!(short(&p.root, &clash.clash.unwrap()), "tests/test_a.py:13");
|
||||
// A name test_plain's body already uses (`done`) would be shadowed.
|
||||
let clash =
|
||||
ops::nav::nav_pytest_fixture_rename(&p.host, WINDOW, test_a, at, "done".into(), request()).await.unwrap();
|
||||
assert_eq!(short(&p.root, &clash.clash.unwrap()), "tests/test_a.py:13");
|
||||
// test_d in tests/sub would get sub/conftest.py's `seed` instead.
|
||||
let clash =
|
||||
ops::nav::nav_pytest_fixture_rename(&p.host, WINDOW, test_a, at, "seed".into(), request()).await.unwrap();
|
||||
assert_eq!(short(&p.root, &clash.clash.unwrap()), "tests/sub/conftest.py:6");
|
||||
// TestDb.test_db would get the class's own `extra` instead of `db`.
|
||||
let db = pos_of(TEST_A, "def test_db(self, db)", 18);
|
||||
let clash =
|
||||
ops::nav::nav_pytest_fixture_rename(&p.host, WINDOW, test_a, db, "extra".into(), request()).await.unwrap();
|
||||
assert_eq!(short(&p.root, &clash.clash.unwrap()), "tests/test_a.py:25");
|
||||
|
||||
let renamed =
|
||||
ops::nav::nav_pytest_fixture_rename(&p.host, WINDOW, test_a, at, "todo".into(), request()).await.unwrap();
|
||||
assert!(renamed.clash.is_none());
|
||||
let lines = |file: &str| -> Vec<u32> {
|
||||
let edits = renamed.edit.files.iter().find_map(|f| match f {
|
||||
FileEdit::Edit { path, edits, .. } if path.ends_with(file) => Some(edits.clone()),
|
||||
_ => None,
|
||||
});
|
||||
let mut lines: Vec<u32> = edits.unwrap_or_default().iter().map(|e| e.range.start.line + 1).collect();
|
||||
lines.sort();
|
||||
lines
|
||||
};
|
||||
// conftest.py: the definition, sample_tasks's parameter and its read.
|
||||
assert_eq!(lines("tests/conftest.py"), [7, 12, 13]);
|
||||
assert_eq!(lines("tests/sub/test_c.py"), [5, 6]);
|
||||
// test_a.py: the overriding parameter and its read, test_plain's parameter and its read
|
||||
// (not the comprehension's own `tasks`), and the getfixturevalue string; not test_own's.
|
||||
assert_eq!(lines("tests/test_a.py"), [6, 7, 13, 15, 20]);
|
||||
}
|
||||
@@ -941,3 +941,156 @@ async fn compose_service_survives_disconnect_and_is_removed_on_stop() {
|
||||
assert!(!guard.0.exists());
|
||||
assert!(compose_ids(true).await.is_empty(), "the stop command did not remove the compose service");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_daemon_preserves_agent_across_disconnect_and_records_backend_stop_for_resume() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("home");
|
||||
let base = tmp.path().join("server");
|
||||
let project = home.join("demo");
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
let agents_dir = base.join("config/agents");
|
||||
std::fs::create_dir_all(&agents_dir).unwrap();
|
||||
|
||||
// Custom ACP agent: blocks on "hold" while disconnected, finishes immediately on continuation prompt.
|
||||
let agent_script = tmp.path().join("mock-acp-agent.sh");
|
||||
let script = r#"#!/bin/sh
|
||||
while IFS= read -r line; do
|
||||
id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p')
|
||||
case "$line" in
|
||||
*'"initialize"'*)
|
||||
printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true}}}\n' "$id"
|
||||
;;
|
||||
*'"session/new"'*)
|
||||
printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"remote-s1"}}\n' "$id"
|
||||
;;
|
||||
*'"session/load"'*)
|
||||
printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
|
||||
;;
|
||||
*'"session/prompt"'*)
|
||||
case "$line" in
|
||||
*'"hold"'*)
|
||||
sleep 30
|
||||
printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"
|
||||
;;
|
||||
*)
|
||||
printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"remote-s1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"remote resumed"}}}}\n'
|
||||
printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
esac
|
||||
done
|
||||
"#;
|
||||
std::fs::write(&agent_script, script).unwrap();
|
||||
std::fs::set_permissions(&agent_script, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
std::fs::write(
|
||||
agents_dir.join("mock.toml"),
|
||||
format!("name = \"Mock Remote\"\ncommand = {:?}\nargs = []\n", agent_script.to_string_lossy()),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let _guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
|
||||
|
||||
// 1. Connect first client, open project, and start a long-running agent task.
|
||||
let (first, _) = attach_client(&home, &base, "~/demo", 1);
|
||||
initialize(&first).await;
|
||||
invoke(&first, "open_project", json!({ "path": project })).await.unwrap();
|
||||
invoke(&first, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap();
|
||||
let _ =
|
||||
invoke(&first, "agent_subscribe", json!({ "onEvent": { "$channel": 1 }, "subscriber": "w1" })).await.unwrap();
|
||||
let report1 = invoke(&first, "agent_reconcile_interrupted", json!({})).await.unwrap();
|
||||
let instance1 = report1["instanceId"].as_str().unwrap().to_owned();
|
||||
|
||||
let created = invoke(
|
||||
&first,
|
||||
"agent_create",
|
||||
json!({
|
||||
"request": {
|
||||
"projectRoot": null,
|
||||
"prompt": { "text": "hold", "files": [], "images": [] },
|
||||
"provider": "mock",
|
||||
"config": [],
|
||||
"isolation": "local",
|
||||
"base": null,
|
||||
"mcpOverrides": {},
|
||||
"skillOverrides": {},
|
||||
"idle": false,
|
||||
"ephemeral": false,
|
||||
}
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let task_id = created["id"].as_str().unwrap().to_owned();
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let tasks = invoke(&first, "agent_subscribe", json!({ "onEvent": { "$channel": 2 }, "subscriber": "w1" }))
|
||||
.await
|
||||
.unwrap();
|
||||
if tasks.as_array().unwrap().iter().any(|t| t["id"] == task_id && t["status"] == "running") {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("remote agent task did not reach running");
|
||||
|
||||
// 2. Kill client relay (SSH disconnect / laptop sleep) and wait past the 1s idle timeout:
|
||||
// `has_live_work()` keeps the daemon and the agent turn alive!
|
||||
first.kill();
|
||||
first.exited().await;
|
||||
tokio::time::sleep(Duration::from_millis(1600)).await;
|
||||
|
||||
let (second, _) = attach_client(&home, &base, "~/demo", 1);
|
||||
initialize(&second).await;
|
||||
let tasks =
|
||||
invoke(&second, "agent_subscribe", json!({ "onEvent": { "$channel": 1 }, "subscriber": "w2" })).await.unwrap();
|
||||
let live_task = tasks.as_array().unwrap().iter().find(|t| t["id"] == task_id).unwrap();
|
||||
assert_eq!(live_task["status"], json!("running"), "SSH disconnect must not interrupt a remote daemon's agent");
|
||||
let report2 = invoke(&second, "agent_reconcile_interrupted", json!({})).await.unwrap();
|
||||
assert_eq!(report2["instanceId"].as_str(), Some(instance1.as_str()));
|
||||
assert_eq!(report2["firstReconcile"], json!(false));
|
||||
|
||||
// 3. Explicit Stop Remote Backend (`"shutdown"`) settles the active turn as `Interrupted (backendStop)`.
|
||||
shutdown(&second).await;
|
||||
|
||||
// 4. Reconnect (spawns fresh daemon): new `instanceId`, task is `Interrupted (backendStop)`, and 1-click Resume finishes!
|
||||
let (third, _) = attach_client(&home, &base, "~/demo", 5);
|
||||
initialize(&third).await;
|
||||
invoke(&third, "open_project", json!({ "path": project })).await.unwrap();
|
||||
let tasks3 =
|
||||
invoke(&third, "agent_subscribe", json!({ "onEvent": { "$channel": 1 }, "subscriber": "w3" })).await.unwrap();
|
||||
let stopped_task = tasks3.as_array().unwrap().iter().find(|t| t["id"] == task_id).unwrap();
|
||||
assert_eq!(stopped_task["status"], json!("ready"));
|
||||
assert_eq!(stopped_task["interrupted"]["reason"], json!("backendStop"));
|
||||
|
||||
let report3 = invoke(&third, "agent_reconcile_interrupted", json!({})).await.unwrap();
|
||||
assert_ne!(report3["instanceId"].as_str(), Some(instance1.as_str()));
|
||||
assert_eq!(report3["firstReconcile"], json!(true));
|
||||
assert_eq!(report3["interrupted"], json!([task_id]));
|
||||
|
||||
invoke(&third, "agent_resume_task", json!({ "task": task_id })).await.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let cur = invoke(&third, "agent_subscribe", json!({ "onEvent": { "$channel": 2 }, "subscriber": "w3" }))
|
||||
.await
|
||||
.unwrap();
|
||||
let t = cur.as_array().unwrap().iter().find(|t| t["id"] == task_id).unwrap();
|
||||
if t["status"] == "ready" && t.get("interrupted").is_none_or(Value::is_null) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("resumed remote task did not finish");
|
||||
|
||||
let entries = invoke(&third, "agent_entries", json!({ "task": task_id, "subagent": null })).await.unwrap();
|
||||
assert!(entries.as_array().unwrap().iter().any(|e| e["type"] == "agent" && e["text"] == "remote resumed"));
|
||||
shutdown(&third).await;
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Settings Sync between two machines through a local bare repository.
|
||||
|
||||
mod common;
|
||||
|
||||
use ide_host::Host;
|
||||
use ide_host::ops::settings_sync::{SettingsSyncMode, SettingsSyncResult, has_local_changes, sync_now};
|
||||
use ide_ssh::secrets::testing::use_memory_store;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
type Storage = BTreeMap<String, BTreeMap<String, String>>;
|
||||
|
||||
fn machine(dir: &Path, remote: &Path, settings: &str) -> Host {
|
||||
std::fs::create_dir_all(dir.join("config")).unwrap();
|
||||
let repository = format!("[settingsSync]\nrepository = {:?}\n", remote.to_str().unwrap());
|
||||
std::fs::write(dir.join("config/settings.toml"), format!("{repository}{settings}")).unwrap();
|
||||
Host::new(common::host_config(dir))
|
||||
}
|
||||
|
||||
fn storage(entries: &[(&str, &str, &str)]) -> Storage {
|
||||
let mut out = Storage::new();
|
||||
for (category, key, value) in entries {
|
||||
out.entry((*category).into()).or_default().insert((*key).into(), (*value).into());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn two_machines_sync_through_a_bare_repository() {
|
||||
use_memory_store();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let remote = tmp.path().join("settings.git");
|
||||
assert!(std::process::Command::new("git").args(["init", "--bare", "-q"]).arg(&remote).status().unwrap().success());
|
||||
|
||||
let a = machine(
|
||||
&tmp.path().join("a"),
|
||||
&remote,
|
||||
"[general]\nconfirmExit = false\nlastRunVersion = \"a\"\n[editor]\nfontSize = 15\n\
|
||||
[languages.python]\ninterpreter = \"/a/bin/python\"\n[proxy]\npassword = \"p\"\n[terminal.env]\nAWS_ACCESS_KEY_ID = \"AKIA-SECRET\"\n",
|
||||
);
|
||||
let b = machine(
|
||||
&tmp.path().join("b"),
|
||||
&remote,
|
||||
"[general]\nlastRunVersion = \"b\"\n[editor]\ntabSize = 2\n[languages.python]\ninterpreter = \"/b/bin/python\"\n",
|
||||
);
|
||||
let macros = storage(&[("macros", "openidea.macros.v1", "[\"a\"]")]);
|
||||
let a_storage = storage(&[("macros", "openidea.macros.v1", "[\"a\"]"), ("plugins", "acme.minimap", "Minimap")]);
|
||||
|
||||
// A pushes first; B finds settings it never synced with and is asked.
|
||||
assert_eq!(sync_now(&a, &a_storage, None, false).unwrap(), SettingsSyncResult::default());
|
||||
assert!(sync_now(&b, &Storage::new(), None, false).unwrap().needs_choice);
|
||||
let merged = sync_now(&b, &Storage::new(), Some(SettingsSyncMode::Merge), false).unwrap();
|
||||
assert!(merged.settings_changed);
|
||||
assert_eq!(merged.storage, macros);
|
||||
let minimap = BTreeMap::from([("acme.minimap".to_owned(), "Minimap".to_owned())]);
|
||||
assert_eq!(merged.plugins_elsewhere, minimap, "offered, not installed");
|
||||
let settings = b.global_settings.effective();
|
||||
assert_eq!((settings.editor.font_size, settings.editor.tab_size), (15.0, 2));
|
||||
assert_eq!(settings.languages.python.interpreter, "/b/bin/python", "machine paths stay");
|
||||
assert_eq!((settings.general.confirm_exit, settings.general.last_run_version.as_str()), (false, "b"));
|
||||
|
||||
// A picks up B's change; nothing secret or machine-specific reached the repository.
|
||||
assert!(sync_now(&a, ¯os, None, false).unwrap().settings_changed);
|
||||
assert_eq!(a.global_settings.effective().editor.tab_size, 2);
|
||||
assert_eq!(a.global_settings.effective().languages.python.interpreter, "/a/bin/python");
|
||||
let log = std::process::Command::new("git").current_dir(&remote).args(["log", "-p", "main"]).output().unwrap();
|
||||
let log = String::from_utf8(log.stdout).unwrap();
|
||||
assert!(
|
||||
log.contains("\"fontSize\": 15")
|
||||
&& !log.contains("python")
|
||||
&& !log.contains("password")
|
||||
&& !log.contains("lastRunVersion")
|
||||
&& !log.contains("AKIA-SECRET"),
|
||||
"{log}"
|
||||
);
|
||||
|
||||
// Nothing changed since: the check after a settings change stays off the network.
|
||||
assert!(!has_local_changes(&a, ¯os).unwrap());
|
||||
assert!(has_local_changes(&a, &a_storage).unwrap(), "a newly installed plugin counts");
|
||||
a.global_settings
|
||||
.set(ide_workspace::settings::SettingsScope::Global, "languages.python.interpreter", "/a/py2".into())
|
||||
.unwrap();
|
||||
assert!(!has_local_changes(&a, ¯os).unwrap(), "machine paths do not count");
|
||||
|
||||
// Both change the font size: each machine's own value wins where it syncs, and is reported.
|
||||
a.global_settings.set(ide_workspace::settings::SettingsScope::Global, "editor.fontSize", 16.into()).unwrap();
|
||||
assert!(has_local_changes(&a, ¯os).unwrap());
|
||||
b.global_settings.set(ide_workspace::settings::SettingsScope::Global, "editor.fontSize", 17.into()).unwrap();
|
||||
sync_now(&a, ¯os, None, false).unwrap();
|
||||
let late = sync_now(&b, ¯os, None, false).unwrap();
|
||||
assert_eq!(late.overwritten, ["editor.fontSize"]);
|
||||
sync_now(&a, ¯os, None, false).unwrap();
|
||||
assert_eq!(a.global_settings.effective().editor.font_size, 17.0);
|
||||
}
|
||||
|
||||
/// Commits `contents` over `name` in the repository (`None` deletes it), as another tool would.
|
||||
fn edit_remote(remote: &Path, work: &Path, name: &str, contents: Option<&str>) {
|
||||
let git = |dir: &Path, args: &[&str]| {
|
||||
let mut command = std::process::Command::new("git");
|
||||
command.current_dir(dir).args(["-c", "user.name=t", "-c", "[email protected]"]).args(args);
|
||||
assert!(command.status().unwrap().success(), "{args:?}");
|
||||
};
|
||||
let _ = std::fs::remove_dir_all(work);
|
||||
git(remote.parent().unwrap(), &["clone", "-q", remote.to_str().unwrap(), work.to_str().unwrap()]);
|
||||
match contents {
|
||||
Some(text) => std::fs::write(work.join(name), text).unwrap(),
|
||||
None => std::fs::remove_file(work.join(name)).unwrap(),
|
||||
}
|
||||
git(work, &["commit", "-qam", "edit"]);
|
||||
git(work, &["push", "-q", "origin", "HEAD:main"]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_broken_or_missing_file_never_clears_this_computers_settings() {
|
||||
use_memory_store();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let remote = tmp.path().join("settings.git");
|
||||
assert!(
|
||||
std::process::Command::new("git")
|
||||
.args(["init", "--bare", "-q", "-b", "main"])
|
||||
.arg(&remote)
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
let a = machine(&tmp.path().join("a"), &remote, "[editor]\nfontSize = 15\n");
|
||||
let macros = storage(&[("macros", "openidea.macros.v1", "[\"a\"]")]);
|
||||
sync_now(&a, ¯os, None, false).unwrap();
|
||||
let show = |name: &str| {
|
||||
let spec = format!("main:{name}");
|
||||
let out = std::process::Command::new("git").current_dir(&remote).args(["show", &spec]).output().unwrap();
|
||||
String::from_utf8(out.stdout).unwrap()
|
||||
};
|
||||
|
||||
// Conflict markers or another shape: the sync stops, naming the file, and changes nothing.
|
||||
for (name, broken) in [("editor.json", "<<<<<<< theirs\n{}\n"), ("macros.json", "[]\n")] {
|
||||
let good = show(name);
|
||||
edit_remote(&remote, &tmp.path().join("work"), name, Some(broken));
|
||||
let error = sync_now(&a, ¯os, None, false).unwrap_err();
|
||||
assert!(error.message.contains(name), "{}", error.message);
|
||||
assert_eq!(a.global_settings.effective().editor.font_size, 15.0, "{name}");
|
||||
assert_eq!(show(name), broken, "{name} is left for the user to repair");
|
||||
edit_remote(&remote, &tmp.path().join("work"), name, Some(&good));
|
||||
let repaired = sync_now(&a, ¯os, None, false).unwrap();
|
||||
assert!(!repaired.settings_changed && repaired.storage.is_empty(), "{repaired:?}");
|
||||
}
|
||||
|
||||
// An unreadable plugin list is left alone; the rest still syncs.
|
||||
let good = show("plugins.json");
|
||||
edit_remote(&remote, &tmp.path().join("work"), "plugins.json", Some("<<<<<<< theirs\n"));
|
||||
let with_plugin = storage(&[("macros", "openidea.macros.v1", "[\"a\"]"), ("plugins", "acme.minimap", "Minimap")]);
|
||||
assert!(sync_now(&a, &with_plugin, None, false).unwrap().plugins_elsewhere.is_empty());
|
||||
assert_eq!(show("plugins.json"), "<<<<<<< theirs\n");
|
||||
edit_remote(&remote, &tmp.path().join("work"), "plugins.json", Some(&good));
|
||||
|
||||
// A deleted file is written again from this computer's settings.
|
||||
edit_remote(&remote, &tmp.path().join("work"), "editor.json", None);
|
||||
let result = sync_now(&a, ¯os, None, false).unwrap();
|
||||
assert!(!result.settings_changed, "{result:?}");
|
||||
assert_eq!(a.global_settings.effective().editor.font_size, 15.0);
|
||||
assert!(show("editor.json").contains("\"fontSize\": 15"));
|
||||
}
|
||||
@@ -177,6 +177,45 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
|
||||
),
|
||||
call!("vcs_blame", "", vcs::vcs_blame(host, w, file.clone(), None, None)),
|
||||
call!("vcs_block_history", "", vcs::vcs_block_history(host, w, RequestId(1), file.clone(), None, (0, 1))),
|
||||
call!(
|
||||
"vcs_block_history_summary",
|
||||
"",
|
||||
vcs::vcs_block_history_summary(host, w, RequestId(31), file.clone(), None, (0, 1))
|
||||
),
|
||||
call!(
|
||||
"vcs_block_history_revisions",
|
||||
"",
|
||||
vcs::vcs_block_history_revisions(
|
||||
host,
|
||||
w,
|
||||
RequestId(32),
|
||||
file.clone(),
|
||||
ide_vcs::BlockHistoryAnchor { commit: project.head.clone(), lines: (0, 1) },
|
||||
0,
|
||||
vec![project.first.clone()]
|
||||
)
|
||||
),
|
||||
call!(
|
||||
"vcs_block_history_revisions_at",
|
||||
"",
|
||||
vcs::vcs_block_history_revisions_at(
|
||||
host,
|
||||
w,
|
||||
RequestId(34),
|
||||
file.clone(),
|
||||
// Two spots so the parallel scoped-thread path runs in Restricted Mode.
|
||||
vec![
|
||||
ide_vcs::BlockRevisionSpot {
|
||||
id: project.head.clone(),
|
||||
ranges: Some(vec![ide_vcs::BlockSpotRange { path: "src/a.txt".into(), start: 1, end: 3 }])
|
||||
},
|
||||
ide_vcs::BlockRevisionSpot {
|
||||
id: project.first.clone(),
|
||||
ranges: Some(vec![ide_vcs::BlockSpotRange { path: "src/a.txt".into(), start: 1, end: 2 }])
|
||||
}
|
||||
]
|
||||
)
|
||||
),
|
||||
call!("vcs_log", "", vcs::vcs_log(host, w, root(), Default::default())),
|
||||
call!("vcs_log_refs", "", vcs::vcs_log_refs(host, w, root())),
|
||||
call!("vcs_log_users", "", vcs::vcs_log_users(host, w, root())),
|
||||
|
||||
@@ -556,3 +556,19 @@ async fn add_to_ignore_accepts_the_repositories_of_attached_projects() {
|
||||
assert!(!sibling_root.join(".gitignore").exists());
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_repository_created_in_the_project_is_known_when_init_returns() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let project_root = base.join("project");
|
||||
std::fs::create_dir_all(&project_root).unwrap();
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&project_root, true, false).unwrap();
|
||||
let project = host.open_project("main", &project_root).unwrap();
|
||||
assert!(project.repos().all().is_empty());
|
||||
|
||||
vcs::vcs_init(&host, "main", project_root.clone()).await.unwrap();
|
||||
let roots: Vec<_> = project.repos().all().iter().map(|r| r.root().to_path_buf()).collect();
|
||||
assert_eq!(roots, [project_root]);
|
||||
}
|
||||
@@ -11,8 +11,11 @@ ide-vfs.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json = { workspace = true, features = ["raw_value"] }
|
||||
specta.workspace = true
|
||||
tokio.workspace = true
|
||||
# `net`: tunnel.rs opens connections reqwest does not (a WebSocket).
|
||||
tokio = { workspace = true, features = ["net"] }
|
||||
parking_lot.workspace = true
|
||||
base64.workspace = true
|
||||
http = "1"
|
||||
reqwest.workspace = true
|
||||
# The system proxy reqwest reads, to notice when it changes (see `client::shared`).
|
||||
hyper-util = { version = "0.1", default-features = false, features = ["client-proxy", "client-proxy-system"] }
|
||||
@@ -20,6 +23,10 @@ rustls.workspace = true
|
||||
rustls-platform-verifier.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFArray", "CFDictionary", "CFError", "CFNumber", "CFString", "CFURL"] }
|
||||
objc2-cf-network = { version = "0.3", default-features = false, features = ["std", "CFProxySupport"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["net"] }
|
||||
tempfile.workspace = true
|
||||
@@ -7,10 +7,14 @@ use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// `builder` routed as `proxy` says: direct, the environment's proxy (reqwest's
|
||||
/// default), or the manual proxy except for the "No proxy for" hosts.
|
||||
/// `builder` routed as `proxy` says: direct, the system's proxy (reqwest's
|
||||
/// default, plus the macOS PAC script when configured and no `*_PROXY` env var
|
||||
/// is set), or the manual proxy except for the "No proxy for" hosts.
|
||||
pub fn with_proxy(builder: reqwest::ClientBuilder, proxy: &ProxySettings) -> reqwest::ClientBuilder {
|
||||
match proxy.mode {
|
||||
#[cfg(target_os = "macos")]
|
||||
ProxyMode::Auto => crate::pac::with_system_pac(builder),
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
ProxyMode::Auto => builder,
|
||||
ProxyMode::None => builder.no_proxy(),
|
||||
ProxyMode::Manual => {
|
||||
@@ -42,9 +46,7 @@ pub fn tls_config() -> IdeResult<rustls::ClientConfig> {
|
||||
.map(|builder| builder.with_no_client_auth())
|
||||
}
|
||||
|
||||
/// A client with an explicit redirect policy, for callers enforcing network grants.
|
||||
pub fn build_with_redirect(proxy: &ProxySettings, redirect: reqwest::redirect::Policy) -> IdeResult<reqwest::Client> {
|
||||
let fail = |e: String| IdeError::internal(format!("HTTP client: {e}"));
|
||||
fn base_builder(redirect: reqwest::redirect::Policy) -> IdeResult<reqwest::ClientBuilder> {
|
||||
let tls = tls_config()?;
|
||||
// `localhost` is tried on IPv4 first: local servers (Ollama, dev servers)
|
||||
// usually listen there, and on Windows a refused `::1` costs ~2 s before
|
||||
@@ -53,13 +55,26 @@ pub fn build_with_redirect(proxy: &ProxySettings, redirect: reqwest::redirect::P
|
||||
std::net::SocketAddr::from((std::net::Ipv4Addr::LOCALHOST, 0)),
|
||||
std::net::SocketAddr::from((std::net::Ipv6Addr::LOCALHOST, 0)),
|
||||
];
|
||||
let builder = reqwest::Client::builder()
|
||||
Ok(reqwest::Client::builder()
|
||||
.tls_backend_preconfigured(tls)
|
||||
.redirect(redirect)
|
||||
.resolve_to_addrs("localhost", &loopback)
|
||||
.connect_timeout(Duration::from_secs(30))
|
||||
.user_agent(concat!("OpenIDEA-HttpClient/", env!("CARGO_PKG_VERSION")));
|
||||
with_proxy(builder, proxy).build().map_err(|e| fail(e.to_string()))
|
||||
.user_agent(concat!("OpenIDEA-HttpClient/", env!("CARGO_PKG_VERSION"))))
|
||||
}
|
||||
|
||||
/// A client with an explicit redirect policy, for callers enforcing network grants.
|
||||
pub fn build_with_redirect(proxy: &ProxySettings, redirect: reqwest::redirect::Policy) -> IdeResult<reqwest::Client> {
|
||||
let fail = |e: String| IdeError::internal(format!("HTTP client: {e}"));
|
||||
with_proxy(base_builder(redirect)?, proxy).build().map_err(|e| fail(e.to_string()))
|
||||
}
|
||||
|
||||
#[cfg(all(test, target_os = "macos"))]
|
||||
pub(crate) fn build_with_builder(
|
||||
f: impl FnOnce(reqwest::ClientBuilder) -> reqwest::ClientBuilder,
|
||||
) -> IdeResult<reqwest::Client> {
|
||||
let fail = |e: String| IdeError::internal(format!("HTTP client: {e}"));
|
||||
f(base_builder(reqwest::redirect::Policy::default())?).build().map_err(|e| fail(e.to_string()))
|
||||
}
|
||||
|
||||
/// A client built for these proxy settings and, in Auto mode, this system proxy.
|
||||
@@ -83,10 +98,11 @@ pub fn shared_without_redirects() -> IdeResult<reqwest::Client> {
|
||||
cached_client(&CLIENT, |proxy| build_with_redirect(proxy, reqwest::redirect::Policy::none()), system_proxy)
|
||||
}
|
||||
|
||||
/// The system proxy (the environment's, then macOS / Windows settings) as reqwest reads
|
||||
/// it when a client is built, re-read at most every few seconds. A client in Auto mode
|
||||
/// keeps the proxy it was built with, so a proxy app that switches the system proxy on
|
||||
/// after launch would otherwise leave downloads going direct until a restart.
|
||||
/// The system proxy (the environment's, then macOS / Windows settings, including
|
||||
/// any active macOS PAC configuration) as reqwest reads it when a client is built,
|
||||
/// re-read at most every few seconds. A client in Auto mode keeps the proxy it
|
||||
/// was built with, so a proxy app or PAC change after launch would otherwise
|
||||
/// leave downloads on the old route until a restart.
|
||||
fn system_proxy() -> String {
|
||||
static LAST: Mutex<Option<(Instant, String)>> = Mutex::new(None);
|
||||
let mut last = LAST.lock();
|
||||
@@ -96,7 +112,14 @@ fn system_proxy() -> String {
|
||||
return seen.clone();
|
||||
}
|
||||
// Credentials are left out of the matcher's `Debug`.
|
||||
let seen = format!("{:?}", hyper_util::client::proxy::matcher::Matcher::from_system());
|
||||
let base = format!("{:?}", hyper_util::client::proxy::matcher::Matcher::from_system());
|
||||
#[cfg(target_os = "macos")]
|
||||
let seen = match crate::pac::system_pac_fingerprint() {
|
||||
Some(pac) => format!("{base}\n{pac}"),
|
||||
None => base,
|
||||
};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let seen = base;
|
||||
*last = Some((Instant::now(), seen.clone()));
|
||||
seen
|
||||
}
|
||||
@@ -199,6 +222,17 @@ mod tests {
|
||||
get();
|
||||
get();
|
||||
assert_eq!(BUILDS.load(std::sync::atomic::Ordering::SeqCst), 2);
|
||||
// A PAC URL is added, changed, and later removed.
|
||||
*SYSTEM.lock() = "Matcher {}\npac:0000000000000001".into();
|
||||
get();
|
||||
get();
|
||||
assert_eq!(BUILDS.load(std::sync::atomic::Ordering::SeqCst), 3);
|
||||
*SYSTEM.lock() = "Matcher {}\npac:0000000000000002".into();
|
||||
get();
|
||||
assert_eq!(BUILDS.load(std::sync::atomic::Ordering::SeqCst), 4);
|
||||
*SYSTEM.lock() = "Matcher {}".into();
|
||||
get();
|
||||
assert_eq!(BUILDS.load(std::sync::atomic::Ordering::SeqCst), 5);
|
||||
}
|
||||
use ide_core::proxy_settings::ProxyKind;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
|
||||
@@ -10,7 +10,10 @@ pub mod curl;
|
||||
pub mod env;
|
||||
pub mod exec;
|
||||
pub mod history;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod pac;
|
||||
pub mod parse;
|
||||
pub mod tunnel;
|
||||
|
||||
pub use env::Environments;
|
||||
pub use exec::{HttpResponse, PreparedRequest};
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,165 @@
|
||||
//! A TCP connection routed like the HTTP client's requests, for protocols reqwest does not
|
||||
//! speak (a WebSocket): direct, or through an HTTP proxy's `CONNECT` tunnel.
|
||||
|
||||
use base64::Engine;
|
||||
use ide_core::proxy_settings::ProxyRoute;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// A connection to `url`'s host and port, through the proxy System Settings › HTTP Proxy
|
||||
/// (or, in Auto mode, the system) routes that host to.
|
||||
pub async fn connect(url: &reqwest::Url) -> IdeResult<TcpStream> {
|
||||
let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?;
|
||||
let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?;
|
||||
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
|
||||
let proxy = match ide_core::proxy_settings::proxy().route(Some(host)) {
|
||||
ProxyRoute::Direct => None,
|
||||
ProxyRoute::Via(via) => Some(via),
|
||||
ProxyRoute::System => {
|
||||
// The system proxy of the scheme reqwest would use (`ws` → `http`).
|
||||
let scheme = if url.scheme() == "wss" || url.scheme() == "https" { "https" } else { "http" };
|
||||
let uri: http::Uri =
|
||||
format!("{scheme}://{target}/").parse().map_err(|_| IdeError::invalid("invalid host"))?;
|
||||
hyper_util::client::proxy::matcher::Matcher::from_system().intercept(&uri).map(|intercept| {
|
||||
let auth =
|
||||
intercept.raw_auth().map(|(user, password)| format!("{user}:{password}@")).unwrap_or_default();
|
||||
let uri = intercept.uri();
|
||||
format!(
|
||||
"{}://{auth}{}",
|
||||
uri.scheme_str().unwrap_or("http"),
|
||||
uri.authority().map(|a| a.as_str()).unwrap_or_default()
|
||||
)
|
||||
})
|
||||
}
|
||||
};
|
||||
let connecting = async {
|
||||
let Some(proxy) = proxy else {
|
||||
return TcpStream::connect(&target).await.map_err(|error| reach(&target, &error));
|
||||
};
|
||||
let proxy = reqwest::Url::parse(&proxy).map_err(|_| IdeError::invalid("invalid proxy URL"))?;
|
||||
if proxy.scheme() != "http" {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"a {} proxy cannot carry this connection; set an HTTP proxy",
|
||||
proxy.scheme()
|
||||
)));
|
||||
}
|
||||
let address =
|
||||
format!("{}:{}", proxy.host_str().unwrap_or_default(), proxy.port_or_known_default().unwrap_or(80));
|
||||
let stream = TcpStream::connect(&address).await.map_err(|error| reach(&address, &error))?;
|
||||
let auth = (!proxy.username().is_empty()).then(|| {
|
||||
let user = percent_decode(proxy.username());
|
||||
let password = percent_decode(proxy.password().unwrap_or_default());
|
||||
base64::engine::general_purpose::STANDARD.encode(format!("{user}:{password}"))
|
||||
});
|
||||
tunnel(stream, &target, auth.as_deref()).await
|
||||
};
|
||||
tokio::time::timeout(CONNECT_TIMEOUT, connecting)
|
||||
.await
|
||||
.map_err(|_| IdeError::unavailable(format!("connecting to {target} timed out")))?
|
||||
}
|
||||
|
||||
fn reach(address: &str, error: &std::io::Error) -> IdeError {
|
||||
IdeError::unavailable(format!("could not connect to {address}: {error}"))
|
||||
}
|
||||
|
||||
fn percent_decode(text: &str) -> String {
|
||||
let bytes = text.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%'
|
||||
&& let Some(byte) = text.get(i + 1..i + 3).and_then(|hex| u8::from_str_radix(hex, 16).ok())
|
||||
{
|
||||
out.push(byte);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
/// Asks the proxy on `stream` for a tunnel to `target` (`host:port`).
|
||||
async fn tunnel(mut stream: TcpStream, target: &str, auth: Option<&str>) -> IdeResult<TcpStream> {
|
||||
let auth = auth.map(|auth| format!("Proxy-Authorization: Basic {auth}\r\n")).unwrap_or_default();
|
||||
let request = format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n{auth}\r\n");
|
||||
let failed = |error: std::io::Error| IdeError::unavailable(format!("proxy: {error}"));
|
||||
stream.write_all(request.as_bytes()).await.map_err(failed)?;
|
||||
// The reply's head only: nothing follows it until this side speaks.
|
||||
let mut head = Vec::new();
|
||||
let mut byte = [0u8; 1];
|
||||
while !head.ends_with(b"\r\n\r\n") {
|
||||
if head.len() > 8192 || stream.read(&mut byte).await.map_err(failed)? == 0 {
|
||||
return Err(IdeError::unavailable("the proxy closed the connection"));
|
||||
}
|
||||
head.push(byte[0]);
|
||||
}
|
||||
let status = String::from_utf8_lossy(&head);
|
||||
let status = status.lines().next().unwrap_or_default();
|
||||
match status.split_whitespace().nth(1) {
|
||||
Some("200") => Ok(stream),
|
||||
Some("407") => Err(IdeError::unavailable("the proxy needs a login (HTTP Proxy settings)")),
|
||||
_ => Err(IdeError::unavailable(format!("the proxy refused the connection: {status}"))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
/// A proxy that answers `reply` to one CONNECT and then echoes; returns what it was asked.
|
||||
async fn proxy(reply: &'static str) -> (String, tokio::task::JoinHandle<String>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap().to_string();
|
||||
let task = tokio::spawn(async move {
|
||||
let (mut client, _) = listener.accept().await.unwrap();
|
||||
let mut head = Vec::new();
|
||||
let mut byte = [0u8; 1];
|
||||
while !head.ends_with(b"\r\n\r\n") {
|
||||
client.read_exact(&mut byte).await.unwrap();
|
||||
head.push(byte[0]);
|
||||
}
|
||||
client.write_all(reply.as_bytes()).await.unwrap();
|
||||
let mut echo = [0u8; 5];
|
||||
if client.read_exact(&mut echo).await.is_ok() {
|
||||
client.write_all(&echo).await.unwrap();
|
||||
}
|
||||
String::from_utf8(head).unwrap()
|
||||
});
|
||||
(address, task)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_tunnel_carries_bytes_after_the_proxy_agrees() {
|
||||
let (address, asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
|
||||
let stream = TcpStream::connect(&address).await.unwrap();
|
||||
let mut stream = tunnel(stream, "hub.example.com:443", Some("dTpw")).await.unwrap();
|
||||
stream.write_all(b"hello").await.unwrap();
|
||||
let mut back = [0u8; 5];
|
||||
stream.read_exact(&mut back).await.unwrap();
|
||||
assert_eq!(&back, b"hello");
|
||||
let asked = asked.await.unwrap();
|
||||
assert!(asked.starts_with("CONNECT hub.example.com:443 HTTP/1.1\r\n"));
|
||||
assert!(asked.contains("Proxy-Authorization: Basic dTpw\r\n"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_refused_tunnel_says_why() {
|
||||
let (address, _) = proxy("HTTP/1.1 407 Proxy Authentication Required\r\n\r\n").await;
|
||||
let stream = TcpStream::connect(&address).await.unwrap();
|
||||
let error = tunnel(stream, "hub.example.com:443", None).await.unwrap_err();
|
||||
assert!(error.message.contains("needs a login"), "{}", error.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_credentials_are_percent_decoded() {
|
||||
assert_eq!(percent_decode("a%40b%3Ac"), "a@b:c");
|
||||
assert_eq!(percent_decode("100%"), "100%");
|
||||
}
|
||||
}
|
||||
@@ -182,7 +182,9 @@ impl Shared {
|
||||
let snapshot_started = Instant::now();
|
||||
let fast = self.try_fast_start();
|
||||
let snapshot_elapsed = snapshot_started.elapsed();
|
||||
if let Err(reason) = fast {
|
||||
if fast.is_err() && self.is_cancelled() {
|
||||
// Closing: the stat loops stopped early, and a fallback walk would only stall the close.
|
||||
} else if let Err(reason) = fast {
|
||||
let snapshot_guard = SystemTime::now();
|
||||
let walk_started = Instant::now();
|
||||
let found = self.walk_roots(None);
|
||||
@@ -276,13 +278,24 @@ impl Shared {
|
||||
}
|
||||
let root = filter.root();
|
||||
let validation_started = Instant::now();
|
||||
for i in 0..snapshot.dirs_len() {
|
||||
let rel = snapshot.dir(i);
|
||||
let path = if rel.is_empty() { root.to_owned() } else { root.join(rel) };
|
||||
let Ok(meta) = std::fs::symlink_metadata(&path) else { return Err("directory changed") };
|
||||
if !meta.is_dir() || mtime_of(&meta) != snapshot.dir_mtime(i) {
|
||||
return Err("directory changed");
|
||||
}
|
||||
// In parallel: on a network share each stat is a round trip.
|
||||
let cancelled = &self.cancelled;
|
||||
let dirs_valid = INDEX_POOL.install(|| {
|
||||
(0..snapshot.dirs_len()).into_par_iter().all(|i| {
|
||||
if cancelled.load(Ordering::Relaxed) {
|
||||
return false;
|
||||
}
|
||||
let rel = snapshot.dir(i);
|
||||
let path = if rel.is_empty() { root.to_owned() } else { root.join(rel) };
|
||||
std::fs::symlink_metadata(&path)
|
||||
.is_ok_and(|meta| meta.is_dir() && mtime_of(&meta) == snapshot.dir_mtime(i))
|
||||
})
|
||||
});
|
||||
if self.is_cancelled() {
|
||||
return Err("cancelled");
|
||||
}
|
||||
if !dirs_valid {
|
||||
return Err("directory changed");
|
||||
}
|
||||
let external = crate::store::external_ignore_candidates(root);
|
||||
let saved_external: Vec<&str> = (0..snapshot.ignore_len())
|
||||
@@ -309,28 +322,56 @@ impl Shared {
|
||||
}
|
||||
let validation_elapsed = validation_started.elapsed();
|
||||
let build_started = Instant::now();
|
||||
let entries: Vec<Option<(FileEntry, Vec<StoredSymbol>)>> = INDEX_POOL.install(|| {
|
||||
(0..snapshot.len())
|
||||
.into_par_iter()
|
||||
.map(|i| {
|
||||
let path = root.join(snapshot.rel(i));
|
||||
let meta = std::fs::symlink_metadata(&path).ok()?;
|
||||
if !meta.is_file() || mtime_of(&meta) != snapshot.mtime(i) || meta.len() != snapshot.size(i) {
|
||||
// Files are checked against their folder's listing, one per folder: on Windows the
|
||||
// listing carries each entry's metadata, so a share costs a round trip per folder
|
||||
// instead of one per file. Elsewhere `DirEntry::metadata` is the same `lstat`.
|
||||
let mut by_dir: HashMap<&str, Vec<usize>> = HashMap::new();
|
||||
for i in 0..snapshot.len() {
|
||||
let rel = snapshot.rel(i);
|
||||
if !safe_rel(rel) {
|
||||
return Err("file changed");
|
||||
}
|
||||
let dir = rel.rfind('/').map_or("", |at| &rel[..at]);
|
||||
by_dir.entry(dir).or_default().push(i);
|
||||
}
|
||||
let by_dir: Vec<(&str, Vec<usize>)> = by_dir.into_iter().collect();
|
||||
let entries: Option<Vec<Vec<Indexed>>> = INDEX_POOL.install(|| {
|
||||
by_dir
|
||||
.par_iter()
|
||||
.map(|(dir, files)| {
|
||||
if cancelled.load(Ordering::Relaxed) {
|
||||
return None;
|
||||
}
|
||||
Some(snapshot.entry(i, root))
|
||||
let path = if dir.is_empty() { root.to_owned() } else { root.join(dir) };
|
||||
let listed: HashMap<std::ffi::OsString, std::fs::Metadata> = std::fs::read_dir(&path)
|
||||
.ok()?
|
||||
.filter_map(|e| {
|
||||
let e = e.ok()?;
|
||||
Some((e.file_name(), e.metadata().ok()?))
|
||||
})
|
||||
.collect();
|
||||
files
|
||||
.iter()
|
||||
.map(|&i| {
|
||||
let rel = snapshot.rel(i);
|
||||
let name = rel.rfind('/').map_or(rel, |at| &rel[at + 1..]);
|
||||
let meta = listed.get(std::ffi::OsStr::new(name))?;
|
||||
if !meta.is_file() || mtime_of(meta) != snapshot.mtime(i) || meta.len() != snapshot.size(i)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(snapshot.entry(i, root))
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
let built = build_started.elapsed();
|
||||
if entries.iter().any(Option::is_none) {
|
||||
return Err("file changed");
|
||||
}
|
||||
let validated = entries;
|
||||
let mut entries = Vec::with_capacity(validated.len());
|
||||
for entry in validated {
|
||||
entries.push(entry.expect("validated above"));
|
||||
if self.is_cancelled() {
|
||||
return Err("cancelled");
|
||||
}
|
||||
let Some(entries) = entries else { return Err("file changed") };
|
||||
let entries: Vec<(FileEntry, Vec<StoredSymbol>)> = entries.into_iter().flatten().collect();
|
||||
let dirs: Vec<(Box<str>, PathBuf, u32)> = (0..snapshot.dirs_len())
|
||||
.filter_map(|i| {
|
||||
let rel = snapshot.dir(i);
|
||||
@@ -1108,6 +1149,9 @@ impl Shared {
|
||||
|
||||
type ContentHash = [u8; 32];
|
||||
|
||||
/// A file validated on a warm start, with its stored symbols.
|
||||
type Indexed = (FileEntry, Vec<StoredSymbol>);
|
||||
|
||||
/// `Some(prev_hash)` when `f` is missing or stale in `d` (`None` inner hash when
|
||||
/// the file must be parsed fresh); `None` when `d` is already current for `f`.
|
||||
fn prev_hash_if_stale(d: &IndexData, f: &Found) -> Option<Option<ContentHash>> {
|
||||
@@ -1438,6 +1482,32 @@ mod metric_tests {
|
||||
assert_eq!(index_files(&shared, found[..1].iter(), true).symbol_extractions, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warm_start_checks_files_against_their_folder_listing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
std::fs::create_dir_all(root.join("src/deep")).unwrap();
|
||||
let root = dunce::canonicalize(root).unwrap();
|
||||
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
|
||||
std::fs::write(root.join("src/lib.rs"), "pub fn a() {}\n").unwrap();
|
||||
std::fs::write(root.join("src/deep/b.rs"), "pub fn b() {}\n").unwrap();
|
||||
let cache = dir.path().join("cache");
|
||||
let open = || {
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
index
|
||||
};
|
||||
open().scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
let index = open();
|
||||
assert_eq!(index.try_fast_start(), Ok(()));
|
||||
assert_eq!(index.data.read().file_count, 3);
|
||||
// Same folder mtime, a different size: only the listing's metadata can tell.
|
||||
let dir_mtime = std::fs::metadata(root.join("src/deep")).unwrap().modified().unwrap();
|
||||
std::fs::write(root.join("src/deep/b.rs"), "pub fn b() { /* longer */ }\n").unwrap();
|
||||
std::fs::File::open(root.join("src/deep")).and_then(|f| f.set_modified(dir_mtime)).ok();
|
||||
assert_eq!(open().try_fast_start(), Err("file changed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reopened_cache_counts_metadata_reuse() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -1533,7 +1603,8 @@ mod metric_tests {
|
||||
index.run(true);
|
||||
});
|
||||
assert_eq!(index.parsed.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(index.data.read().file_count, 1);
|
||||
// The project is closing: its validation stops instead of statting the rest of a tree.
|
||||
assert_eq!(index.data.read().file_count, 0);
|
||||
assert_eq!(count.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
|
||||
@@ -29,9 +29,9 @@ pub use syntax::{
|
||||
set_external_syntax, shift_pos, shift_range,
|
||||
};
|
||||
pub use syntax::{
|
||||
MethodBody, PhpAlignment, PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestModule,
|
||||
PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression, bundler_aliases, resolve_fixture,
|
||||
visible_fixtures,
|
||||
MethodBody, PhpAlignment, PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestImport,
|
||||
PytestModule, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression, bundler_aliases,
|
||||
resolve_fixture, visible_fixtures,
|
||||
};
|
||||
|
||||
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
|
||||
|
||||
@@ -50,6 +50,8 @@ const BUILTIN: &[(&str, &str)] = &[
|
||||
("ignore", include_str!("../../../languages/ignore.toml")),
|
||||
("ini", include_str!("../../../languages/ini.toml")),
|
||||
("java", include_str!("../../../languages/java.toml")),
|
||||
("jinja", include_str!("../../../languages/jinja.toml")),
|
||||
("jinja-html", include_str!("../../../languages/jinja-html.toml")),
|
||||
("javascript", include_str!("../../../languages/javascript.toml")),
|
||||
("javascriptreact", include_str!("../../../languages/javascriptreact.toml")),
|
||||
("json", include_str!("../../../languages/json.toml")),
|
||||
@@ -506,6 +508,7 @@ mod tests {
|
||||
"Java",
|
||||
"JavaScript",
|
||||
"Jinja",
|
||||
"Jinja HTML",
|
||||
"JSON",
|
||||
"JSX",
|
||||
"LESS",
|
||||
@@ -854,6 +857,23 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sourcekit_lsp_serves_xcode_projects() {
|
||||
let reg = reg();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["App/App.xcodeproj", "Suite/Suite.xcworkspace", "Bsp/.bsp", "Plain/Sources"] {
|
||||
std::fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
let cfg = reg.get(&LanguageId::new("swift")).unwrap();
|
||||
let sourcekit = cfg.language_servers.iter().find(|s| s.name == "sourcekit-lsp").unwrap();
|
||||
let served = |file: &str| crate::marked_root(Some(root), &root.join(file), &sourcekit.root_markers);
|
||||
assert_eq!(served("App/Sources/View.swift"), Some(root.join("App")));
|
||||
assert_eq!(served("Suite/Sources/View.swift"), Some(root.join("Suite")));
|
||||
assert_eq!(served("Bsp/View.swift"), Some(root.join("Bsp")));
|
||||
assert_eq!(served("Plain/Sources/View.swift"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stylelint_serves_style_sheets_only_below_its_config() {
|
||||
let reg = reg();
|
||||
@@ -1011,6 +1031,21 @@ mod tests {
|
||||
assert!(reg.is_framework_marker(&root.join("src/manage.py")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jinja_templates_are_html_only_by_inner_extension() {
|
||||
let reg = reg();
|
||||
let detect = |file: &str| reg.detect(Path::new(file), None).as_str().to_owned();
|
||||
assert_eq!(detect("templates/base.jinja"), "jinja");
|
||||
assert_eq!(detect("roles/web/templates/nginx.conf.J2"), "jinja");
|
||||
assert_eq!(detect("templates/values.yaml.j2"), "jinja");
|
||||
assert_eq!(detect("templates/page.html.jinja2"), "jinja-html");
|
||||
assert_eq!(detect("templates/page.HTML.j2"), "jinja-html");
|
||||
assert_eq!(detect("templates/mail.htm.jinja"), "jinja-html");
|
||||
// The HTML server only serves the HTML ones.
|
||||
let servers = |id: &str| reg.get(&LanguageId::new(id)).unwrap().language_servers.len();
|
||||
assert_eq!((servers("jinja"), servers("jinja-html")), (0, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn helm_charts_make_yaml_and_notes_in_templates_folders_helm_templates() {
|
||||
let reg = reg();
|
||||
|
||||
@@ -37,8 +37,8 @@ pub use outline::{merge_kinds, merge_visibility};
|
||||
pub use php_align::PhpAlignment;
|
||||
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression};
|
||||
pub use python_fixtures::{
|
||||
PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestModule, resolve_fixture,
|
||||
visible_fixtures,
|
||||
PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestImport, PytestModule,
|
||||
resolve_fixture, visible_fixtures,
|
||||
};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -17,6 +17,18 @@ pub struct PytestModule {
|
||||
pub slots: Vec<PytestFixtureSlot>,
|
||||
/// Modules named by a module-level `pytest_plugins`, as written (`pkg.fixtures`).
|
||||
pub plugins: Vec<String>,
|
||||
/// Module-level `from … import …`: pytest takes an imported fixture as the module's own.
|
||||
pub imports: Vec<PytestImport>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PytestImport {
|
||||
/// As written, leading dots of a relative import included (`.fixtures`).
|
||||
pub module: String,
|
||||
/// The imported name, `*` for a star import.
|
||||
pub name: String,
|
||||
/// The name it is bound to here (`as …`, else the name).
|
||||
pub alias: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -27,6 +39,10 @@ pub struct PytestFixture {
|
||||
pub selection: Range,
|
||||
/// The class whose method it is; only that class's tests see it.
|
||||
pub class: Option<String>,
|
||||
/// Named by `name="…"`: renaming it leaves the function alone.
|
||||
pub by_argument: bool,
|
||||
/// The function's name, which an import names it by.
|
||||
pub function: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -47,6 +63,9 @@ pub struct PytestFixtureUse {
|
||||
/// For a parameter: the names in the function's body that read it (attribute names and
|
||||
/// keyword argument names left out), which a rename of the fixture renames too.
|
||||
pub body: Vec<Range>,
|
||||
/// For a parameter: the names its function already uses (its parameters, the names in its
|
||||
/// body), which a renamed fixture must not take.
|
||||
pub taken: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -63,6 +82,15 @@ impl PytestModule {
|
||||
self.uses.iter().find(|u| u.range.start <= pos && pos <= u.range.end)
|
||||
}
|
||||
|
||||
/// The use at `pos`, or the use whose parameter is read in a function body at `pos`; with
|
||||
/// the range of the name there.
|
||||
pub fn use_or_read_at(&self, pos: Pos) -> Option<(&PytestFixtureUse, Range)> {
|
||||
let covers = |r: &Range| r.start <= pos && pos <= r.end;
|
||||
self.use_at(pos)
|
||||
.map(|u| (u, u.range))
|
||||
.or_else(|| self.uses.iter().find_map(|u| u.body.iter().find(|r| covers(r)).map(|r| (u, *r))))
|
||||
}
|
||||
|
||||
/// The fixture whose name (function name or `name=` string) covers `pos`.
|
||||
pub fn definition_at(&self, pos: Pos) -> Option<usize> {
|
||||
self.fixtures.iter().position(|f| f.selection.start <= pos && pos <= f.selection.end)
|
||||
@@ -177,6 +205,7 @@ fn statement(node: Node, class: Option<&str>, text: &str, idx: &LineIndex, out:
|
||||
}
|
||||
}
|
||||
"expression_statement" if class.is_none() => plugins(definition, text, idx, &mut out.plugins),
|
||||
"import_from_statement" if class.is_none() => imports(definition, text, &mut out.imports),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -203,7 +232,13 @@ fn function(
|
||||
Some((_, string)) => *string,
|
||||
None => idx.range(name_node.start_byte(), name_node.end_byte()),
|
||||
};
|
||||
out.fixtures.push(PytestFixture { name: fixture_name.clone(), selection, class: class.map(str::to_owned) });
|
||||
out.fixtures.push(PytestFixture {
|
||||
name: fixture_name.clone(),
|
||||
selection,
|
||||
class: class.map(str::to_owned),
|
||||
by_argument: f.is_some(),
|
||||
function: name.clone(),
|
||||
});
|
||||
}
|
||||
let Some(params) = def.child_by_field_name("parameters") else { return };
|
||||
out.slots.push(PytestFixtureSlot {
|
||||
@@ -214,6 +249,11 @@ fn function(
|
||||
let mut skip: Vec<String> = parametrized(decorators, text, idx);
|
||||
skip.extend_from_slice(class_args);
|
||||
let mut c = params.walk();
|
||||
let mut taken: Vec<String> = params.named_children(&mut c).filter_map(|p| parameter_name(p, text)).collect();
|
||||
if let Some(body) = def.child_by_field_name("body") {
|
||||
names_in(body, text, &mut taken);
|
||||
}
|
||||
let mut c = params.walk();
|
||||
for (i, param) in params.named_children(&mut c).enumerate() {
|
||||
let ident = match param.kind() {
|
||||
"identifier" => param,
|
||||
@@ -236,29 +276,138 @@ fn function(
|
||||
class: class.map(str::to_owned),
|
||||
in_fixture: fixture.is_some().then(|| fixture_name.clone()),
|
||||
body,
|
||||
taken: taken.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifiers `name` in `body`, except attribute names (`x.name`) and keyword argument
|
||||
/// names (`f(name=…)`). A nested function that rebinds the name is not told apart.
|
||||
/// The name a parameter node binds (`x`, `x: int`, `x=1`, `*x`, `**x`).
|
||||
fn parameter_name(param: Node, text: &str) -> Option<String> {
|
||||
let ident = match param.kind() {
|
||||
"identifier" => param,
|
||||
"typed_parameter" | "list_splat_pattern" | "dictionary_splat_pattern" => {
|
||||
let mut c = param.walk();
|
||||
param.named_children(&mut c).find(|n| n.kind() == "identifier")?
|
||||
}
|
||||
"default_parameter" | "typed_default_parameter" => param.child_by_field_name("name")?,
|
||||
_ => return None,
|
||||
};
|
||||
Some(text_of(ident, text))
|
||||
}
|
||||
|
||||
/// Whether `node` (a nested function, lambda or comprehension) binds `name` itself, so its
|
||||
/// `name` is another variable.
|
||||
fn rebinds(node: Node, name: &str, text: &str) -> bool {
|
||||
match node.kind() {
|
||||
"function_definition" | "lambda" => node.child_by_field_name("parameters").is_some_and(|params| {
|
||||
let mut c = params.walk();
|
||||
params.named_children(&mut c).any(|p| parameter_name(p, text).as_deref() == Some(name))
|
||||
}),
|
||||
"list_comprehension" | "set_comprehension" | "dictionary_comprehension" | "generator_expression" => {
|
||||
let mut c = node.walk();
|
||||
node.named_children(&mut c).filter(|n| n.kind() == "for_in_clause").any(|clause| {
|
||||
let mut found = false;
|
||||
if let Some(left) = clause.child_by_field_name("left") {
|
||||
let mut cursor = left.walk();
|
||||
visit(&mut cursor, &mut |n| found |= n.kind() == "identifier" && text_of(n, text) == name);
|
||||
}
|
||||
found
|
||||
})
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifiers `name` in `body` that read the parameter: not attribute names (`x.name`),
|
||||
/// keyword argument names (`f(name=…)`), nor names inside a nested function, lambda or
|
||||
/// comprehension that binds `name` itself.
|
||||
fn reads_of(body: Node, name: &str, text: &str, idx: &LineIndex) -> Vec<Range> {
|
||||
fn walk(n: Node, name: &str, text: &str, idx: &LineIndex, out: &mut Vec<Range>) {
|
||||
if rebinds(n, name, text) {
|
||||
// Still the outer name: parameter defaults and annotations, a comprehension's first iterable.
|
||||
for outer in evaluated_outside(n) {
|
||||
walk(outer, name, text, idx, out);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if n.kind() == "identifier" && text.get(n.byte_range()) == Some(name) {
|
||||
let field_of =
|
||||
|parent: Node, field: &str| parent.child_by_field_name(field).is_some_and(|c| c.id() == n.id());
|
||||
let excluded = n.parent().is_some_and(|parent| {
|
||||
(parent.kind() == "attribute" && field_of(parent, "attribute"))
|
||||
|| (parent.kind() == "keyword_argument" && field_of(parent, "name"))
|
||||
});
|
||||
if !excluded {
|
||||
out.push(idx.range(n.start_byte(), n.end_byte()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut c = n.walk();
|
||||
for child in n.children(&mut c) {
|
||||
walk(child, name, text, idx, out);
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(body, name, text, idx, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// The parts of a nested function, lambda or comprehension that run in the enclosing scope.
|
||||
fn evaluated_outside(n: Node) -> Vec<Node> {
|
||||
let mut out = Vec::new();
|
||||
if let Some(params) = n.child_by_field_name("parameters") {
|
||||
let mut c = params.walk();
|
||||
for p in params.named_children(&mut c) {
|
||||
out.extend(["value", "type"].iter().filter_map(|f| p.child_by_field_name(f)));
|
||||
}
|
||||
out.extend(n.child_by_field_name("return_type"));
|
||||
} else {
|
||||
let mut c = n.walk();
|
||||
let first = n.named_children(&mut c).find(|c| c.kind() == "for_in_clause");
|
||||
out.extend(first.and_then(|clause| clause.child_by_field_name("right")));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every name `body` uses (attribute and keyword argument names left out), nested scopes included.
|
||||
fn names_in(body: Node, text: &str, out: &mut Vec<String>) {
|
||||
let mut cursor = body.walk();
|
||||
visit(&mut cursor, &mut |n| {
|
||||
if n.kind() != "identifier" || text.get(n.byte_range()) != Some(name) {
|
||||
if n.kind() != "identifier" {
|
||||
return;
|
||||
}
|
||||
let field_of = |parent: Node, field: &str| parent.child_by_field_name(field).is_some_and(|c| c.id() == n.id());
|
||||
if let Some(parent) = n.parent()
|
||||
&& ((parent.kind() == "attribute" && field_of(parent, "attribute"))
|
||||
|| (parent.kind() == "keyword_argument" && field_of(parent, "name")))
|
||||
{
|
||||
return;
|
||||
let excluded = n.parent().is_some_and(|parent| {
|
||||
(parent.kind() == "attribute" && field_of(parent, "attribute"))
|
||||
|| (parent.kind() == "keyword_argument" && field_of(parent, "name"))
|
||||
});
|
||||
let name = text_of(n, text);
|
||||
if !excluded && !out.contains(&name) {
|
||||
out.push(name);
|
||||
}
|
||||
out.push(idx.range(n.start_byte(), n.end_byte()));
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// `from a.b import x, y as z` / `from . import *`.
|
||||
fn imports(statement: Node, text: &str, out: &mut Vec<PytestImport>) {
|
||||
let Some(module) = statement.child_by_field_name("module_name").map(|m| text_of(m, text)) else { return };
|
||||
let mut c = statement.walk();
|
||||
for child in statement.named_children(&mut c) {
|
||||
let (name, alias) = match child.kind() {
|
||||
"wildcard_import" => ("*".to_owned(), "*".to_owned()),
|
||||
"aliased_import" => match (child.child_by_field_name("name"), child.child_by_field_name("alias")) {
|
||||
(Some(n), Some(a)) => (text_of(n, text), text_of(a, text)),
|
||||
_ => continue,
|
||||
},
|
||||
"dotted_name"
|
||||
if child.start_byte() > statement.child_by_field_name("module_name").map_or(0, |m| m.end_byte()) =>
|
||||
{
|
||||
(text_of(child, text), text_of(child, text))
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
out.push(PytestImport { module: module.clone(), name, alias });
|
||||
}
|
||||
}
|
||||
|
||||
/// `Some(None)` for `@pytest.fixture` / `@fixture(...)`, `Some(Some((name, range)))` with a
|
||||
@@ -352,6 +501,7 @@ fn fixture_call(call: Node, text: &str, idx: &LineIndex, out: &mut PytestModule)
|
||||
class: class.clone(),
|
||||
in_fixture: None,
|
||||
body: Vec::new(),
|
||||
taken: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -546,6 +696,49 @@ class TestTasks:
|
||||
assert_eq!(m.definition_at(Pos::new(0, 6)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_scope_that_rebinds_the_name_keeps_its_own() {
|
||||
let m = module(concat!(
|
||||
"def test_a(tasks, other=1):\n",
|
||||
" done = [tasks for tasks in range(3)]\n",
|
||||
" f = lambda tasks: tasks\n",
|
||||
" def inner(tasks):\n",
|
||||
" return tasks\n",
|
||||
" def uses():\n",
|
||||
" return tasks\n",
|
||||
" return tasks\n",
|
||||
));
|
||||
let u = &m.uses[0];
|
||||
let reads: Vec<u32> = u.body.iter().map(|r| r.start.line).collect();
|
||||
assert_eq!(reads, [6, 7]);
|
||||
assert_eq!(u.taken[..2], ["tasks", "other"]);
|
||||
// Rename from a read in the body finds its parameter.
|
||||
let (found, range) = m.use_or_read_at(Pos::new(7, 12)).unwrap();
|
||||
assert_eq!((found.name.as_str(), range.start.line), ("tasks", 7));
|
||||
assert!(m.use_or_read_at(Pos::new(4, 16)).is_none(), "the nested function's own `tasks`");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_and_the_first_iterable_of_a_nested_scope_read_the_outer_name() {
|
||||
let m = module(concat!(
|
||||
"def test_a(tasks):\n",
|
||||
" def inner(tasks=tasks):\n",
|
||||
" return tasks\n",
|
||||
" f = lambda tasks=tasks: tasks\n",
|
||||
" return [tasks for tasks in tasks]\n",
|
||||
));
|
||||
let reads: Vec<(u32, u32)> = m.uses[0].body.iter().map(|r| (r.start.line, r.start.col)).collect();
|
||||
assert_eq!(reads, [(1, 20), (3, 21), (4, 31)]);
|
||||
assert!(m.uses[0].taken.iter().any(|n| n == "inner") && m.uses[0].taken.iter().any(|n| n == "f"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_imported_names() {
|
||||
let m = module("from tests.shared import item, other as alias\nfrom .local import *\nimport os\n");
|
||||
let imports: Vec<String> = m.imports.iter().map(|i| format!("{} {} {}", i.module, i.name, i.alias)).collect();
|
||||
assert_eq!(imports, ["tests.shared item item", "tests.shared other alias", ".local * *"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_definition_replaces_an_earlier_one() {
|
||||
let m = module("import pytest\n\n@pytest.fixture\ndef a():\n pass\n\n@pytest.fixture\ndef a():\n pass\n");
|
||||
|
||||
@@ -19,6 +19,10 @@ jupyter-zmq-client.workspace = true
|
||||
jupyter-protocol.workspace = true
|
||||
zeromq.workspace = true
|
||||
tempfile.workspace = true
|
||||
ide-http.workspace = true
|
||||
reqwest.workspace = true
|
||||
tokio-tungstenite.workspace = true
|
||||
futures.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! Output routing ends at the matching shell reply AND IOPub idle. Readers remain
|
||||
//! alive and drain later background output, but never attribute it to another run.
|
||||
|
||||
pub mod debug;
|
||||
mod process;
|
||||
mod transport;
|
||||
|
||||
@@ -14,9 +15,53 @@ use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Mutex as AsyncMutex;
|
||||
|
||||
/// A read of the variables running longer is interrupted. Its kernel is kept even if it does
|
||||
/// not drain; an Interrupt then stops it like a run.
|
||||
const READ_LIMIT: Duration = Duration::from_secs(5);
|
||||
|
||||
pub use transport::remote::{KernelSpec, kernel_specs, normalize_server_url};
|
||||
|
||||
/// Where a notebook's kernel runs.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub enum KernelTarget {
|
||||
/// A kernel the IDE starts from this Python interpreter.
|
||||
Local(PathBuf),
|
||||
/// A kernel started on a Jupyter server.
|
||||
Remote(RemoteKernel),
|
||||
}
|
||||
|
||||
/// A kernel spec on a Jupyter server, and the token to reach it.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct RemoteKernel {
|
||||
/// The server's base URL, ending in `/` (see [`normalize_server_url`]).
|
||||
pub base: String,
|
||||
pub token: String,
|
||||
pub spec: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RemoteKernel {
|
||||
// Leaves out the token.
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("RemoteKernel").field("base", &self.base).field("spec", &self.spec).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Path> for KernelTarget {
|
||||
fn from(python: &Path) -> Self {
|
||||
Self::Local(python.to_path_buf())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&PathBuf> for KernelTarget {
|
||||
fn from(python: &PathBuf) -> Self {
|
||||
Self::Local(python.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) type StatusCallback = Arc<dyn Fn(&Path, KernelState, Option<String>) + Send + Sync>;
|
||||
pub(super) type OutputCallback = Arc<dyn Fn(KernelOutput) + Send + Sync>;
|
||||
|
||||
@@ -65,8 +110,13 @@ struct Slot {
|
||||
interrupt: Mutex<Option<CancellationToken>>,
|
||||
stop: Mutex<Option<CancellationToken>>,
|
||||
closed: AtomicBool,
|
||||
/// A silent inspection holds `operation`; a run waits for it instead of failing as busy.
|
||||
inspecting: AtomicBool,
|
||||
/// Inspections in flight. One holds `operation`; a run waits for it instead of failing as busy.
|
||||
inspecting: AtomicUsize,
|
||||
/// Interrupts the inspection holding `operation`.
|
||||
inspection: Mutex<Option<CancellationToken>>,
|
||||
/// Counts `cancel()` calls, so an inspection sees one that came before its token was set.
|
||||
interrupts: AtomicUsize,
|
||||
debug: transport::DebugPort,
|
||||
}
|
||||
|
||||
impl Slot {
|
||||
@@ -76,14 +126,22 @@ impl Slot {
|
||||
interrupt: Mutex::new(None),
|
||||
stop: Mutex::new(None),
|
||||
closed: AtomicBool::new(false),
|
||||
inspecting: AtomicBool::new(false),
|
||||
inspecting: AtomicUsize::new(0),
|
||||
inspection: Mutex::new(None),
|
||||
interrupts: AtomicUsize::new(0),
|
||||
debug: transport::DebugPort::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel(&self) {
|
||||
self.interrupts.fetch_add(1, Ordering::SeqCst);
|
||||
if let Some(token) = self.interrupt.lock().as_ref() {
|
||||
token.cancel();
|
||||
}
|
||||
// A run waiting behind a stuck inspection is interrupted through it.
|
||||
if let Some(token) = self.inspection.lock().as_ref() {
|
||||
token.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
fn stop(&self) {
|
||||
@@ -106,7 +164,7 @@ impl Drop for ActiveExecution<'_> {
|
||||
struct Inspecting<'a>(&'a Slot);
|
||||
impl Drop for Inspecting<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.inspecting.store(false, Ordering::Release);
|
||||
self.0.inspecting.fetch_sub(1, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,11 +183,12 @@ impl KernelManager {
|
||||
pub async fn execute(
|
||||
&self,
|
||||
notebook: &Path,
|
||||
python: &Path,
|
||||
target: impl Into<KernelTarget>,
|
||||
code: &str,
|
||||
cancel: CancellationToken,
|
||||
on_output: OutputCallback,
|
||||
) -> IdeResult<ExecutionResult> {
|
||||
let target = target.into();
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
@@ -154,13 +213,13 @@ impl KernelManager {
|
||||
// A second caller must not sit in a queue and execute stale source later.
|
||||
let mut running = match slot.operation.try_lock() {
|
||||
Ok(running) => running,
|
||||
Err(_) if slot.inspecting.load(Ordering::Acquire) => slot.operation.lock().await,
|
||||
Err(_) if slot.inspecting.load(Ordering::Acquire) > 0 => slot.operation.lock().await,
|
||||
Err(_) => return Err(IdeError::unavailable("notebook kernel is busy")),
|
||||
};
|
||||
if slot.closed.load(Ordering::Acquire) {
|
||||
return Err(IdeError::unavailable("notebook kernel was closed"));
|
||||
}
|
||||
if running.as_ref().is_some_and(|r| r.python != python || r.is_finished())
|
||||
if running.as_ref().is_some_and(|r| r.target != target || r.is_finished())
|
||||
&& let Some(old) = running.take()
|
||||
{
|
||||
old.shutdown().await;
|
||||
@@ -172,8 +231,9 @@ impl KernelManager {
|
||||
let (new, ready) = transport::Running::spawn(
|
||||
self.runtime_dir.clone(),
|
||||
notebook.to_path_buf(),
|
||||
python.to_path_buf(),
|
||||
target,
|
||||
self.on_status.clone(),
|
||||
slot.debug.clone(),
|
||||
);
|
||||
*slot.stop.lock() = Some(new.stop.clone());
|
||||
*running = Some(new);
|
||||
@@ -218,27 +278,48 @@ impl KernelManager {
|
||||
if slot.interrupt.lock().is_some() {
|
||||
return Err(IdeError::unavailable("notebook kernel is busy"));
|
||||
}
|
||||
// Flagged before locking, so a run arriving meanwhile waits rather than failing.
|
||||
slot.inspecting.store(true, Ordering::Release);
|
||||
let interrupts = slot.interrupts.load(Ordering::SeqCst);
|
||||
// Counted before locking, so a run arriving meanwhile waits rather than failing.
|
||||
slot.inspecting.fetch_add(1, Ordering::AcqRel);
|
||||
let _inspecting = Inspecting(&slot);
|
||||
let running = slot.operation.try_lock().map_err(|_| IdeError::unavailable("notebook kernel is busy"))?;
|
||||
let Some(kernel) = running.as_ref().filter(|r| !r.is_finished() && !slot.closed.load(Ordering::Acquire)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
// A fixed bound; a wedged `__repr__` is interrupted when the reply is dropped.
|
||||
let result = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(10),
|
||||
kernel.execute(
|
||||
code,
|
||||
Some(expressions),
|
||||
CancellationToken::new(),
|
||||
CancellationToken::new(),
|
||||
Arc::new(|_| {}),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| IdeError::unavailable("kernel did not answer within 10 seconds"))??;
|
||||
Ok(result.user_expressions)
|
||||
// Interrupt, restart and close reach it through `inspection` and the stop token.
|
||||
let interrupt = CancellationToken::new();
|
||||
*slot.inspection.lock() = Some(interrupt.clone());
|
||||
if slot.interrupts.load(Ordering::SeqCst) != interrupts {
|
||||
interrupt.cancel();
|
||||
}
|
||||
// Interrupted at the limit, never dropped: the waiting run needs the kernel drained.
|
||||
let limit = CancellationToken::new();
|
||||
let timer = tokio::spawn({
|
||||
let limit = limit.clone();
|
||||
async move {
|
||||
tokio::time::sleep(READ_LIMIT).await;
|
||||
limit.cancel();
|
||||
}
|
||||
});
|
||||
let result = kernel.execute(code, Some(expressions), limit, interrupt, Arc::new(|_| {})).await;
|
||||
timer.abort();
|
||||
slot.inspection.lock().take();
|
||||
Ok(result?.user_expressions)
|
||||
}
|
||||
|
||||
/// Starts `target` for the notebook, or replaces a kernel of another target; a kernel
|
||||
/// already running for `target` is kept.
|
||||
pub async fn start(&self, notebook: &Path, target: impl Into<KernelTarget>) -> IdeResult<()> {
|
||||
self.execute(notebook, target, "", CancellationToken::new(), Arc::new(|_| {})).await.map(|_| ())
|
||||
}
|
||||
|
||||
/// Opens the debugger of the notebook's running kernel. One session at a time; it ends
|
||||
/// when the returned value is dropped or the kernel stops.
|
||||
pub fn debugger(&self, notebook: &Path) -> IdeResult<KernelDebugger> {
|
||||
let slot = self.slots.lock().get(notebook).cloned();
|
||||
let slot = slot.ok_or_else(|| IdeError::unavailable("the notebook's kernel is not running"))?;
|
||||
let (control, inbox) = slot.debug.open()?;
|
||||
Ok(KernelDebugger { control, inbox })
|
||||
}
|
||||
|
||||
/// Cancels the active request, including startup. The execution future drains
|
||||
@@ -246,6 +327,8 @@ impl KernelManager {
|
||||
pub async fn interrupt(&self, notebook: &Path) -> IdeResult<()> {
|
||||
let slot = self.slots.lock().get(notebook).cloned();
|
||||
if let Some(slot) = slot {
|
||||
// A run paused at a breakpoint goes on first; paused, it would not answer in time.
|
||||
slot.debug.release().await;
|
||||
slot.cancel();
|
||||
// Wait for native interrupt delivery/drain, not just token mutation.
|
||||
let _drained = slot.operation.lock().await;
|
||||
@@ -262,10 +345,15 @@ impl KernelManager {
|
||||
return Err(IdeError::unavailable("notebook kernel was closed"));
|
||||
}
|
||||
let Some(old) = running.take() else { return Ok(()) };
|
||||
let python = old.python.clone();
|
||||
let target = old.target.clone();
|
||||
old.shutdown().await;
|
||||
let (new, ready) =
|
||||
transport::Running::spawn(self.runtime_dir.clone(), notebook.to_path_buf(), python, self.on_status.clone());
|
||||
let (new, ready) = transport::Running::spawn(
|
||||
self.runtime_dir.clone(),
|
||||
notebook.to_path_buf(),
|
||||
target,
|
||||
self.on_status.clone(),
|
||||
slot.debug.clone(),
|
||||
);
|
||||
*slot.stop.lock() = Some(new.stop.clone());
|
||||
*running = Some(new);
|
||||
if slot.closed.load(Ordering::Acquire) {
|
||||
@@ -336,3 +424,26 @@ impl Drop for KernelManager {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A debug session on a notebook's kernel, in the Jupyter debugger protocol: DAP requests
|
||||
/// go out as `debug_request`, DAP responses and events come back.
|
||||
pub struct KernelDebugger {
|
||||
control: tokio::sync::mpsc::Sender<jupyter_protocol::JupyterMessage>,
|
||||
inbox: tokio::sync::mpsc::UnboundedReceiver<Value>,
|
||||
}
|
||||
|
||||
impl KernelDebugger {
|
||||
/// Sends a DAP request.
|
||||
pub async fn send(&self, request: Value) -> IdeResult<()> {
|
||||
let message: jupyter_protocol::JupyterMessage = jupyter_protocol::DebugRequest { content: request }.into();
|
||||
self.control.send(message).await.map_err(|_| IdeError::unavailable("the notebook's kernel stopped"))
|
||||
}
|
||||
|
||||
/// The next DAP response or event; `None` once the kernel stopped.
|
||||
pub async fn receive(&mut self) -> Option<Value> {
|
||||
tokio::select! {
|
||||
message = self.inbox.recv() => message,
|
||||
() = self.control.closed() => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
//! A notebook kernel's debugger as a DAP stream, for the IDE's DAP client.
|
||||
//!
|
||||
//! The kernel compiles each cell's code as a file of its own (`<tmp>/<hash of the code>.py`).
|
||||
//! Once the debugger starts, every cell's code is sent with `dumpCell`, which writes that file
|
||||
//! and names it. Paths are then rewritten both ways: the IDE's cell URIs to the kernel's files
|
||||
//! in requests, the kernel's files to cell URIs in responses and events.
|
||||
|
||||
use super::KernelDebugger;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader, DuplexStream};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
/// DAP messages larger than this end the session (a kernel reply is far smaller).
|
||||
const MAX_MESSAGE_BYTES: usize = 16 * 1024 * 1024;
|
||||
/// Sequence numbers of the bridge's own requests, above any the IDE uses.
|
||||
const OWN_SEQ: i64 = 1 << 40;
|
||||
use super::transport::CANNOT_DEBUG;
|
||||
/// A kernel that has a debugger but could not start it (debugpy failed).
|
||||
const NOT_STARTED: &str = "the kernel could not start its debugger (debugpy)";
|
||||
|
||||
/// Starts the bridge; the IDE reads and writes DAP on the returned stream. `cells` gives the
|
||||
/// notebook's code cells as they are now, as (URI, source). Closing the stream disconnects the
|
||||
/// debugger, which leaves the kernel and its state running.
|
||||
pub fn dap_stream(
|
||||
debugger: KernelDebugger,
|
||||
cells: impl Fn() -> Vec<(String, String)> + Send + 'static,
|
||||
) -> DuplexStream {
|
||||
let (ide, ours) = tokio::io::duplex(1 << 16);
|
||||
tokio::spawn(bridge(debugger, cells, ours));
|
||||
ide
|
||||
}
|
||||
|
||||
/// What to do with a request of the IDE.
|
||||
enum Next {
|
||||
Send(Value),
|
||||
/// Answered here, without the kernel.
|
||||
Reply(Value),
|
||||
/// The cell's current code must be dumped first; the request waits.
|
||||
Dump {
|
||||
uri: String,
|
||||
code: String,
|
||||
request: Value,
|
||||
},
|
||||
}
|
||||
|
||||
async fn bridge(mut debugger: KernelDebugger, cells: impl Fn() -> Vec<(String, String)>, stream: DuplexStream) {
|
||||
let (read, mut write) = tokio::io::split(stream);
|
||||
let (requests, mut from_ide) = mpsc::channel::<Value>(64);
|
||||
let reader = tokio::spawn(async move {
|
||||
let mut read = BufReader::new(read);
|
||||
while let Ok(Some(message)) = read_message(&mut read).await {
|
||||
if requests.send(message).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut map = PathMap::default();
|
||||
// The bridge's dumpCell requests in flight, by seq; the IDE's requests wait for them.
|
||||
let mut dumping: HashMap<i64, (String, String)> = HashMap::new();
|
||||
let mut held: VecDeque<Value> = VecDeque::new();
|
||||
let mut seq = OWN_SEQ;
|
||||
let mut disconnected = false;
|
||||
// The IDE's requests the kernel has not answered yet, in order: the control channel
|
||||
// answers them in turn, and a kernel without debugpy answers with no message at all.
|
||||
let mut unanswered: VecDeque<(Value, Value)> = VecDeque::new();
|
||||
'session: loop {
|
||||
// The IDE's requests that wait for no dump, in order.
|
||||
while dumping.is_empty()
|
||||
&& let Some(request) = held.pop_front()
|
||||
{
|
||||
match prepare(request, &map, &cells) {
|
||||
Next::Send(request) => {
|
||||
unanswered.push_back((request["seq"].clone(), request["command"].clone()));
|
||||
if debugger.send(request).await.is_err() {
|
||||
break 'session;
|
||||
}
|
||||
}
|
||||
Next::Reply(reply) => {
|
||||
if write_message(&mut write, &reply).await.is_err() {
|
||||
break 'session;
|
||||
}
|
||||
}
|
||||
Next::Dump { uri, code, request } => {
|
||||
seq += 1;
|
||||
let dump =
|
||||
json!({"type": "request", "seq": seq, "command": "dumpCell", "arguments": {"code": code}});
|
||||
dumping.insert(seq, (uri, code));
|
||||
held.push_front(request);
|
||||
if debugger.send(dump).await.is_err() {
|
||||
break 'session;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tokio::select! {
|
||||
request = from_ide.recv() => {
|
||||
let Some(mut request) = request else { break };
|
||||
// Never end the kernel: it is the notebook's, not the debug session's.
|
||||
if request["command"] == "terminate" {
|
||||
let reply = json!({"type": "response", "request_seq": request["seq"], "command": "terminate", "success": true});
|
||||
if write_message(&mut write, &reply).await.is_err() {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if request["command"] == "disconnect" {
|
||||
disconnected = true;
|
||||
request["arguments"]["terminateDebuggee"] = json!(false);
|
||||
}
|
||||
held.push_back(request);
|
||||
}
|
||||
message = debugger.receive() => {
|
||||
let Some(mut message) = message else { break };
|
||||
if message["type"] == "response"
|
||||
&& let Some((uri, code)) = message["request_seq"].as_i64().and_then(|seq| dumping.remove(&seq))
|
||||
{
|
||||
if let Some(path) = message["body"]["sourcePath"].as_str() {
|
||||
map.insert(uri, code, path.to_owned());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if message.get("type").is_none() {
|
||||
let Some((seq, command)) = unanswered.pop_front() else { continue };
|
||||
message = json!({"type": "response", "request_seq": seq, "command": command,
|
||||
"success": false, "message": CANNOT_DEBUG});
|
||||
} else if message["type"] == "response" {
|
||||
unanswered.retain(|(seq, _)| *seq != message["request_seq"]);
|
||||
}
|
||||
// The kernel starts its debugger on `initialize`: then the cells can be dumped.
|
||||
let initialize = message["type"] == "response" && message["command"] == "initialize";
|
||||
let started = initialize && message["success"] == true;
|
||||
if initialize && !started && message.get("message").is_none() {
|
||||
message["message"] = json!(NOT_STARTED);
|
||||
}
|
||||
map.to_ide(&mut message);
|
||||
if write_message(&mut write, &message).await.is_err() {
|
||||
break;
|
||||
}
|
||||
if started {
|
||||
for (uri, code) in cells() {
|
||||
seq += 1;
|
||||
let dump = json!({"type": "request", "seq": seq, "command": "dumpCell", "arguments": {"code": code}});
|
||||
dumping.insert(seq, (uri, code));
|
||||
let _ = debugger.send(dump).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
reader.abort();
|
||||
// Breakpoints left behind would stop later runs with no one to continue them.
|
||||
if !disconnected {
|
||||
let disconnect = json!({"type": "request", "seq": seq + 1, "command": "disconnect",
|
||||
"arguments": {"restart": false, "terminateDebuggee": false}});
|
||||
let _ = debugger.send(disconnect).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A cell's breakpoints go to the file of the cell's current code, dumped again when the code
|
||||
/// changed (or the cell is new) since the last dump.
|
||||
fn prepare(mut request: Value, map: &PathMap, cells: &impl Fn() -> Vec<(String, String)>) -> Next {
|
||||
let uri = request["arguments"]["source"]["path"].as_str().filter(|path| path.starts_with(CELL_SCHEME));
|
||||
if request["command"] != "setBreakpoints" || uri.is_none() {
|
||||
map.to_kernel(&mut request);
|
||||
return Next::Send(request);
|
||||
}
|
||||
let uri = uri.unwrap_or_default().to_owned();
|
||||
let Some(code) = cells().into_iter().find(|(cell, _)| *cell == uri).map(|(_, code)| code) else {
|
||||
return Next::Reply(unverified(&request, "not a code cell of this notebook"));
|
||||
};
|
||||
match map.cells.get(&uri) {
|
||||
Some((dumped, path)) if *dumped == code => {
|
||||
if map.files.get(path) != Some(&uri) {
|
||||
return Next::Reply(unverified(&request, "another cell has the same code: set the breakpoint there"));
|
||||
}
|
||||
map.to_kernel(&mut request);
|
||||
Next::Send(request)
|
||||
}
|
||||
_ => Next::Dump { uri, code, request },
|
||||
}
|
||||
}
|
||||
|
||||
/// A `setBreakpoints` response with each of `request`'s breakpoints unverified for `reason`.
|
||||
fn unverified(request: &Value, reason: &str) -> Value {
|
||||
let breakpoints: Vec<Value> = request["arguments"]["breakpoints"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|breakpoint| json!({"verified": false, "line": breakpoint["line"], "message": reason}))
|
||||
.collect();
|
||||
json!({"type": "response", "request_seq": request["seq"], "command": request["command"], "success": true,
|
||||
"body": {"breakpoints": breakpoints}})
|
||||
}
|
||||
|
||||
const CELL_SCHEME: &str = "vscode-notebook-cell:";
|
||||
|
||||
/// Cell URIs and the kernel's files for their code. Cells with the same code share a file;
|
||||
/// it maps back to the first of them.
|
||||
#[derive(Default)]
|
||||
struct PathMap {
|
||||
/// By cell URI: the code dumped and its file.
|
||||
cells: HashMap<String, (String, String)>,
|
||||
/// By file: its cell.
|
||||
files: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl PathMap {
|
||||
fn insert(&mut self, uri: String, code: String, path: String) {
|
||||
if let Some((_, old)) = self.cells.get(&uri)
|
||||
&& self.files.get(old) == Some(&uri)
|
||||
{
|
||||
self.files.remove(&old.clone());
|
||||
}
|
||||
self.files.entry(path.clone()).or_insert_with(|| uri.clone());
|
||||
self.cells.insert(uri, (code, path));
|
||||
}
|
||||
|
||||
fn to_kernel(&self, message: &mut Value) {
|
||||
rewrite(message, &|path| self.cells.get(path).map(|(_, file)| file.clone()));
|
||||
}
|
||||
|
||||
fn to_ide(&self, message: &mut Value) {
|
||||
rewrite(message, &|path| self.files.get(path).cloned());
|
||||
}
|
||||
}
|
||||
|
||||
/// Rewrites the `path` of every `source` object in `value`.
|
||||
fn rewrite(value: &mut Value, paths: &dyn Fn(&str) -> Option<String>) {
|
||||
match value {
|
||||
Value::Object(object) => {
|
||||
if let Some(Value::Object(source)) = object.get_mut("source")
|
||||
&& let Some(mapped) = source.get("path").and_then(Value::as_str).and_then(paths)
|
||||
{
|
||||
source.insert("path".into(), Value::String(mapped));
|
||||
// The kernel's name is its file's (`908337371.py`); the IDE names the cell.
|
||||
source.remove("name");
|
||||
}
|
||||
object.values_mut().for_each(|value| rewrite(value, paths));
|
||||
}
|
||||
Value::Array(values) => values.iter_mut().for_each(|value| rewrite(value, paths)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_message<R: AsyncReadExt + AsyncBufReadExt + Unpin>(read: &mut R) -> std::io::Result<Option<Value>> {
|
||||
let mut length = None;
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
if read.read_line(&mut line).await? == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let line = line.trim_end();
|
||||
if line.is_empty() {
|
||||
break;
|
||||
}
|
||||
if let Some((name, value)) = line.split_once(':')
|
||||
&& name.eq_ignore_ascii_case("content-length")
|
||||
{
|
||||
length = value.trim().parse::<usize>().ok();
|
||||
}
|
||||
}
|
||||
let length = length.filter(|length| *length <= MAX_MESSAGE_BYTES).ok_or_else(|| {
|
||||
std::io::Error::new(std::io::ErrorKind::InvalidData, "DAP message without a valid Content-Length")
|
||||
})?;
|
||||
let mut body = vec![0; length];
|
||||
read.read_exact(&mut body).await?;
|
||||
serde_json::from_slice(&body).map(Some).map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
|
||||
}
|
||||
|
||||
async fn write_message<W: AsyncWriteExt + Unpin>(write: &mut W, message: &Value) -> std::io::Result<()> {
|
||||
let body = message.to_string();
|
||||
write.write_all(format!("Content-Length: {}\r\n\r\n", body.len()).as_bytes()).await?;
|
||||
write.write_all(body.as_bytes()).await?;
|
||||
write.flush().await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn paths_are_rewritten_in_every_source() {
|
||||
let mut map = PathMap::default();
|
||||
map.insert("vscode-notebook-cell:/p/a.ipynb#c1".into(), "x = 1".into(), "/tmp/ipykernel_1/123.py".into());
|
||||
let mut request = json!({"command": "setBreakpoints", "arguments": {
|
||||
"source": {"path": "vscode-notebook-cell:/p/a.ipynb#c1", "name": "a.ipynb#c1"}, "breakpoints": [{"line": 2}]}});
|
||||
map.to_kernel(&mut request);
|
||||
assert_eq!(request["arguments"]["source"], json!({"path": "/tmp/ipykernel_1/123.py"}));
|
||||
let mut frames = json!({"body": {"stackFrames": [
|
||||
{"name": "f", "line": 2, "source": {"path": "/tmp/ipykernel_1/123.py", "name": "123.py"}},
|
||||
{"name": "g", "line": 9, "source": {"path": "/work/lib.py", "name": "lib.py"}}]}});
|
||||
map.to_ide(&mut frames);
|
||||
assert_eq!(frames["body"]["stackFrames"][0]["source"], json!({"path": "vscode-notebook-cell:/p/a.ipynb#c1"}));
|
||||
assert_eq!(frames["body"]["stackFrames"][1]["source"]["path"], "/work/lib.py", "other files are left alone");
|
||||
}
|
||||
|
||||
/// A bridge over a stand-in kernel: what it is sent, and a way to answer.
|
||||
fn fake(
|
||||
cells: Vec<(String, String)>,
|
||||
) -> (DuplexStream, mpsc::Receiver<jupyter_protocol::JupyterMessage>, mpsc::UnboundedSender<Value>) {
|
||||
let (control, sent) = mpsc::channel(16);
|
||||
let (answer, inbox) = mpsc::unbounded_channel();
|
||||
(dap_stream(KernelDebugger { control, inbox }, move || cells.clone()), sent, answer)
|
||||
}
|
||||
|
||||
fn content(message: jupyter_protocol::JupyterMessage) -> Value {
|
||||
match message.content {
|
||||
jupyter_protocol::JupyterMessageContent::DebugRequest(request) => request.content,
|
||||
other => panic!("not a debug request: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_kernel_without_debugpy_fails_initialize_with_a_reason() {
|
||||
let (stream, mut sent, answer) = fake(Vec::new());
|
||||
let (read, mut write) = tokio::io::split(stream);
|
||||
let mut read = BufReader::new(read);
|
||||
write_message(&mut write, &json!({"type": "request", "seq": 1, "command": "initialize", "arguments": {}}))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(content(sent.recv().await.unwrap())["command"], "initialize");
|
||||
answer.send(Value::Null).unwrap();
|
||||
let reply = read_message(&mut read).await.unwrap().unwrap();
|
||||
assert_eq!(reply["request_seq"], 1);
|
||||
assert_eq!(reply["success"], false);
|
||||
assert_eq!(reply["message"], CANNOT_DEBUG);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn breakpoints_wait_for_the_cells_to_be_dumped() {
|
||||
let uri = "vscode-notebook-cell:/p/a.ipynb#c1";
|
||||
let (stream, mut sent, answer) = fake(vec![(uri.into(), "x = 1\n".into())]);
|
||||
let (read, mut write) = tokio::io::split(stream);
|
||||
let mut read = BufReader::new(read);
|
||||
write_message(&mut write, &json!({"type": "request", "seq": 1, "command": "initialize", "arguments": {}}))
|
||||
.await
|
||||
.unwrap();
|
||||
sent.recv().await.unwrap();
|
||||
answer.send(json!({"type": "response", "request_seq": 1, "command": "initialize", "success": true})).unwrap();
|
||||
assert_eq!(read_message(&mut read).await.unwrap().unwrap()["success"], true);
|
||||
let dump = content(sent.recv().await.unwrap());
|
||||
assert_eq!((dump["command"].as_str(), dump["arguments"]["code"].as_str()), (Some("dumpCell"), Some("x = 1\n")));
|
||||
// Sent before the dump is answered: held, then sent with the kernel's path.
|
||||
let set = json!({"type": "request", "seq": 2, "command": "setBreakpoints",
|
||||
"arguments": {"source": {"path": uri}, "breakpoints": [{"line": 1}]}});
|
||||
write_message(&mut write, &set).await.unwrap();
|
||||
tokio::task::yield_now().await;
|
||||
assert!(sent.try_recv().is_err());
|
||||
answer
|
||||
.send(json!({"type": "response", "request_seq": dump["seq"], "command": "dumpCell", "success": true,
|
||||
"body": {"sourcePath": "/tmp/k/1.py"}}))
|
||||
.unwrap();
|
||||
let set = content(sent.recv().await.unwrap());
|
||||
assert_eq!(set["arguments"]["source"]["path"], "/tmp/k/1.py");
|
||||
// Dropping the IDE's side disconnects the kernel's debugger.
|
||||
drop((read, write));
|
||||
let disconnect = content(sent.recv().await.unwrap());
|
||||
assert_eq!(
|
||||
(disconnect["command"].as_str(), disconnect["arguments"]["terminateDebuggee"].as_bool()),
|
||||
(Some("disconnect"), Some(false))
|
||||
);
|
||||
}
|
||||
|
||||
/// Starts a bridge over `cells` and answers `initialize` and the first dumps (`/tmp/k/<n>.py`).
|
||||
async fn started(
|
||||
cells: std::sync::Arc<parking_lot::Mutex<Vec<(String, String)>>>,
|
||||
) -> (
|
||||
BufReader<tokio::io::ReadHalf<DuplexStream>>,
|
||||
tokio::io::WriteHalf<DuplexStream>,
|
||||
mpsc::Receiver<jupyter_protocol::JupyterMessage>,
|
||||
mpsc::UnboundedSender<Value>,
|
||||
) {
|
||||
let (control, mut sent) = mpsc::channel(16);
|
||||
let (answer, inbox) = mpsc::unbounded_channel();
|
||||
let current = cells.clone();
|
||||
let stream = dap_stream(KernelDebugger { control, inbox }, move || current.lock().clone());
|
||||
let (read, mut write) = tokio::io::split(stream);
|
||||
let mut read = BufReader::new(read);
|
||||
write_message(&mut write, &json!({"type": "request", "seq": 1, "command": "initialize", "arguments": {}}))
|
||||
.await
|
||||
.unwrap();
|
||||
sent.recv().await.unwrap();
|
||||
answer.send(json!({"type": "response", "request_seq": 1, "command": "initialize", "success": true})).unwrap();
|
||||
read_message(&mut read).await.unwrap().unwrap();
|
||||
let count = cells.lock().len();
|
||||
for _ in 0..count {
|
||||
answer_dump(&mut sent, &answer).await;
|
||||
}
|
||||
(read, write, sent, answer)
|
||||
}
|
||||
|
||||
/// Answers the next request, a dumpCell, with a file named by its code's length.
|
||||
async fn answer_dump(
|
||||
sent: &mut mpsc::Receiver<jupyter_protocol::JupyterMessage>,
|
||||
answer: &mpsc::UnboundedSender<Value>,
|
||||
) {
|
||||
let dump = content(sent.recv().await.unwrap());
|
||||
assert_eq!(dump["command"], "dumpCell");
|
||||
let path = format!("/tmp/k/{}.py", dump["arguments"]["code"].as_str().unwrap().len());
|
||||
answer
|
||||
.send(json!({"type": "response", "request_seq": dump["seq"], "command": "dumpCell", "success": true,
|
||||
"body": {"sourcePath": path}}))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn set(seq: i64, uri: &str) -> Value {
|
||||
json!({"type": "request", "seq": seq, "command": "setBreakpoints",
|
||||
"arguments": {"source": {"path": uri}, "breakpoints": [{"line": 1}]}})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cells_edited_or_added_during_the_session_are_dumped_again() {
|
||||
let (a, b) = ("vscode-notebook-cell:/p/a.ipynb#a", "vscode-notebook-cell:/p/a.ipynb#b");
|
||||
let cells = std::sync::Arc::new(parking_lot::Mutex::new(vec![(a.to_owned(), "x = 1".to_owned())]));
|
||||
let (_read, mut write, mut sent, answer) = started(cells.clone()).await;
|
||||
// Unchanged: straight to the kernel.
|
||||
write_message(&mut write, &set(2, a)).await.unwrap();
|
||||
assert_eq!(content(sent.recv().await.unwrap())["arguments"]["source"]["path"], "/tmp/k/5.py");
|
||||
// Edited, and a new cell: dumped again first.
|
||||
cells.lock()[0].1 = "x = 100".into();
|
||||
cells.lock().push((b.to_owned(), "y".to_owned()));
|
||||
write_message(&mut write, &set(3, a)).await.unwrap();
|
||||
answer_dump(&mut sent, &answer).await;
|
||||
assert_eq!(content(sent.recv().await.unwrap())["arguments"]["source"]["path"], "/tmp/k/7.py");
|
||||
write_message(&mut write, &set(4, b)).await.unwrap();
|
||||
answer_dump(&mut sent, &answer).await;
|
||||
assert_eq!(content(sent.recv().await.unwrap())["arguments"]["source"]["path"], "/tmp/k/1.py");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_cell_with_another_cells_code_says_so() {
|
||||
let (a, b, gone) = (
|
||||
"vscode-notebook-cell:/p/a.ipynb#a",
|
||||
"vscode-notebook-cell:/p/a.ipynb#b",
|
||||
"vscode-notebook-cell:/p/a.ipynb#gone",
|
||||
);
|
||||
let cells = std::sync::Arc::new(parking_lot::Mutex::new(vec![
|
||||
(a.to_owned(), "x = 1".to_owned()),
|
||||
(b.to_owned(), "x = 1".to_owned()),
|
||||
]));
|
||||
let (mut read, mut write, mut sent, _answer) = started(cells).await;
|
||||
write_message(&mut write, &set(2, b)).await.unwrap();
|
||||
let reply = read_message(&mut read).await.unwrap().unwrap();
|
||||
assert_eq!(reply["request_seq"], 2);
|
||||
assert_eq!(reply["body"]["breakpoints"][0]["verified"], false);
|
||||
assert!(reply["body"]["breakpoints"][0]["message"].as_str().unwrap().contains("same code"));
|
||||
write_message(&mut write, &set(3, gone)).await.unwrap();
|
||||
let reply = read_message(&mut read).await.unwrap().unwrap();
|
||||
assert_eq!(
|
||||
(reply["request_seq"].as_i64(), reply["body"]["breakpoints"][0]["verified"].as_bool()),
|
||||
(Some(3), Some(false))
|
||||
);
|
||||
// The first of the two keeps the file.
|
||||
write_message(&mut write, &set(4, a)).await.unwrap();
|
||||
assert_eq!(content(sent.recv().await.unwrap())["arguments"]["source"]["path"], "/tmp/k/5.py");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dap_frames_round_trip() {
|
||||
let (a, b) = tokio::io::duplex(1024);
|
||||
let (_, mut write) = tokio::io::split(a);
|
||||
let (read, _) = tokio::io::split(b);
|
||||
let mut read = BufReader::new(read);
|
||||
write_message(&mut write, &json!({"seq": 1, "type": "request", "command": "initialize"})).await.unwrap();
|
||||
write_message(&mut write, &json!({"seq": 2, "text": "ünïcode"})).await.unwrap();
|
||||
assert_eq!(read_message(&mut read).await.unwrap().unwrap()["command"], "initialize");
|
||||
assert_eq!(read_message(&mut read).await.unwrap().unwrap()["text"], "ünïcode");
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
use super::process::Process;
|
||||
use super::{ExecutionResult, KernelOutput, KernelState, OutputCallback, StatusCallback};
|
||||
use super::{ExecutionResult, KernelOutput, KernelState, KernelTarget, OutputCallback, StatusCallback};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use jupyter_protocol::{ExecuteRequest, JupyterMessage, KernelInfoRequest, ShutdownRequest};
|
||||
use jupyter_zmq_client::{ClientControlConnection, Connection, DealerSendConnection, RawMessage};
|
||||
use jupyter_zmq_client::{Connection, DealerSendConnection, RawMessage};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::Value;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
@@ -16,7 +16,11 @@ use tokio::time::{Instant, MissedTickBehavior};
|
||||
use uuid::Uuid;
|
||||
use zeromq::SocketRecv;
|
||||
|
||||
pub(crate) mod remote;
|
||||
|
||||
const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
/// A heavy kernel on a shared server (a JupyterHub) can take longer.
|
||||
const REMOTE_STARTUP_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
const INTERRUPT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const SEND_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
const MAX_MESSAGE_BYTES: usize = 8 * 1024 * 1024;
|
||||
@@ -44,7 +48,7 @@ struct Execution {
|
||||
}
|
||||
|
||||
pub(super) struct Running {
|
||||
pub python: PathBuf,
|
||||
pub target: KernelTarget,
|
||||
pub stop: CancellationToken,
|
||||
requests: mpsc::Sender<Execution>,
|
||||
task: Option<JoinHandle<()>>,
|
||||
@@ -55,14 +59,16 @@ impl Running {
|
||||
pub fn spawn(
|
||||
runtime: PathBuf,
|
||||
notebook: PathBuf,
|
||||
python: PathBuf,
|
||||
target: KernelTarget,
|
||||
status: StatusCallback,
|
||||
debug: DebugPort,
|
||||
) -> (Self, oneshot::Receiver<IdeResult<()>>) {
|
||||
let stop = CancellationToken::new();
|
||||
let (requests, receiver) = mpsc::channel(1);
|
||||
let (ready, ready_rx) = oneshot::channel();
|
||||
let task = tokio::spawn(supervise(runtime, notebook, python.clone(), status, stop.clone(), receiver, ready));
|
||||
(Self { python, stop, requests, task: Some(task), busy: Arc::new(AtomicBool::new(false)) }, ready_rx)
|
||||
let task =
|
||||
tokio::spawn(supervise(runtime, notebook, target.clone(), status, stop.clone(), receiver, ready, debug));
|
||||
(Self { target, stop, requests, task: Some(task), busy: Arc::new(AtomicBool::new(false)) }, ready_rx)
|
||||
}
|
||||
|
||||
pub fn is_finished(&self) -> bool {
|
||||
@@ -116,6 +122,116 @@ impl Drop for Running {
|
||||
enum Channel {
|
||||
Shell,
|
||||
Iopub,
|
||||
Control,
|
||||
}
|
||||
|
||||
/// A `disconnect` sent before an interrupt: its seq, and who waits for the answer.
|
||||
type Release = (i64, oneshot::Sender<()>);
|
||||
|
||||
/// A kernel's debugger, in the Jupyter debugger protocol: DAP messages go out as
|
||||
/// `debug_request` on the control channel and come back as `debug_reply` there and
|
||||
/// `debug_event` on IOPub. Kept per notebook across kernel generations.
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct DebugPort {
|
||||
/// The running generation's control channel.
|
||||
control: Arc<Mutex<Option<mpsc::Sender<JupyterMessage>>>>,
|
||||
/// The open debug session's inbox, if any.
|
||||
sink: Arc<Mutex<Option<mpsc::UnboundedSender<Value>>>>,
|
||||
/// Whether the running kernel said it has a debugger.
|
||||
capable: Arc<AtomicBool>,
|
||||
/// A `disconnect` sent before an interrupt, by seq, and who waits for its answer.
|
||||
release: Arc<Mutex<Option<Release>>>,
|
||||
}
|
||||
|
||||
impl DebugPort {
|
||||
/// Hands a debug reply or event to the open session; false for any other message.
|
||||
fn route(&self, kind: &str, content: &Value) -> bool {
|
||||
if kind != "debug_reply" && kind != "debug_event" {
|
||||
return false;
|
||||
}
|
||||
let mut release = self.release.lock();
|
||||
if release
|
||||
.as_ref()
|
||||
.is_some_and(|(seq, _)| content["request_seq"].as_i64() == Some(*seq) && content["type"] == "response")
|
||||
{
|
||||
let _ = release.take().map(|(_, done)| done.send(()));
|
||||
return true;
|
||||
}
|
||||
drop(release);
|
||||
if let Some(sink) = self.sink.lock().as_ref() {
|
||||
let _ = sink.send(content.clone());
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn attach(&self, control: mpsc::Sender<JupyterMessage>) {
|
||||
*self.control.lock() = Some(control);
|
||||
}
|
||||
|
||||
/// The control channel to send DAP requests on and the inbox of DAP replies and events.
|
||||
/// One session at a time.
|
||||
pub fn open(&self) -> IdeResult<(mpsc::Sender<JupyterMessage>, mpsc::UnboundedReceiver<Value>)> {
|
||||
let control = self
|
||||
.control
|
||||
.lock()
|
||||
.clone()
|
||||
.filter(|control| !control.is_closed())
|
||||
.ok_or_else(|| IdeError::unavailable("the notebook's kernel is not running"))?;
|
||||
if !self.capable.load(Ordering::Acquire) {
|
||||
return Err(IdeError::unavailable(CANNOT_DEBUG));
|
||||
}
|
||||
let mut sink = self.sink.lock();
|
||||
if sink.as_ref().is_some_and(|sink| !sink.is_closed()) {
|
||||
return Err(IdeError::unavailable("the notebook is already being debugged"));
|
||||
}
|
||||
let (tx, inbox) = mpsc::unbounded_channel();
|
||||
*sink = Some(tx);
|
||||
Ok((control, inbox))
|
||||
}
|
||||
|
||||
/// Before an interrupt: a debug session's `disconnect`, so that a run paused at a breakpoint
|
||||
/// goes on and can be interrupted (a paused kernel does not answer SIGINT in time and is
|
||||
/// stopped). Waits a little for the kernel to answer.
|
||||
pub async fn release(&self) {
|
||||
if !self.sink.lock().as_ref().is_some_and(|sink| !sink.is_closed()) {
|
||||
return;
|
||||
}
|
||||
let Some(control) = self.control.lock().clone() else { return };
|
||||
const SEQ: i64 = (1 << 50) + 1;
|
||||
let (done, answered) = oneshot::channel();
|
||||
*self.release.lock() = Some((SEQ, done));
|
||||
let request = json!({"type": "request", "seq": SEQ, "command": "disconnect",
|
||||
"arguments": {"restart": false, "terminateDebuggee": false}});
|
||||
let message: JupyterMessage = jupyter_protocol::DebugRequest { content: request }.into();
|
||||
if control.send(message).await.is_ok() {
|
||||
let _ = tokio::time::timeout(Duration::from_secs(3), answered).await;
|
||||
}
|
||||
self.release.lock().take();
|
||||
}
|
||||
}
|
||||
|
||||
/// The reason Debug Cell gives for a kernel without a debugger.
|
||||
pub(super) const CANNOT_DEBUG: &str =
|
||||
"this kernel has no debugger: Debug Cell needs a Python kernel with ipykernel 6 or later and debugpy installed";
|
||||
|
||||
/// Whether a `kernel_info_reply` announces the debugger: `debugger: true` (ipykernel 6) or
|
||||
/// `"debugger"` among `supported_features` (ipykernel 7).
|
||||
fn has_debugger(reply: &Value) -> bool {
|
||||
reply["debugger"] == true
|
||||
|| reply["supported_features"].as_array().is_some_and(|features| features.iter().any(|f| f == "debugger"))
|
||||
}
|
||||
|
||||
/// Sends what arrives on the returned channel over `connection`, until either closes.
|
||||
fn control_writer(mut connection: DealerSendConnection) -> (mpsc::Sender<JupyterMessage>, JoinHandle<()>) {
|
||||
let (tx, mut messages) = mpsc::channel::<JupyterMessage>(16);
|
||||
let task = tokio::spawn(async move {
|
||||
while let Some(message) = messages.recv().await {
|
||||
if send(&mut connection, message).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
(tx, task)
|
||||
}
|
||||
|
||||
struct Frame {
|
||||
@@ -160,11 +276,14 @@ fn reader<S: SocketRecv + Send + 'static>(
|
||||
tx: mpsc::Sender<Frame>,
|
||||
failure: Failure,
|
||||
queued: Arc<Semaphore>,
|
||||
debug: DebugPort,
|
||||
) -> JoinHandle<()> {
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let result = receive(&mut connection, channel, &queued).await;
|
||||
match result {
|
||||
// The debugger's messages, and the control channel's other replies, are not a run's.
|
||||
Ok(frame) if debug.route(&frame.kind, &frame.content) || channel == Channel::Control => {}
|
||||
Ok(frame) => {
|
||||
if tx.try_send(frame).is_err() {
|
||||
failure.fail(IdeError::unavailable(
|
||||
@@ -225,10 +344,46 @@ fn protocol(error: impl std::fmt::Display) -> IdeError {
|
||||
IdeError::new(ide_core::error::ErrorKind::Protocol, format!("Jupyter protocol: {error}"))
|
||||
}
|
||||
|
||||
/// How messages reach the kernel: ZeroMQ to a process the IDE owns, or a Jupyter server.
|
||||
#[expect(clippy::large_enum_variant, reason = "one per running kernel")]
|
||||
enum Link {
|
||||
Local { process: Process, shell: DealerSendConnection, control: mpsc::Sender<JupyterMessage> },
|
||||
Remote(remote::Link),
|
||||
}
|
||||
|
||||
impl Link {
|
||||
async fn send(&mut self, message: JupyterMessage) -> IdeResult<()> {
|
||||
match self {
|
||||
Self::Local { shell, .. } => send(shell, message).await,
|
||||
Self::Remote(link) => link.send(message).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn interrupt(&mut self) -> IdeResult<()> {
|
||||
match self {
|
||||
Self::Local { process, .. } => process.interrupt(),
|
||||
Self::Remote(link) => link.interrupt().await,
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a local process exited; a remote kernel's death closes its reader instead.
|
||||
fn death(&mut self) -> IdeResult<Option<String>> {
|
||||
match self {
|
||||
Self::Local { process, .. } => process.death(),
|
||||
Self::Remote(_) => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn stderr(&self) -> String {
|
||||
match self {
|
||||
Self::Local { process, .. } => process.stderr(),
|
||||
Self::Remote(_) => String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Session {
|
||||
process: Process,
|
||||
shell: DealerSendConnection,
|
||||
control: ClientControlConnection,
|
||||
link: Link,
|
||||
frames: mpsc::Receiver<Frame>,
|
||||
failure: Failure,
|
||||
_readers: Readers,
|
||||
@@ -238,8 +393,21 @@ impl Session {
|
||||
async fn connect(
|
||||
runtime: &std::path::Path,
|
||||
notebook: &std::path::Path,
|
||||
python: &std::path::Path,
|
||||
target: &KernelTarget,
|
||||
debug: &DebugPort,
|
||||
) -> IdeResult<Self> {
|
||||
let python = match target {
|
||||
KernelTarget::Local(python) => python,
|
||||
KernelTarget::Remote(kernel) => {
|
||||
let (tx, frames) = mpsc::channel(QUEUED_MESSAGES);
|
||||
let failure = Failure::new();
|
||||
let queued = Arc::new(Semaphore::new(QUEUED_BYTES));
|
||||
let (link, reader) = remote::connect(kernel, tx, failure.clone(), queued, debug.clone()).await?;
|
||||
let (control, writer) = link.control();
|
||||
debug.attach(control);
|
||||
return Ok(Self { link: Link::Remote(link), frames, failure, _readers: Readers(vec![reader, writer]) });
|
||||
}
|
||||
};
|
||||
let (process, info) = Process::spawn(runtime, notebook, python).await?;
|
||||
let session = Uuid::new_v4().to_string();
|
||||
let identity = jupyter_zmq_client::peer_identity_for_session(&session).map_err(protocol)?;
|
||||
@@ -250,32 +418,43 @@ impl Session {
|
||||
)
|
||||
.map_err(protocol)?;
|
||||
let (shell, shell_recv) = shell.split();
|
||||
let (control, control_recv) = control.split();
|
||||
let (control, writer) = control_writer(control);
|
||||
debug.attach(control.clone());
|
||||
let (tx, frames) = mpsc::channel(QUEUED_MESSAGES);
|
||||
let failure = Failure::new();
|
||||
let queued = Arc::new(Semaphore::new(QUEUED_BYTES));
|
||||
let readers = Readers(vec![
|
||||
reader(iopub, Channel::Iopub, tx.clone(), failure.clone(), queued.clone()),
|
||||
reader(shell_recv, Channel::Shell, tx, failure.clone(), queued),
|
||||
reader(iopub, Channel::Iopub, tx.clone(), failure.clone(), queued.clone(), debug.clone()),
|
||||
reader(shell_recv, Channel::Shell, tx.clone(), failure.clone(), queued.clone(), debug.clone()),
|
||||
reader(control_recv, Channel::Control, tx, failure.clone(), queued, debug.clone()),
|
||||
writer,
|
||||
]);
|
||||
Ok(Self { process, shell, control, frames, failure, _readers: readers })
|
||||
Ok(Self { link: Link::Local { process, shell, control }, frames, failure, _readers: readers })
|
||||
}
|
||||
|
||||
async fn ready(&mut self, stop: &CancellationToken) -> IdeResult<()> {
|
||||
let deadline = Instant::now() + STARTUP_TIMEOUT;
|
||||
/// Waits for the kernel to answer; whether it has a debugger (`kernel_info_reply`).
|
||||
async fn ready(&mut self, stop: &CancellationToken) -> IdeResult<bool> {
|
||||
let remote = matches!(self.link, Link::Remote(_));
|
||||
let deadline = Instant::now() + if remote { REMOTE_STARTUP_TIMEOUT } else { STARTUP_TIMEOUT };
|
||||
let mut probe = tokio::time::interval(Duration::from_millis(250));
|
||||
probe.set_missed_tick_behavior(MissedTickBehavior::Delay);
|
||||
let mut request = String::new();
|
||||
let mut reply = false;
|
||||
let mut idle = false;
|
||||
let mut debugger = false;
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = stop.cancelled() => return Err(IdeError::cancelled()),
|
||||
_ = self.failure.token.cancelled() => return Err(self.failure.error()),
|
||||
_ = tokio::time::sleep_until(deadline) => return Err(IdeError::unavailable(format!(
|
||||
"selected Python kernel was not ready within 30 seconds; {}", self.process.stderr()))),
|
||||
_ = tokio::time::sleep_until(deadline) => return Err(IdeError::unavailable(if remote {
|
||||
"the kernel on the Jupyter server was not ready within 60 seconds".to_owned()
|
||||
} else {
|
||||
format!("selected Python kernel was not ready within 30 seconds; {}", self.link.stderr())
|
||||
})),
|
||||
_ = probe.tick() => {
|
||||
if let Some(message) = self.process.death()? {
|
||||
if let Some(message) = self.link.death()? {
|
||||
return Err(IdeError::unavailable(message));
|
||||
}
|
||||
// Only readiness probes are retried, never user execution.
|
||||
@@ -284,7 +463,7 @@ impl Session {
|
||||
let message: JupyterMessage = KernelInfoRequest {}.into();
|
||||
request = message.header.msg_id.clone();
|
||||
idle = false;
|
||||
send(&mut self.shell, message).await?;
|
||||
self.link.send(message).await?;
|
||||
} else if !idle {
|
||||
// A slow subscriber can miss the first idle. Probe again
|
||||
// after a reply, proving BOTH live shell and subscription.
|
||||
@@ -294,9 +473,12 @@ impl Session {
|
||||
frame = self.frames.recv() => {
|
||||
let frame = frame.ok_or_else(|| IdeError::unavailable("kernel readers closed during startup"))?;
|
||||
if frame.parent != request { continue; }
|
||||
if frame.channel == Channel::Shell && frame.kind == "kernel_info_reply" { reply = true; }
|
||||
if frame.channel == Channel::Shell && frame.kind == "kernel_info_reply" {
|
||||
reply = true;
|
||||
debugger = has_debugger(&frame.content);
|
||||
}
|
||||
if frame.channel == Channel::Iopub && is_idle(&frame) { idle = true; }
|
||||
if reply && idle { return Ok(()); }
|
||||
if reply && idle { return Ok(debugger); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -326,7 +508,7 @@ impl Session {
|
||||
let request_id = request.header.msg_id.clone();
|
||||
// If sending fails/times out, delivery is uncertain. Supervisor closes
|
||||
// the process; no caller may retry user code automatically.
|
||||
send(&mut self.shell, request).await?;
|
||||
self.link.send(request).await?;
|
||||
if !silent {
|
||||
status(notebook, KernelState::Busy, None);
|
||||
}
|
||||
@@ -342,25 +524,30 @@ impl Session {
|
||||
_ = stop.cancelled() => return Err(IdeError::cancelled()),
|
||||
_ = self.failure.token.cancelled() => return Err(self.failure.error()),
|
||||
_ = execution.cancel.cancelled(), if !interrupted => {
|
||||
self.process.interrupt()?;
|
||||
self.link.interrupt().await?;
|
||||
interrupted = true;
|
||||
interrupt_deadline = Some(Instant::now() + INTERRUPT_TIMEOUT);
|
||||
},
|
||||
_ = execution.interrupt.cancelled(), if !interrupted => {
|
||||
self.process.interrupt()?;
|
||||
// Also after a read's time limit, which leaves no deadline.
|
||||
_ = execution.interrupt.cancelled(), if interrupt_deadline.is_none() => {
|
||||
self.link.interrupt().await?;
|
||||
interrupted = true;
|
||||
interrupt_deadline = Some(Instant::now() + INTERRUPT_TIMEOUT);
|
||||
},
|
||||
_ = death.tick() => {
|
||||
if execution.reply.is_closed() && !interrupted {
|
||||
self.process.interrupt()?;
|
||||
self.link.interrupt().await?;
|
||||
interrupted = true;
|
||||
interrupt_deadline = Some(Instant::now() + INTERRUPT_TIMEOUT);
|
||||
}
|
||||
if interrupt_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
|
||||
return Err(IdeError::unavailable("kernel did not drain within 5 seconds of interrupt; owned kernel stopped"));
|
||||
// A read interrupted for its time limit keeps its kernel; Interrupt stops it.
|
||||
if !silent || execution.interrupt.is_cancelled() {
|
||||
return Err(IdeError::unavailable("kernel did not drain within 5 seconds of interrupt; owned kernel stopped"));
|
||||
}
|
||||
interrupt_deadline = None;
|
||||
}
|
||||
if let Some(message) = self.process.death()? { return Err(IdeError::unavailable(message)); }
|
||||
if let Some(message) = self.link.death()? { return Err(IdeError::unavailable(message)); }
|
||||
},
|
||||
frame = self.frames.recv() => {
|
||||
let frame = frame.ok_or_else(|| IdeError::unavailable("kernel readers closed during execution"))?;
|
||||
@@ -385,19 +572,23 @@ impl Session {
|
||||
}
|
||||
|
||||
async fn shutdown(&mut self) {
|
||||
let (process, control) = match &mut self.link {
|
||||
Link::Local { process, control, .. } => (process, control),
|
||||
Link::Remote(link) => return link.shutdown().await,
|
||||
};
|
||||
// Stop is separate from user interrupt: graceful shutdown, then kill only
|
||||
// our process group/job. It must remain bounded even for wedged Python.
|
||||
let request: JupyterMessage = ShutdownRequest { restart: false }.into();
|
||||
let _ = tokio::time::timeout(Duration::from_millis(500), self.control.send(request)).await;
|
||||
let _ = control.send_timeout(request, Duration::from_millis(500)).await;
|
||||
let deadline = Instant::now() + Duration::from_millis(750);
|
||||
while Instant::now() < deadline {
|
||||
match self.process.death() {
|
||||
match process.death() {
|
||||
Ok(None) => {}
|
||||
_ => break,
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
self.process.shutdown().await;
|
||||
process.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,35 +673,46 @@ impl Budget {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn supervise(
|
||||
runtime: PathBuf,
|
||||
notebook: PathBuf,
|
||||
python: PathBuf,
|
||||
target: KernelTarget,
|
||||
status: StatusCallback,
|
||||
stop: CancellationToken,
|
||||
mut requests: mpsc::Receiver<Execution>,
|
||||
ready: oneshot::Sender<IdeResult<()>>,
|
||||
debug: DebugPort,
|
||||
) {
|
||||
status(¬ebook, KernelState::Starting, None);
|
||||
// Starting a remote kernel also waits for the server's REST answer.
|
||||
let limit = match &target {
|
||||
KernelTarget::Local(_) => STARTUP_TIMEOUT,
|
||||
KernelTarget::Remote(_) => REMOTE_STARTUP_TIMEOUT + Duration::from_secs(15),
|
||||
};
|
||||
let startup = async {
|
||||
let mut session = Session::connect(&runtime, ¬ebook, &python).await?;
|
||||
session.ready(&stop).await?;
|
||||
let mut session = Session::connect(&runtime, ¬ebook, &target, &debug).await?;
|
||||
let debugger = session.ready(&stop).await?;
|
||||
debug.capable.store(debugger, Ordering::Release);
|
||||
IdeResult::Ok(session)
|
||||
};
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = stop.cancelled() => Err(IdeError::cancelled()),
|
||||
result = tokio::time::timeout(STARTUP_TIMEOUT, startup) => result.unwrap_or_else(|_| Err(IdeError::unavailable("selected Python kernel startup timed out"))),
|
||||
result = tokio::time::timeout(limit, startup) => result.unwrap_or_else(|_| Err(IdeError::unavailable("kernel startup timed out"))),
|
||||
};
|
||||
let mut session = match result {
|
||||
Ok(session) => session,
|
||||
Err(error) => {
|
||||
let message = format!(
|
||||
"{}; selected Python: {}. Ensure ipykernel is installed in this exact environment ({} -m pip install ipykernel); no fallback interpreter was used",
|
||||
error.message,
|
||||
python.display(),
|
||||
python.display()
|
||||
);
|
||||
let message = match &target {
|
||||
KernelTarget::Local(python) => format!(
|
||||
"{}; selected Python: {}. Ensure ipykernel is installed in this exact environment ({} -m pip install ipykernel); no fallback interpreter was used",
|
||||
error.message,
|
||||
python.display(),
|
||||
python.display()
|
||||
),
|
||||
KernelTarget::Remote(kernel) => format!("{}; Jupyter server: {}", error.message, kernel.base),
|
||||
};
|
||||
let error = IdeError::new(error.kind, message);
|
||||
status(¬ebook, KernelState::Dead, Some(error.message.clone()));
|
||||
let _ = ready.send(Err(error));
|
||||
@@ -530,7 +732,7 @@ async fn supervise(
|
||||
biased;
|
||||
_ = stop.cancelled() => break,
|
||||
_ = failure.token.cancelled() => { reason = Some(failure.error().message); break; },
|
||||
_ = death.tick() => match session.process.death() {
|
||||
_ = death.tick() => match session.link.death() {
|
||||
Ok(None) => {},
|
||||
Ok(Some(message)) => { reason = Some(message); break; },
|
||||
Err(error) => { reason = Some(error.message); break; },
|
||||
@@ -567,3 +769,17 @@ async fn supervise(
|
||||
#[cfg(test)]
|
||||
#[path = "transport_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod debugger_tests {
|
||||
use super::has_debugger;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn kernel_info_announces_the_debugger_either_way() {
|
||||
assert!(has_debugger(&json!({"debugger": true})));
|
||||
assert!(has_debugger(&json!({"supported_features": ["kernel subshells", "debugger"]})));
|
||||
assert!(!has_debugger(&json!({"supported_features": ["kernel subshells"]})));
|
||||
assert!(!has_debugger(&json!({"implementation": "IRkernel"})));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
//! A kernel on a Jupyter server (`jupyter server`, JupyterLab, a JupyterHub user server):
|
||||
//! REST calls start, interrupt and delete it, and its messages go over the kernel's
|
||||
//! channels WebSocket as JSON text frames.
|
||||
use super::{Channel, DebugPort, Failure, Frame, MAX_MESSAGE_BYTES, SEND_TIMEOUT, protocol};
|
||||
use crate::kernel::RemoteKernel;
|
||||
use futures::SinkExt;
|
||||
use futures::stream::StreamExt;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use jupyter_protocol::JupyterMessage;
|
||||
use reqwest::Method;
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
use specta::Type;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::sync::{Semaphore, mpsc, oneshot};
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
|
||||
use tokio_tungstenite::tungstenite::{Message, http::HeaderValue};
|
||||
use tokio_tungstenite::{Connector, MaybeTlsStream, WebSocketStream, client_async_tls_with_config};
|
||||
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
/// Waits between attempts to reopen a dropped channels socket, about 15 s in all.
|
||||
const RECONNECT_DELAYS: [Duration; 5] = [
|
||||
Duration::from_millis(500),
|
||||
Duration::from_secs(1),
|
||||
Duration::from_secs(2),
|
||||
Duration::from_secs(4),
|
||||
Duration::from_secs(8),
|
||||
];
|
||||
|
||||
type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>;
|
||||
|
||||
/// A kernel spec a Jupyter server offers.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct KernelSpec {
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
}
|
||||
|
||||
/// Where a page's path starts on a Jupyter server (JupyterLab, Notebook, their editors).
|
||||
const PAGES: [&str; 6] = ["lab", "tree", "notebooks", "edit", "doc", "voila"];
|
||||
|
||||
/// The server's base URL (`http(s)://host[:port]/[prefix/]`) from what a user pastes, and
|
||||
/// the `?token=` it carries. A page's path (`/lab/tree/x.ipynb`, `/notebooks/x.ipynb`) is
|
||||
/// dropped, so a URL copied from the browser works. A JupyterHub user server's
|
||||
/// `/user/<name>/` is kept whatever the name.
|
||||
pub fn normalize_server_url(text: &str) -> IdeResult<(String, Option<String>)> {
|
||||
let invalid = || IdeError::invalid("enter the Jupyter server's http:// or https:// URL");
|
||||
let mut url = reqwest::Url::parse(text.trim()).map_err(|_| invalid())?;
|
||||
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none_or(str::is_empty) {
|
||||
return Err(invalid());
|
||||
}
|
||||
let token = url.query_pairs().find(|(key, _)| key == "token").map(|(_, value)| value.into_owned());
|
||||
let mut segments: Vec<String> =
|
||||
url.path_segments().into_iter().flatten().filter(|s| !s.is_empty()).map(str::to_owned).collect();
|
||||
let prefix = if segments.first().is_some_and(|first| first == "user") { 2 } else { 0 };
|
||||
if let Some(page) = segments.iter().skip(prefix).position(|s| PAGES.contains(&s.as_str())) {
|
||||
segments.truncate(prefix + page);
|
||||
}
|
||||
let path = segments.iter().map(|segment| format!("{segment}/")).collect::<String>();
|
||||
url.set_path(&format!("/{path}"));
|
||||
url.set_query(None);
|
||||
url.set_fragment(None);
|
||||
let _ = url.set_username("");
|
||||
let _ = url.set_password(None);
|
||||
Ok((url.to_string(), token))
|
||||
}
|
||||
|
||||
async fn call(base: &str, token: &str, method: Method, path: &str, body: Option<Value>) -> IdeResult<Value> {
|
||||
// Redirects are not followed: the token must not travel to another host.
|
||||
let client = ide_http::client::shared_without_redirects()?;
|
||||
let write = method != Method::GET;
|
||||
let mut request = client.request(method, format!("{base}{path}")).timeout(REQUEST_TIMEOUT);
|
||||
if !token.is_empty() {
|
||||
request = request.header(reqwest::header::AUTHORIZATION, format!("token {token}"));
|
||||
} else if write && let Some(xsrf) = xsrf(&client, base).await {
|
||||
// A server without a token checks XSRF on every request that changes something.
|
||||
request = request.header(reqwest::header::COOKIE, format!("_xsrf={xsrf}")).header("X-XSRFToken", xsrf);
|
||||
}
|
||||
if let Some(body) = body {
|
||||
request = request.header(reqwest::header::CONTENT_TYPE, "application/json").body(body.to_string());
|
||||
}
|
||||
let response = request.send().await.map_err(|error| {
|
||||
IdeError::unavailable(format!("could not reach the Jupyter server: {}", ide_http::client::describe(&error)))
|
||||
})?;
|
||||
let status = response.status();
|
||||
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
|
||||
return Err(IdeError::unavailable(if token.is_empty() {
|
||||
"the Jupyter server needs a token"
|
||||
} else {
|
||||
"the Jupyter server did not accept the token"
|
||||
}));
|
||||
}
|
||||
if !status.is_success() {
|
||||
return Err(IdeError::unavailable(format!("the Jupyter server answered {status} to {path}")));
|
||||
}
|
||||
let bytes = response
|
||||
.bytes()
|
||||
.await
|
||||
.map_err(|error| IdeError::unavailable(format!("Jupyter server: {}", ide_http::client::describe(&error))))?;
|
||||
if bytes.is_empty() {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
serde_json::from_slice(&bytes).map_err(|_| IdeError::unavailable("the URL did not answer like a Jupyter server"))
|
||||
}
|
||||
|
||||
/// The `_xsrf` cookie the server sets on any page (an API reply sets none).
|
||||
async fn xsrf(client: &reqwest::Client, base: &str) -> Option<String> {
|
||||
let response = client.get(base).timeout(REQUEST_TIMEOUT).send().await.ok()?;
|
||||
response.headers().get_all(reqwest::header::SET_COOKIE).iter().find_map(|cookie| {
|
||||
let value = cookie.to_str().ok()?.split(';').next()?.trim().strip_prefix("_xsrf=")?;
|
||||
Some(value.trim_matches('"').to_owned())
|
||||
})
|
||||
}
|
||||
|
||||
/// The server's kernel specs, its default first. Also checks the URL and the token.
|
||||
pub async fn kernel_specs(base: &str, token: &str) -> IdeResult<Vec<KernelSpec>> {
|
||||
parse_specs(&call(base, token, Method::GET, "api/kernelspecs", None).await?)
|
||||
}
|
||||
|
||||
fn parse_specs(reply: &Value) -> IdeResult<Vec<KernelSpec>> {
|
||||
let specs = reply["kernelspecs"]
|
||||
.as_object()
|
||||
.ok_or_else(|| IdeError::unavailable("the URL did not answer like a Jupyter server"))?;
|
||||
let default = reply["default"].as_str().unwrap_or_default();
|
||||
let mut specs: Vec<KernelSpec> = specs
|
||||
.iter()
|
||||
.map(|(name, spec)| KernelSpec {
|
||||
name: name.clone(),
|
||||
display_name: spec["spec"]["display_name"].as_str().unwrap_or(name).to_owned(),
|
||||
})
|
||||
.collect();
|
||||
specs.sort_by(|a, b| (a.name != default, &a.display_name).cmp(&(b.name != default, &b.display_name)));
|
||||
Ok(specs)
|
||||
}
|
||||
|
||||
/// A kernel the IDE started on a server. Deleted there when the last handle goes, so a
|
||||
/// startup that fails, times out or is cancelled leaves nothing running.
|
||||
struct Kernel {
|
||||
base: String,
|
||||
token: String,
|
||||
id: String,
|
||||
deleted: AtomicBool,
|
||||
}
|
||||
|
||||
async fn delete(base: &str, token: &str, id: &str) {
|
||||
let _ = call(base, token, Method::DELETE, &format!("api/kernels/{id}"), None).await;
|
||||
}
|
||||
|
||||
impl Kernel {
|
||||
async fn delete(&self) {
|
||||
if !self.deleted.swap(true, Ordering::AcqRel) {
|
||||
delete(&self.base, &self.token, &self.id).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Kernel {
|
||||
fn drop(&mut self) {
|
||||
if !*self.deleted.get_mut()
|
||||
&& let Ok(runtime) = tokio::runtime::Handle::try_current()
|
||||
{
|
||||
let (base, token, id) = (self.base.clone(), self.token.clone(), self.id.clone());
|
||||
runtime.spawn(async move { delete(&base, &token, &id).await });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Link {
|
||||
kernel: Arc<Kernel>,
|
||||
outgoing: mpsc::Sender<String>,
|
||||
}
|
||||
|
||||
/// Starts a kernel of `kernel.spec` and connects to its channels; frames go to `tx` like
|
||||
/// a local kernel's ZeroMQ frames. The returned task owns the socket and reopens it, for
|
||||
/// the same kernel, when it drops.
|
||||
pub(super) async fn connect(
|
||||
kernel: &RemoteKernel,
|
||||
tx: mpsc::Sender<Frame>,
|
||||
failure: Failure,
|
||||
queued: Arc<Semaphore>,
|
||||
debug: DebugPort,
|
||||
) -> IdeResult<(Link, JoinHandle<()>)> {
|
||||
let RemoteKernel { base, token, spec } = kernel.clone();
|
||||
// Not cancelled with the caller: a kernel the server starts after that is deleted.
|
||||
let (sent, started) = oneshot::channel();
|
||||
tokio::spawn(async move {
|
||||
let reply = call(&base, &token, Method::POST, "api/kernels", Some(json!({ "name": spec }))).await;
|
||||
let kernel = reply.and_then(|reply| {
|
||||
let id = reply["id"].as_str().ok_or_else(|| protocol("kernel start reply has no id"))?.to_owned();
|
||||
Ok(Arc::new(Kernel { base, token, id, deleted: AtomicBool::new(false) }))
|
||||
});
|
||||
let _ = sent.send(kernel);
|
||||
});
|
||||
let kernel = started.await.map_err(|_| IdeError::unavailable("kernel start task ended"))??;
|
||||
let session = uuid::Uuid::new_v4().to_string();
|
||||
let socket = open_channels(&kernel, &session).await?;
|
||||
let (outgoing, messages) = mpsc::channel(16);
|
||||
let pump = tokio::spawn(pump(kernel.clone(), session, socket, messages, tx, failure, queued, debug));
|
||||
Ok((Link { kernel, outgoing }, pump))
|
||||
}
|
||||
|
||||
/// Moves messages between the socket and the session until the link goes. A socket that
|
||||
/// drops is reopened with the same session id, so the server replays what it buffered.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn pump(
|
||||
kernel: Arc<Kernel>,
|
||||
session: String,
|
||||
mut socket: Socket,
|
||||
mut messages: mpsc::Receiver<String>,
|
||||
tx: mpsc::Sender<Frame>,
|
||||
failure: Failure,
|
||||
queued: Arc<Semaphore>,
|
||||
debug: DebugPort,
|
||||
) {
|
||||
loop {
|
||||
tokio::select! {
|
||||
message = messages.recv() => {
|
||||
let Some(message) = message else { return };
|
||||
match tokio::time::timeout(SEND_TIMEOUT, socket.send(Message::Text(message.into()))).await {
|
||||
Ok(Ok(())) => {}
|
||||
_ => return failure.fail(IdeError::unavailable(
|
||||
"sending to the Jupyter server failed; delivery uncertain, not retried",
|
||||
)),
|
||||
}
|
||||
}
|
||||
incoming = socket.next() => {
|
||||
let text = match incoming {
|
||||
Some(Ok(Message::Text(text))) => text,
|
||||
// Binary frames carry messages with buffers (widgets), which notebooks do not show.
|
||||
Some(Ok(Message::Close(_)) | Err(_)) | None => match reopen(&kernel, &session).await {
|
||||
Ok(reopened) => { socket = reopened; continue; }
|
||||
Err(error) => return failure.fail(error),
|
||||
},
|
||||
Some(Ok(_)) => continue,
|
||||
};
|
||||
match frame(text.as_str(), &queued, &debug) {
|
||||
Ok(Some(frame)) => {
|
||||
if tx.try_send(frame).is_err() {
|
||||
return failure.fail(IdeError::unavailable(
|
||||
"kernel output queue overflow; execution stopped to bound memory",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => return failure.fail(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn reopen(kernel: &Kernel, session: &str) -> IdeResult<Socket> {
|
||||
let mut last = None;
|
||||
for delay in RECONNECT_DELAYS {
|
||||
tokio::time::sleep(delay).await;
|
||||
match open_channels(kernel, session).await {
|
||||
Ok(socket) => return Ok(socket),
|
||||
Err(error) => last = Some(error),
|
||||
}
|
||||
}
|
||||
let reason = last.map(|error| error.message).unwrap_or_default();
|
||||
Err(IdeError::unavailable(format!(
|
||||
"lost the connection to the Jupyter server ({reason}); the kernel may still be running there"
|
||||
)))
|
||||
}
|
||||
|
||||
async fn open_channels(kernel: &Kernel, session: &str) -> IdeResult<Socket> {
|
||||
let Kernel { base, token, id, .. } = kernel;
|
||||
let ws = base.replacen("http", "ws", 1);
|
||||
let url = format!("{ws}api/kernels/{id}/channels?session_id={session}");
|
||||
let mut request = url
|
||||
.as_str()
|
||||
.into_client_request()
|
||||
.map_err(|error| IdeError::invalid(format!("Jupyter server URL: {error}")))?;
|
||||
if !token.is_empty() {
|
||||
let value = HeaderValue::from_str(&format!("token {token}"))
|
||||
.map_err(|_| IdeError::invalid("the token contains characters a header cannot carry"))?;
|
||||
request.headers_mut().insert("authorization", value);
|
||||
}
|
||||
let config =
|
||||
WebSocketConfig::default().max_message_size(Some(MAX_MESSAGE_BYTES)).max_frame_size(Some(MAX_MESSAGE_BYTES));
|
||||
let connector = if ws.starts_with("wss:") {
|
||||
Connector::Rustls(Arc::new(ide_http::client::tls_config()?))
|
||||
} else {
|
||||
Connector::Plain
|
||||
};
|
||||
let opening = async {
|
||||
// Through the HTTP proxy the REST calls use, if any.
|
||||
let stream =
|
||||
ide_http::tunnel::connect(&reqwest::Url::parse(&url).map_err(|_| IdeError::invalid("Jupyter server URL"))?)
|
||||
.await?;
|
||||
client_async_tls_with_config(request, stream, Some(config), Some(connector))
|
||||
.await
|
||||
.map_err(|error| IdeError::unavailable(format!("could not connect to the kernel's channels: {error}")))
|
||||
};
|
||||
let (socket, _) = tokio::time::timeout(REQUEST_TIMEOUT, opening)
|
||||
.await
|
||||
.map_err(|_| IdeError::unavailable("connecting to the kernel's channels on the Jupyter server timed out"))??;
|
||||
Ok(socket)
|
||||
}
|
||||
|
||||
/// One JSON message from the channels socket; `None` for channels notebooks do not use.
|
||||
fn frame(text: &str, queued: &Arc<Semaphore>, debug: &DebugPort) -> IdeResult<Option<Frame>> {
|
||||
let bytes = text.len();
|
||||
if bytes > MAX_MESSAGE_BYTES {
|
||||
return Err(IdeError::unavailable("kernel message exceeds 8 MiB limit; execution stopped"));
|
||||
}
|
||||
let mut value: Value = serde_json::from_str(text).map_err(protocol)?;
|
||||
if debug.route(value["header"]["msg_type"].as_str().unwrap_or_default(), &value["content"]) {
|
||||
return Ok(None);
|
||||
}
|
||||
let channel = match value["channel"].as_str() {
|
||||
Some("shell") => Channel::Shell,
|
||||
Some("iopub") => Channel::Iopub,
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let kind = value["header"]["msg_type"].as_str().ok_or_else(|| protocol("missing Jupyter message type"))?.to_owned();
|
||||
// The server restarts a kernel that died; its state, and any run, is gone.
|
||||
if kind == "status" && matches!(value["content"]["execution_state"].as_str(), Some("restarting" | "dead")) {
|
||||
return Err(IdeError::unavailable("the kernel on the Jupyter server died"));
|
||||
}
|
||||
let parent = value["parent_header"]["msg_id"].as_str().unwrap_or_default().to_owned();
|
||||
let permit = queued
|
||||
.clone()
|
||||
.try_acquire_many_owned(bytes as u32)
|
||||
.map_err(|_| IdeError::unavailable("kernel output queue exceeds 16 MiB; execution stopped"))?;
|
||||
Ok(Some(Frame { channel, parent, kind, content: value["content"].take(), bytes, _permit: Some(permit) }))
|
||||
}
|
||||
|
||||
/// A message as the channels socket carries it: JSON text naming its channel.
|
||||
fn encode(mut message: JupyterMessage, channel: jupyter_protocol::Channel) -> IdeResult<String> {
|
||||
message.channel = Some(channel);
|
||||
let mut value = serde_json::to_value(&message).map_err(protocol)?;
|
||||
value["buffers"] = json!([]);
|
||||
Ok(value.to_string())
|
||||
}
|
||||
|
||||
impl Link {
|
||||
/// A sender for the kernel's control channel, over the same socket.
|
||||
pub(super) fn control(&self) -> (mpsc::Sender<JupyterMessage>, JoinHandle<()>) {
|
||||
let (tx, mut messages) = mpsc::channel::<JupyterMessage>(16);
|
||||
let outgoing = self.outgoing.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
while let Some(message) = messages.recv().await {
|
||||
let Ok(text) = encode(message, jupyter_protocol::Channel::Control) else { continue };
|
||||
if outgoing.send(text).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
(tx, task)
|
||||
}
|
||||
|
||||
pub(super) async fn send(&mut self, message: JupyterMessage) -> IdeResult<()> {
|
||||
let text = encode(message, jupyter_protocol::Channel::Shell)?;
|
||||
tokio::time::timeout(SEND_TIMEOUT, self.outgoing.send(text))
|
||||
.await
|
||||
.map_err(|_| IdeError::unavailable("kernel request send timed out; delivery uncertain, not retried"))?
|
||||
.map_err(|_| IdeError::unavailable("the connection to the Jupyter server closed"))
|
||||
}
|
||||
|
||||
/// Asks the server to interrupt the kernel, without waiting: the run keeps reading
|
||||
/// output meanwhile, and its interrupt deadline covers a server that does not answer.
|
||||
pub(super) async fn interrupt(&mut self) -> IdeResult<()> {
|
||||
let kernel = self.kernel.clone();
|
||||
tokio::spawn(async move {
|
||||
let _ =
|
||||
call(&kernel.base, &kernel.token, Method::POST, &format!("api/kernels/{}/interrupt", kernel.id), None)
|
||||
.await;
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Deletes the kernel and waits for the server's answer. A server that cannot be
|
||||
/// reached keeps it until it culls idle kernels, if it is configured to.
|
||||
pub(super) async fn shutdown(&mut self) {
|
||||
self.kernel.delete().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn server_urls_are_reduced_to_their_base() {
|
||||
let base = |text| normalize_server_url(text).unwrap();
|
||||
assert_eq!(base("http://localhost:8888"), ("http://localhost:8888/".into(), None));
|
||||
assert_eq!(
|
||||
base(" http://127.0.0.1:8888/lab?token=abc "),
|
||||
("http://127.0.0.1:8888/".into(), Some("abc".into()))
|
||||
);
|
||||
assert_eq!(
|
||||
base("https://hub.example.com/user/alice/lab"),
|
||||
("https://hub.example.com/user/alice/".into(), None)
|
||||
);
|
||||
assert_eq!(
|
||||
base("https://hub.example.com/user/alice/tree?x=1#y"),
|
||||
("https://hub.example.com/user/alice/".into(), None)
|
||||
);
|
||||
// A page's path, wherever it ends.
|
||||
assert_eq!(base("http://localhost:8888/lab/tree/work/x.ipynb"), ("http://localhost:8888/".into(), None));
|
||||
assert_eq!(
|
||||
base("http://localhost:8888/notebooks/x.ipynb?token=t"),
|
||||
("http://localhost:8888/".into(), Some("t".into()))
|
||||
);
|
||||
assert_eq!(base("https://host/jupyter/doc/tree/x.ipynb"), ("https://host/jupyter/".into(), None));
|
||||
// A Hub user named like a page keeps the name.
|
||||
assert_eq!(base("https://hub.example.com/user/lab/"), ("https://hub.example.com/user/lab/".into(), None));
|
||||
assert_eq!(
|
||||
base("https://hub.example.com/user/lab/lab/tree/a"),
|
||||
("https://hub.example.com/user/lab/".into(), None)
|
||||
);
|
||||
assert!(normalize_server_url("file:///tmp").is_err());
|
||||
assert!(normalize_server_url("localhost:8888").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kernel_specs_list_the_default_first() {
|
||||
let reply = json!({"default": "python3", "kernelspecs": {
|
||||
"ir": {"name": "ir", "spec": {"display_name": "R"}},
|
||||
"python3": {"name": "python3", "spec": {"display_name": "Python 3 (ipykernel)"}},
|
||||
"julia": {"name": "julia", "spec": {}},
|
||||
}});
|
||||
let names: Vec<_> = parse_specs(&reply).unwrap().into_iter().map(|s| s.display_name).collect();
|
||||
assert_eq!(names, ["Python 3 (ipykernel)", "R", "julia"]);
|
||||
assert!(parse_specs(&json!({"message": "not found"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_messages_become_frames() {
|
||||
let queued = Arc::new(Semaphore::new(1 << 20));
|
||||
let reply = json!({"channel": "shell", "header": {"msg_type": "execute_reply"},
|
||||
"parent_header": {"msg_id": "run-1"}, "content": {"status": "ok"}});
|
||||
let frame = frame(&reply.to_string(), &queued, &DebugPort::default()).unwrap().unwrap();
|
||||
assert!(frame.channel == Channel::Shell && frame.parent == "run-1" && frame.kind == "execute_reply");
|
||||
assert_eq!(frame.content["status"], "ok");
|
||||
let stdin = json!({"channel": "stdin", "header": {"msg_type": "input_request"}});
|
||||
assert!(super::frame(&stdin.to_string(), &queued, &DebugPort::default()).unwrap().is_none());
|
||||
let died = json!({"channel": "iopub", "header": {"msg_type": "status"}, "parent_header": {},
|
||||
"content": {"execution_state": "restarting"}});
|
||||
assert!(super::frame(&died.to_string(), &queued, &DebugPort::default()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ fn manager(root: &Path) -> Arc<KernelManager> {
|
||||
async fn run(
|
||||
manager: &KernelManager,
|
||||
notebook: &Path,
|
||||
python: &Path,
|
||||
target: impl Into<ide_notebook::kernel::KernelTarget>,
|
||||
code: &str,
|
||||
) -> (IdeResult<ExecutionResult>, Vec<KernelOutput>) {
|
||||
let outputs: Outputs = Arc::new(Mutex::new(Vec::new()));
|
||||
@@ -36,7 +36,7 @@ async fn run(
|
||||
Duration::from_secs(45),
|
||||
manager.execute(
|
||||
notebook,
|
||||
python,
|
||||
target,
|
||||
code,
|
||||
CancellationToken::new(),
|
||||
Arc::new(move |output| sink.lock().unwrap().push(output)),
|
||||
@@ -340,3 +340,476 @@ async fn inspection_is_silent_and_never_starts_a_kernel() {
|
||||
assert!(outputs.iter().all(|o| o.content["text"].as_str().is_none_or(|text| !text.contains("hidden"))));
|
||||
manager.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires OPENIDEA_TEST_PYTHON with real ipykernel"]
|
||||
async fn a_run_waits_for_a_slow_inspection_and_keeps_the_kernel() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let notebook = root.path().join("slow.ipynb");
|
||||
let python = python();
|
||||
let manager = manager(root.path());
|
||||
let (result, _) = run(&manager, ¬ebook, &python,
|
||||
"import time\nclass Slow:\n def __repr__(self):\n time.sleep(2)\n return 'slow'\nslow = Slow()\nkept = 1").await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
let expressions = std::collections::HashMap::from([("v".to_owned(), "repr(slow)".to_owned())]);
|
||||
let inspecting = {
|
||||
let (manager, notebook) = (manager.clone(), notebook.clone());
|
||||
tokio::spawn(async move { manager.inspect(¬ebook, "", expressions).await })
|
||||
};
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
// Arrives during the inspection: waits for it instead of failing as busy.
|
||||
let (result, outputs) = run(&manager, ¬ebook, &python, "kept + 1").await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
assert!(outputs.iter().any(|o| o.kind == "execute_result" && o.content["data"]["text/plain"] == "2"));
|
||||
assert_eq!(inspecting.await.unwrap().unwrap().unwrap()["v"]["data"]["text/plain"], "'slow'");
|
||||
manager.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires OPENIDEA_TEST_PYTHON with real ipykernel"]
|
||||
async fn a_stuck_inspection_is_interrupted_at_its_limit_and_the_waiting_run_goes_on() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let notebook = root.path().join("hung.ipynb");
|
||||
let python = python();
|
||||
let manager = manager(root.path());
|
||||
let (result, _) = run(
|
||||
&manager,
|
||||
¬ebook,
|
||||
&python,
|
||||
"import time\nclass Hung:\n def __repr__(self):\n time.sleep(600)\nhung = Hung()\nkept = 1",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
let expressions = std::collections::HashMap::from([("v".to_owned(), "repr(hung)".to_owned())]);
|
||||
let inspecting = {
|
||||
let (manager, notebook) = (manager.clone(), notebook.clone());
|
||||
tokio::spawn(async move { manager.inspect(¬ebook, "", expressions).await })
|
||||
};
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
let started = std::time::Instant::now();
|
||||
let (result, outputs) =
|
||||
tokio::time::timeout(Duration::from_secs(15), run(&manager, ¬ebook, &python, "kept + 1")).await.unwrap();
|
||||
assert_eq!(result.unwrap().status, "ok", "the run waits for the read, not fails");
|
||||
assert!(outputs.iter().any(|o| o.kind == "execute_result" && o.content["data"]["text/plain"] == "2"));
|
||||
assert!(started.elapsed() < Duration::from_secs(10));
|
||||
assert_eq!(inspecting.await.unwrap().unwrap_err().kind, ErrorKind::Cancelled);
|
||||
manager.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires OPENIDEA_TEST_PYTHON with real ipykernel"]
|
||||
async fn interrupt_stops_a_stuck_inspection_and_keeps_state() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let notebook = root.path().join("stuck.ipynb");
|
||||
let python = python();
|
||||
let manager = manager(root.path());
|
||||
let (result, _) = run(
|
||||
&manager,
|
||||
¬ebook,
|
||||
&python,
|
||||
"import time\nclass Stuck:\n def __repr__(self):\n time.sleep(600)\nstuck = Stuck()\nkept = 1",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
let expressions = std::collections::HashMap::from([("v".to_owned(), "repr(stuck)".to_owned())]);
|
||||
let inspecting = {
|
||||
let (manager, notebook) = (manager.clone(), notebook.clone());
|
||||
tokio::spawn(async move { manager.inspect(¬ebook, "", expressions).await })
|
||||
};
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
tokio::time::timeout(Duration::from_secs(10), manager.interrupt(¬ebook)).await.unwrap().unwrap();
|
||||
let inspected = tokio::time::timeout(Duration::from_secs(10), inspecting).await.unwrap().unwrap();
|
||||
assert_eq!(inspected.unwrap_err().kind, ErrorKind::Cancelled);
|
||||
let (result, _) = run(&manager, ¬ebook, &python, "kept").await;
|
||||
assert_eq!(result.unwrap().status, "ok", "the kernel and its state survive");
|
||||
manager.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires OPENIDEA_TEST_JUPYTER_URL (and OPENIDEA_TEST_JUPYTER_TOKEN) of a running Jupyter server"]
|
||||
async fn remote_kernel_runs_interrupts_restarts_and_is_deleted() {
|
||||
let (server, token, target) = remote(None).await;
|
||||
let before = server_kernels(&server, &token).await;
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let notebook = root.path().join("remote.ipynb");
|
||||
let manager = manager(root.path());
|
||||
let run = |code: &'static str| {
|
||||
let (manager, notebook, target) = (manager.clone(), notebook.clone(), target.clone());
|
||||
async move {
|
||||
let outputs: Outputs = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = outputs.clone();
|
||||
let result = manager
|
||||
.execute(
|
||||
¬ebook,
|
||||
target,
|
||||
code,
|
||||
CancellationToken::new(),
|
||||
Arc::new(move |o| sink.lock().unwrap().push(o)),
|
||||
)
|
||||
.await;
|
||||
let outputs = std::mem::take(&mut *outputs.lock().unwrap());
|
||||
(result, outputs)
|
||||
}
|
||||
};
|
||||
let (result, outputs) = run("answer = 6 * 7\nanswer").await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
assert!(outputs.iter().any(|o| o.kind == "execute_result" && o.content["data"]["text/plain"] == "42"));
|
||||
let sleeping = tokio::spawn(run("import time\ntime.sleep(30)"));
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
manager.interrupt(¬ebook).await.unwrap();
|
||||
let (result, _) = tokio::time::timeout(Duration::from_secs(10), sleeping).await.unwrap().unwrap();
|
||||
assert!(result.is_err() || result.unwrap().status == "error", "the interrupted run must not succeed");
|
||||
let (result, _) = run("answer").await;
|
||||
assert_eq!(result.unwrap().status, "ok", "state survives an interrupt");
|
||||
manager.restart(¬ebook).await.unwrap();
|
||||
let (result, outputs) = run("answer").await;
|
||||
assert_eq!(result.unwrap().status, "error");
|
||||
assert!(outputs.iter().any(|o| o.kind == "error" && o.content["ename"] == "NameError"));
|
||||
manager.shutdown_kernel(¬ebook).await.unwrap();
|
||||
assert_eq!(server_kernels(&server, &token).await, before, "closing the notebook deletes its kernel on the server");
|
||||
}
|
||||
|
||||
/// The test server from `OPENIDEA_TEST_JUPYTER_URL` / `OPENIDEA_TEST_JUPYTER_TOKEN`, with `base`
|
||||
/// in place of its URL when given (a forwarder in front of it).
|
||||
async fn remote(base: Option<String>) -> (String, String, ide_notebook::kernel::KernelTarget) {
|
||||
use ide_notebook::kernel::{KernelTarget, RemoteKernel, kernel_specs, normalize_server_url};
|
||||
let (server, in_url) = normalize_server_url(&std::env::var("OPENIDEA_TEST_JUPYTER_URL").unwrap()).unwrap();
|
||||
let token = std::env::var("OPENIDEA_TEST_JUPYTER_TOKEN").ok().or(in_url).unwrap_or_default();
|
||||
let spec = kernel_specs(&server, &token).await.unwrap().remove(0).name;
|
||||
let base = base.unwrap_or(server.clone());
|
||||
(server.clone(), token.clone(), KernelTarget::Remote(RemoteKernel { base, token, spec }))
|
||||
}
|
||||
|
||||
/// The ids of the server's kernels.
|
||||
async fn server_kernels(server: &str, token: &str) -> std::collections::HashSet<String> {
|
||||
let client = ide_http::client::shared_without_redirects().unwrap();
|
||||
let reply = client.get(format!("{server}api/kernels")).header("Authorization", format!("token {token}"));
|
||||
let kernels: Vec<Value> = serde_json::from_slice(&reply.send().await.unwrap().bytes().await.unwrap()).unwrap();
|
||||
kernels.iter().map(|kernel| kernel["id"].as_str().unwrap().to_owned()).collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires OPENIDEA_TEST_JUPYTER_URL (and OPENIDEA_TEST_JUPYTER_TOKEN) of a running Jupyter server"]
|
||||
async fn closing_a_notebook_while_its_remote_kernel_starts_deletes_the_kernel() {
|
||||
let (server, token, target) = remote(None).await;
|
||||
let before = server_kernels(&server, &token).await;
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let notebook = root.path().join("closed.ipynb");
|
||||
let manager = manager(root.path());
|
||||
let starting = {
|
||||
let (manager, notebook) = (manager.clone(), notebook.clone());
|
||||
tokio::spawn(async move { run(&manager, ¬ebook, target, "1").await })
|
||||
};
|
||||
// Closed once the server has the kernel, before it answers.
|
||||
while server_kernels(&server, &token).await == before {
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
manager.shutdown_kernel(¬ebook).await.unwrap();
|
||||
assert!(starting.await.unwrap().0.is_err());
|
||||
for _ in 0..50 {
|
||||
if server_kernels(&server, &token).await == before {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
panic!("the kernel was left on the server");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires OPENIDEA_TEST_JUPYTER_URL (and OPENIDEA_TEST_JUPYTER_TOKEN) of a running Jupyter server"]
|
||||
async fn a_dropped_connection_to_the_server_reconnects_and_keeps_the_kernel() {
|
||||
// A forwarder in front of the server whose connections can be cut.
|
||||
let (server, token, _) = remote(None).await;
|
||||
let upstream = reqwest::Url::parse(&server).unwrap();
|
||||
let upstream = format!("{}:{}", upstream.host_str().unwrap(), upstream.port_or_known_default().unwrap());
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let base = format!("http://{}/", listener.local_addr().unwrap());
|
||||
let links: Arc<Mutex<Vec<tokio::task::JoinHandle<()>>>> = Arc::default();
|
||||
let accepting = {
|
||||
let links = links.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Ok((mut client, _)) = listener.accept().await {
|
||||
let upstream = upstream.clone();
|
||||
links.lock().unwrap().push(tokio::spawn(async move {
|
||||
let mut server = tokio::net::TcpStream::connect(upstream).await.unwrap();
|
||||
let _ = tokio::io::copy_bidirectional(&mut client, &mut server).await;
|
||||
}));
|
||||
}
|
||||
})
|
||||
};
|
||||
let (_, _, target) = remote(Some(base)).await;
|
||||
let before = server_kernels(&server, &token).await;
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let notebook = root.path().join("dropped.ipynb");
|
||||
let manager = manager(root.path());
|
||||
let (result, _) = run(&manager, ¬ebook, target.clone(), "kept = 5").await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
links.lock().unwrap().drain(..).for_each(|link| link.abort());
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
let (result, outputs) = run(&manager, ¬ebook, target, "kept").await;
|
||||
assert_eq!(result.unwrap().status, "ok", "the run goes to the same kernel after reconnecting");
|
||||
assert!(outputs.iter().any(|o| o.kind == "execute_result" && o.content["data"]["text/plain"] == "5"));
|
||||
manager.shutdown_kernel(¬ebook).await.unwrap();
|
||||
accepting.abort();
|
||||
assert_eq!(server_kernels(&server, &token).await, before, "closing the notebook deletes its one kernel");
|
||||
}
|
||||
|
||||
/// Sends DAP request `command` on `debugger` and waits for its response, keeping the events.
|
||||
async fn dap(
|
||||
debugger: &mut ide_notebook::kernel::KernelDebugger,
|
||||
seq: &mut i64,
|
||||
events: &mut Vec<Value>,
|
||||
command: &str,
|
||||
arguments: Value,
|
||||
) -> Value {
|
||||
*seq += 1;
|
||||
let request = serde_json::json!({"type": "request", "seq": *seq, "command": command, "arguments": arguments});
|
||||
debugger.send(request).await.unwrap();
|
||||
loop {
|
||||
let message = tokio::time::timeout(Duration::from_secs(20), debugger.receive()).await.unwrap().unwrap();
|
||||
if message["type"] == "response" && message["request_seq"] == *seq {
|
||||
assert_eq!(message["success"], true, "{command}: {message}");
|
||||
return message;
|
||||
}
|
||||
events.push(message);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a cell under the kernel's debugger: stops at a breakpoint in another cell's function,
|
||||
/// shows its locals, continues, and the kernel keeps its state after the session.
|
||||
async fn debug_a_cell(manager: Arc<KernelManager>, notebook: PathBuf, target: ide_notebook::kernel::KernelTarget) {
|
||||
let helper = "def double(x):\n y = x * 2\n return y\n";
|
||||
let (result, _) = run(&manager, ¬ebook, target.clone(), helper).await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
let mut debugger = manager.debugger(¬ebook).unwrap();
|
||||
assert!(manager.debugger(¬ebook).is_err(), "one debug session at a time");
|
||||
let (mut seq, mut events) = (0, Vec::new());
|
||||
dap(
|
||||
&mut debugger,
|
||||
&mut seq,
|
||||
&mut events,
|
||||
"initialize",
|
||||
serde_json::json!({"adapterID": "python", "pathFormat": "path", "linesStartAt1": true}),
|
||||
)
|
||||
.await;
|
||||
dap(&mut debugger, &mut seq, &mut events, "attach", serde_json::json!({})).await;
|
||||
let dumped = dap(&mut debugger, &mut seq, &mut events, "dumpCell", serde_json::json!({"code": helper})).await;
|
||||
let path = dumped["body"]["sourcePath"].as_str().unwrap().to_owned();
|
||||
let set = dap(
|
||||
&mut debugger,
|
||||
&mut seq,
|
||||
&mut events,
|
||||
"setBreakpoints",
|
||||
serde_json::json!({"source": {"path": path}, "breakpoints": [{"line": 3}]}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(set["body"]["breakpoints"][0]["verified"], true);
|
||||
dap(&mut debugger, &mut seq, &mut events, "configurationDone", serde_json::json!({})).await;
|
||||
let running = {
|
||||
let (manager, notebook, target) = (manager.clone(), notebook.clone(), target.clone());
|
||||
tokio::spawn(async move { run(&manager, ¬ebook, target, "b = double(21)").await })
|
||||
};
|
||||
let stopped = loop {
|
||||
if let Some(stopped) = events.iter().find(|e| e["event"] == "stopped") {
|
||||
break stopped.clone();
|
||||
}
|
||||
events.push(tokio::time::timeout(Duration::from_secs(20), debugger.receive()).await.unwrap().unwrap());
|
||||
};
|
||||
let thread = stopped["body"]["threadId"].clone();
|
||||
let frames = dap(&mut debugger, &mut seq, &mut events, "stackTrace", serde_json::json!({"threadId": thread})).await;
|
||||
let top = &frames["body"]["stackFrames"][0];
|
||||
assert_eq!(
|
||||
(top["name"].as_str(), top["source"]["path"].as_str(), top["line"].as_i64()),
|
||||
(Some("double"), Some(path.as_str()), Some(3))
|
||||
);
|
||||
let scopes = dap(&mut debugger, &mut seq, &mut events, "scopes", serde_json::json!({"frameId": top["id"]})).await;
|
||||
let reference = scopes["body"]["scopes"][0]["variablesReference"].clone();
|
||||
let locals =
|
||||
dap(&mut debugger, &mut seq, &mut events, "variables", serde_json::json!({"variablesReference": reference}))
|
||||
.await;
|
||||
assert!(locals["body"]["variables"].as_array().unwrap().iter().any(|v| v["name"] == "y" && v["value"] == "42"));
|
||||
dap(&mut debugger, &mut seq, &mut events, "continue", serde_json::json!({"threadId": thread})).await;
|
||||
let (result, _) = tokio::time::timeout(Duration::from_secs(20), running).await.unwrap().unwrap();
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
dap(
|
||||
&mut debugger,
|
||||
&mut seq,
|
||||
&mut events,
|
||||
"disconnect",
|
||||
serde_json::json!({"restart": false, "terminateDebuggee": false}),
|
||||
)
|
||||
.await;
|
||||
drop(debugger);
|
||||
let (result, outputs) = run(&manager, ¬ebook, target, "b").await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
assert!(outputs.iter().any(|o| o.kind == "execute_result" && o.content["data"]["text/plain"] == "42"));
|
||||
assert!(manager.debugger(¬ebook).is_ok(), "a new session can open once the last one is dropped");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires OPENIDEA_TEST_PYTHON with real ipykernel (and debugpy)"]
|
||||
async fn a_cell_runs_under_the_kernels_debugger() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let manager = manager(root.path());
|
||||
let notebook = root.path().join("debug.ipynb");
|
||||
debug_a_cell(manager.clone(), notebook, ide_notebook::kernel::KernelTarget::Local(python())).await;
|
||||
manager.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires OPENIDEA_TEST_JUPYTER_URL (and OPENIDEA_TEST_JUPYTER_TOKEN) of a running Jupyter server"]
|
||||
async fn a_cell_runs_under_a_remote_kernels_debugger() {
|
||||
let (_, _, target) = remote(None).await;
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let manager = manager(root.path());
|
||||
let notebook = root.path().join("debug-remote.ipynb");
|
||||
debug_a_cell(manager.clone(), notebook.clone(), target).await;
|
||||
manager.shutdown_kernel(¬ebook).await.unwrap();
|
||||
}
|
||||
|
||||
/// One DAP message from `read` (Content-Length framing).
|
||||
async fn dap_read(read: &mut (impl tokio::io::AsyncBufReadExt + Unpin)) -> Value {
|
||||
use tokio::io::AsyncReadExt;
|
||||
let mut length = 0;
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
read.read_line(&mut line).await.unwrap();
|
||||
let line = line.trim_end();
|
||||
if line.is_empty() {
|
||||
break;
|
||||
}
|
||||
length = line.split_once(':').unwrap().1.trim().parse().unwrap();
|
||||
}
|
||||
let mut body = vec![0; length];
|
||||
read.read_exact(&mut body).await.unwrap();
|
||||
serde_json::from_slice(&body).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires OPENIDEA_TEST_PYTHON with real ipykernel (and debugpy)"]
|
||||
async fn the_dap_bridge_speaks_in_cell_uris_and_disconnects_when_closed() {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let manager = manager(root.path());
|
||||
let notebook = root.path().join("bridge.ipynb");
|
||||
let python = python();
|
||||
let helper = "def double(x):\n y = x * 2\n return y\n";
|
||||
let (helper_uri, cell_uri) =
|
||||
("vscode-notebook-cell:/p/bridge.ipynb#helper", "vscode-notebook-cell:/p/bridge.ipynb#call");
|
||||
assert_eq!(run(&manager, ¬ebook, &python, helper).await.0.unwrap().status, "ok");
|
||||
let cells = vec![(helper_uri.to_owned(), helper.to_owned()), (cell_uri.to_owned(), "b = double(21)\n".to_owned())];
|
||||
let stream = ide_notebook::kernel::debug::dap_stream(manager.debugger(¬ebook).unwrap(), move || cells.clone());
|
||||
let (read, mut write) = tokio::io::split(stream);
|
||||
let mut read = tokio::io::BufReader::new(read);
|
||||
let mut seq = 0;
|
||||
let mut request = async |write: &mut tokio::io::WriteHalf<_>, command: &str, arguments: Value| {
|
||||
seq += 1;
|
||||
let body =
|
||||
serde_json::json!({"type": "request", "seq": seq, "command": command, "arguments": arguments}).to_string();
|
||||
write.write_all(format!("Content-Length: {}\r\n\r\n{body}", body.len()).as_bytes()).await.unwrap();
|
||||
seq
|
||||
};
|
||||
async fn until(read: &mut (impl tokio::io::AsyncBufReadExt + Unpin), found: impl Fn(&Value) -> bool) -> Value {
|
||||
loop {
|
||||
let message = tokio::time::timeout(Duration::from_secs(20), dap_read(read)).await.unwrap();
|
||||
if found(&message) {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
}
|
||||
let n = request(&mut write, "initialize", serde_json::json!({"adapterID": "python", "pathFormat": "path"})).await;
|
||||
until(&mut read, |m| m["request_seq"] == n).await;
|
||||
request(&mut write, "attach", serde_json::json!({"justMyCode": true})).await;
|
||||
until(&mut read, |m| m["event"] == "initialized").await;
|
||||
let n = request(
|
||||
&mut write,
|
||||
"setBreakpoints",
|
||||
serde_json::json!({"source": {"path": helper_uri}, "breakpoints": [{"line": 3}]}),
|
||||
)
|
||||
.await;
|
||||
let set = until(&mut read, |m| m["request_seq"] == n).await;
|
||||
assert_eq!(set["body"]["breakpoints"][0]["verified"], true, "{set}");
|
||||
let n = request(&mut write, "configurationDone", serde_json::json!({})).await;
|
||||
until(&mut read, |m| m["request_seq"] == n).await;
|
||||
let running = {
|
||||
let (manager, notebook, python) = (manager.clone(), notebook.clone(), python.clone());
|
||||
tokio::spawn(async move { run(&manager, ¬ebook, &python, "b = double(21)\n").await })
|
||||
};
|
||||
let stopped = until(&mut read, |m| m["event"] == "stopped").await;
|
||||
let n = request(&mut write, "stackTrace", serde_json::json!({"threadId": stopped["body"]["threadId"]})).await;
|
||||
let frames = until(&mut read, |m| m["request_seq"] == n).await;
|
||||
let paths: Vec<_> =
|
||||
frames["body"]["stackFrames"].as_array().unwrap().iter().map(|f| f["source"]["path"].clone()).collect();
|
||||
assert_eq!(paths[..2], [serde_json::json!(helper_uri), serde_json::json!(cell_uri)], "{frames}");
|
||||
let n = request(&mut write, "continue", serde_json::json!({"threadId": stopped["body"]["threadId"]})).await;
|
||||
until(&mut read, |m| m["request_seq"] == n).await;
|
||||
assert_eq!(running.await.unwrap().0.unwrap().status, "ok");
|
||||
// Closed without a disconnect: the bridge sends one, so the breakpoint no longer stops runs.
|
||||
drop((read, write));
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
let (result, outputs) = run(&manager, ¬ebook, &python, "double(5)").await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
assert!(outputs.iter().any(|o| o.kind == "execute_result" && o.content["data"]["text/plain"] == "10"));
|
||||
manager.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires OPENIDEA_TEST_PYTHON and OPENIDEA_TEST_JUPYTER_URL"]
|
||||
async fn a_debugger_opened_after_switching_kernels_survives_the_run() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let manager = manager(root.path());
|
||||
let notebook = root.path().join("switch.ipynb");
|
||||
assert_eq!(run(&manager, ¬ebook, &python(), "x = 1").await.0.unwrap().status, "ok");
|
||||
// The drop-down now names a kernel on a server; Debug Cell starts it before attaching.
|
||||
let (_, _, remote) = remote(None).await;
|
||||
manager.start(¬ebook, remote.clone()).await.unwrap();
|
||||
let mut debugger = manager.debugger(¬ebook).unwrap();
|
||||
let (mut seq, mut events) = (0, Vec::new());
|
||||
assert_eq!(run(&manager, ¬ebook, remote, "y = 2").await.0.unwrap().status, "ok");
|
||||
dap(&mut debugger, &mut seq, &mut events, "initialize", serde_json::json!({"adapterID": "python"})).await;
|
||||
drop(debugger);
|
||||
manager.shutdown_kernel(¬ebook).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires OPENIDEA_TEST_PYTHON with real ipykernel (and debugpy)"]
|
||||
async fn interrupting_a_run_paused_at_a_breakpoint_keeps_the_kernel() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let manager = manager(root.path());
|
||||
let notebook = root.path().join("paused.ipynb");
|
||||
let python = python();
|
||||
let helper = "def double(x):\n y = x * 2\n return y\n";
|
||||
assert_eq!(run(&manager, ¬ebook, &python, &format!("{helper}kept = 7")).await.0.unwrap().status, "ok");
|
||||
let mut debugger = manager.debugger(¬ebook).unwrap();
|
||||
let (mut seq, mut events) = (0, Vec::new());
|
||||
dap(&mut debugger, &mut seq, &mut events, "initialize", serde_json::json!({"adapterID": "python"})).await;
|
||||
dap(&mut debugger, &mut seq, &mut events, "attach", serde_json::json!({})).await;
|
||||
let path =
|
||||
dap(&mut debugger, &mut seq, &mut events, "dumpCell", serde_json::json!({"code": format!("{helper}kept = 7")}))
|
||||
.await;
|
||||
let path = path["body"]["sourcePath"].as_str().unwrap().to_owned();
|
||||
dap(
|
||||
&mut debugger,
|
||||
&mut seq,
|
||||
&mut events,
|
||||
"setBreakpoints",
|
||||
serde_json::json!({"source": {"path": path}, "breakpoints": [{"line": 3}]}),
|
||||
)
|
||||
.await;
|
||||
dap(&mut debugger, &mut seq, &mut events, "configurationDone", serde_json::json!({})).await;
|
||||
let running = {
|
||||
let (manager, notebook, python) = (manager.clone(), notebook.clone(), python.clone());
|
||||
tokio::spawn(async move { run(&manager, ¬ebook, &python, "double(1)").await })
|
||||
};
|
||||
while !events.iter().any(|e| e["event"] == "stopped") {
|
||||
events.push(tokio::time::timeout(Duration::from_secs(20), debugger.receive()).await.unwrap().unwrap());
|
||||
}
|
||||
// The notebook's own Interrupt, not the debug session's Stop.
|
||||
tokio::time::timeout(Duration::from_secs(20), manager.interrupt(¬ebook)).await.unwrap().unwrap();
|
||||
let _ = tokio::time::timeout(Duration::from_secs(20), running).await.unwrap();
|
||||
drop(debugger);
|
||||
let (result, outputs) = run(&manager, ¬ebook, &python, "kept").await;
|
||||
assert_eq!(result.unwrap().status, "ok", "the kernel and its state survive");
|
||||
assert!(outputs.iter().any(|o| o.kind == "execute_result" && o.content["data"]["text/plain"] == "7"));
|
||||
manager.shutdown().await;
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
//! | runtime | profiler | output |
|
||||
//! |---|---|---|
|
||||
//! | Node.js (scripts, npm scripts) | `node --cpu-prof` (via `NODE_OPTIONS`) | `.cpuprofile` JSON |
|
||||
//! | Python | `python -m cProfile -o …`, or `py-spy record --format raw` | pstats, or collapsed stacks |
|
||||
//! | Python | cProfile (`python_profile.py`), or `py-spy record --format raw` | pstats, or collapsed stacks |
|
||||
//! | JVM applications | async-profiler agent (`JAVA_TOOL_OPTIONS`) | collapsed stacks |
|
||||
//! | native / `cargo run` (Linux) | `perf record -g`, then `perf script` | perf script text |
|
||||
//!
|
||||
@@ -140,6 +140,9 @@ pub enum ProfileSpec {
|
||||
/// DevTools, CI) or a `pstats` file (cProfile, profile, yappi), told apart by content.
|
||||
/// Relative source files of a `pstats` file resolve against `root`, then its directory.
|
||||
SnapshotFile { path: IpcPath, root: Option<IpcPath> },
|
||||
/// What `python_profile.py` wrote in `dir` for a profiled Python run: `profile.pstats`.
|
||||
/// Relative source files resolve against `root`.
|
||||
PythonRun { profiler: String, dir: IpcPath, root: IpcPath },
|
||||
/// Collapsed-stack files with extension `ext` in `dir`; relative frame files resolve
|
||||
/// against `base`. `jvm_root`: map JVM class frames to sources below it. For the
|
||||
/// allocation modes the last frame of a JVM stack is the allocated type.
|
||||
@@ -207,11 +210,7 @@ pub fn collect(spec: &ProfileSpec) -> IdeResult<Profile> {
|
||||
let path: &Path = path.as_ref();
|
||||
let name =
|
||||
path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned());
|
||||
let bytes = std::fs::read(path).map_err(|e| match e.kind() {
|
||||
// A profiled run that was killed (a second Stop) or left through `os._exit`.
|
||||
std::io::ErrorKind::NotFound => nothing_recorded(&format!("{name} was not written")),
|
||||
_ => IdeError::invalid(format!("Cannot read {name}: {e}")),
|
||||
})?;
|
||||
let bytes = std::fs::read(path).map_err(|e| IdeError::invalid(format!("Cannot read {name}: {e}")))?;
|
||||
let ext = path.extension().map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default();
|
||||
// The content decides (`node --cpu-prof-name=cpu.prof` writes JSON); the extension only
|
||||
// names what a file that is neither failed to be.
|
||||
@@ -240,6 +239,20 @@ pub fn collect(spec: &ProfileSpec) -> IdeResult<Profile> {
|
||||
}
|
||||
Ok(profile)
|
||||
}
|
||||
ProfileSpec::PythonRun { profiler, dir, root } => {
|
||||
let bytes = std::fs::read(Path::new(dir.as_ref()).join("profile.pstats")).map_err(|e| match e.kind() {
|
||||
// A run that was killed (a second Stop) or left through `os._exit`.
|
||||
std::io::ErrorKind::NotFound => nothing_recorded(&format!("{profiler} wrote no profile")),
|
||||
_ => IdeError::invalid(format!("Cannot read the {profiler} profile: {e}")),
|
||||
})?;
|
||||
let bases: [&Path; 2] = [root.as_ref(), dir.as_ref()];
|
||||
let profile = pstats::read(&bytes, &bases, profiler)
|
||||
.map_err(|e| IdeError::invalid(format!("Cannot read the {profiler} profile: {e}")))?;
|
||||
if profile.methods.is_empty() {
|
||||
return Err(nothing_recorded(&format!("{profiler} recorded no calls")));
|
||||
}
|
||||
Ok(profile)
|
||||
}
|
||||
ProfileSpec::Folded { profiler, dir, ext, base, jvm_root, mode } => {
|
||||
for f in files_with_ext(dir, ext) {
|
||||
formats::add_folded(&mut b, &std::fs::read_to_string(&f)?, base, *mode != ProfileMode::Cpu);
|
||||
@@ -359,7 +372,7 @@ mod tests {
|
||||
}
|
||||
let missing =
|
||||
collect(&ProfileSpec::SnapshotFile { path: dir.path().join("gone.cpuprofile").into(), root: None });
|
||||
assert_eq!(missing.unwrap_err().message, "The run produced no profile (gone.cpuprofile was not written).");
|
||||
assert!(missing.unwrap_err().message.starts_with("Cannot read gone.cpuprofile"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -7,6 +7,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
const ASYNC_PROFILER_HOME: &str = "https://github.com/async-profiler/async-profiler/releases";
|
||||
const PY_SPY_HOME: &str = "https://github.com/benfred/py-spy";
|
||||
const PYTHON_LAUNCHER: &str = include_str!("python_profile.py");
|
||||
|
||||
fn s(v: &str) -> String {
|
||||
v.to_owned()
|
||||
@@ -140,17 +141,50 @@ fn python(
|
||||
ready("py-spy", launch, spec)
|
||||
}
|
||||
|
||||
/// `python -m cProfile -o <out>/profile.pstats <script or -m module> …` with the configuration's
|
||||
/// own interpreter (`uv run python`, a virtualenv's). cProfile writes the file when the program
|
||||
/// ends, also when Stop interrupts it.
|
||||
/// Runs the script, module or `-c` code under cProfile with the configuration's own interpreter
|
||||
/// (`uv run python`, a virtualenv's) through `python_profile.py`, written to `out`.
|
||||
/// `python -m cProfile` would end every run with exit code 0, take no `-c` and not run a
|
||||
/// module as `__main__`. The profile is written when the program ends, also when Stop
|
||||
/// interrupts it.
|
||||
fn cprofile(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) -> ProfilePrepared {
|
||||
let file = out.join("profile.pstats");
|
||||
python_launcher(config, dir, out, py, "cprofile", "cProfile")
|
||||
}
|
||||
|
||||
fn python_launcher(
|
||||
config: &RunConfig,
|
||||
dir: &Path,
|
||||
out: &Path,
|
||||
py: wrap::PythonCommand,
|
||||
mode: &str,
|
||||
profiler: &str,
|
||||
) -> ProfilePrepared {
|
||||
let launcher = out.join("python_profile.py");
|
||||
if let Err(e) = std::fs::write(&launcher, PYTHON_LAUNCHER) {
|
||||
return unsupported(format!("Cannot write {}: {e}", launcher.display()));
|
||||
}
|
||||
let mut argv = py.interpreter;
|
||||
argv.extend([s("-m"), s("cProfile"), s("-o"), path(&file)]);
|
||||
argv.extend([path(&launcher), s(mode), path(out)]);
|
||||
let mut launch = config.clone();
|
||||
// Stop on Windows ends the process tree at once; the configuration's stop command
|
||||
// runs first, and the launcher saves the profile when the command opens its pipe.
|
||||
if cfg!(windows) && launch.extras.stop_command.is_none() {
|
||||
let pipe = stop_pipe(out);
|
||||
launch.extras.stop_command = Some(format!("type nul > \"{pipe}\""));
|
||||
argv.extend([s("--stop"), pipe]);
|
||||
}
|
||||
argv.extend(py.target);
|
||||
let (command, args) = argv.split_first().map(|(c, a)| (c.clone(), a.to_vec())).unwrap_or_default();
|
||||
let launch = RunConfig { command, args, ..config.clone() };
|
||||
ready("cProfile", launch, ProfileSpec::SnapshotFile { path: file.into(), root: Some(dir.to_path_buf().into()) })
|
||||
(launch.command, launch.args) = argv.split_first().map(|(c, a)| (c.clone(), a.to_vec())).unwrap_or_default();
|
||||
let spec =
|
||||
ProfileSpec::PythonRun { profiler: s(profiler), dir: out.to_path_buf().into(), root: dir.to_path_buf().into() };
|
||||
ready(profiler, launch, spec)
|
||||
}
|
||||
|
||||
/// The named pipe a Windows Profile run waits on for Stop, one per profile directory.
|
||||
fn stop_pipe(out: &Path) -> String {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
out.hash(&mut hasher);
|
||||
format!(r"\\.\pipe\openidea-profile-{:016x}", hasher.finish())
|
||||
}
|
||||
|
||||
/// `libasyncProfiler.{so,dylib}` from `ASYNC_PROFILER_HOME` or next to `asprof` on the search path.
|
||||
@@ -376,15 +410,18 @@ mod tests {
|
||||
std::fs::write(&python, "").unwrap();
|
||||
let mut c = cfg("python", &python, &["-X", "utf8", "main.py", "--fast"]);
|
||||
c.env.insert("PATH".into(), dir.path().join("nothing").to_string_lossy().into_owned());
|
||||
let file = dir.path().join("profile.pstats").to_string_lossy().into_owned();
|
||||
|
||||
// Nothing installed: cProfile, whatever the platform.
|
||||
let (profiler, launch, spec) = python_plan(&c, dir.path(), "auto");
|
||||
assert_eq!(profiler, "cProfile");
|
||||
assert_eq!(launch.command, python);
|
||||
assert_eq!(launch.args, ["-X", "utf8", "-m", "cProfile", "-o", &file, "main.py", "--fast"]);
|
||||
let root = Some(dir.path().to_path_buf().into());
|
||||
assert_eq!(spec, ProfileSpec::SnapshotFile { path: PathBuf::from(&file).into(), root });
|
||||
assert_eq!(
|
||||
launch.args,
|
||||
[v(&["-X", "utf8"]), launcher_args(dir.path(), "cprofile"), v(&["main.py", "--fast"])].concat()
|
||||
);
|
||||
assert_eq!(std::fs::read_to_string(dir.path().join("python_profile.py")).unwrap(), PYTHON_LAUNCHER);
|
||||
let (out, root) = (dir.path().to_path_buf().into(), dir.path().to_path_buf().into());
|
||||
assert_eq!(spec, ProfileSpec::PythonRun { profiler: "cProfile".into(), dir: out, root });
|
||||
assert_eq!(launch.extras.stop_command.is_some(), cfg!(windows));
|
||||
|
||||
// py-spy installed: Automatic takes it except on macOS, where it would need root.
|
||||
std::fs::write(bin.join(if cfg!(windows) { "py-spy.exe" } else { "py-spy" }), "").unwrap();
|
||||
@@ -397,18 +434,38 @@ mod tests {
|
||||
#[test]
|
||||
fn cprofile_keeps_the_configurations_interpreter() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("profile.pstats").to_string_lossy().into_owned();
|
||||
let launch = |c: RunConfig| python_plan(&c, dir.path(), "cprofile").1;
|
||||
let profiled = launcher_args(dir.path(), "cprofile");
|
||||
|
||||
let uv = launch(cfg("python", "uv", &["run", "--frozen", "python", "-m", "app.cli", "serve"]));
|
||||
assert_eq!(uv.command, "uv");
|
||||
assert_eq!(uv.args, ["run", "--frozen", "python", "-m", "cProfile", "-o", &file, "-m", "app.cli", "serve"]);
|
||||
assert_eq!(
|
||||
uv.args,
|
||||
[v(&["run", "--frozen", "python"]), profiled.clone(), v(&["-m", "app.cli", "serve"])].concat()
|
||||
);
|
||||
|
||||
let bin = dir.path().join(".venv/bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
let pytest = launch(cfg("pytest", &bin.join("pytest").to_string_lossy(), &["tests", "-k", "slow"]));
|
||||
assert!(Path::new(&pytest.command).starts_with(&bin), "{}", pytest.command);
|
||||
assert_eq!(pytest.args, ["-m", "cProfile", "-o", &file, "-m", "pytest", "tests", "-k", "slow"]);
|
||||
assert_eq!(pytest.args, [profiled.clone(), v(&["-m", "pytest", "tests", "-k", "slow"])].concat());
|
||||
|
||||
// `-c` code is what runs, not an interpreter option.
|
||||
let code = launch(cfg("python", "python3", &["-u", "-c", "print(1)", "x"]));
|
||||
assert_eq!(code.args, [v(&["-u"]), profiled, v(&["-c", "print(1)", "x"])].concat());
|
||||
}
|
||||
|
||||
fn v(args: &[&str]) -> Vec<String> {
|
||||
args.iter().map(|a| s(a)).collect()
|
||||
}
|
||||
|
||||
/// `python_profile.py <mode> <out> [--stop <pipe>]`, as the launch passes them.
|
||||
fn launcher_args(out: &Path, mode: &str) -> Vec<String> {
|
||||
let mut args = vec![path(&out.join("python_profile.py")), s(mode), path(out)];
|
||||
if cfg!(windows) {
|
||||
args.extend([s("--stop"), stop_pipe(out)]);
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Runs a script, module (-m) or code (-c) under a profiler for the IDE's Profile action.
|
||||
|
||||
Usage: python python_profile.py cprofile <out dir> [--stop <pipe>] (<script> | -m <module> | -c <code>) [args...]
|
||||
|
||||
Runs the target as `python <target>` would (it is `__main__` until the process exits, its
|
||||
exit code is kept) and writes <out>/profile.pstats when it ends, also when Stop interrupts
|
||||
it (KeyboardInterrupt).
|
||||
`--stop`: where Stop cannot interrupt the process itself (Windows), its stop command opens
|
||||
this named pipe (a FIFO elsewhere); the profile is then saved and the run interrupted.
|
||||
"""
|
||||
|
||||
import _thread
|
||||
import io
|
||||
import os
|
||||
import runpy
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import types
|
||||
|
||||
|
||||
def as_main(**names):
|
||||
"""A fresh `__main__` module that stays in `sys.modules` until the process exits, as
|
||||
Python's own is: threads, atexit callbacks and pickling still find the target there."""
|
||||
main = types.ModuleType("__main__")
|
||||
main.__dict__.update(names)
|
||||
sys.modules["__main__"] = main
|
||||
return main.__dict__
|
||||
|
||||
|
||||
def run(target):
|
||||
isolated = sys.flags.isolated or getattr(sys.flags, "safe_path", False)
|
||||
if target[0] == "-m":
|
||||
if not isolated:
|
||||
sys.path[0] = os.getcwd()
|
||||
# What `python -m` and runpy use to find a module or a package's __main__.
|
||||
_, spec, code = runpy._get_module_details(target[1])
|
||||
sys.argv = [spec.origin] + target[2:]
|
||||
names = as_main(
|
||||
__file__=spec.origin, __cached__=spec.cached, __loader__=spec.loader, __package__=spec.parent, __spec__=spec
|
||||
)
|
||||
exec(code, names)
|
||||
elif target[0] == "-c":
|
||||
sys.argv = ["-c"] + target[2:]
|
||||
if not isolated:
|
||||
sys.path[0] = ""
|
||||
exec(compile(target[1], "<string>", "exec"), as_main())
|
||||
else:
|
||||
sys.argv = target
|
||||
if not isolated:
|
||||
sys.path[0] = os.path.dirname(os.path.abspath(target[0]))
|
||||
if os.path.isdir(target[0]) or target[0].endswith((".zip", ".pyz")):
|
||||
# Its __main__.py; runpy puts the launcher back as __main__ when it returns.
|
||||
runpy.run_path(target[0], run_name="__main__")
|
||||
return
|
||||
with io.open_code(target[0]) as source:
|
||||
code = compile(source.read(), target[0], "exec")
|
||||
exec(code, as_main(__file__=target[0], __cached__=None))
|
||||
|
||||
|
||||
class Once:
|
||||
"""Saves the profile once: when the run ends, or from the stop watcher if it doesn't."""
|
||||
|
||||
def __init__(self, save):
|
||||
self.save, self.lock, self.done = save, threading.Lock(), False
|
||||
|
||||
def __call__(self):
|
||||
with self.lock:
|
||||
if not self.done:
|
||||
self.done = True
|
||||
self.save()
|
||||
|
||||
|
||||
def stop_waiter(name):
|
||||
"""Opens `name` and returns a call that blocks, in C, until Stop connects to it. Since 3.12
|
||||
cProfile records every thread on one call stack, so a watcher that polled would show up
|
||||
in the profile, charged to the program's own functions."""
|
||||
if os.name == "nt":
|
||||
import _winapi
|
||||
|
||||
# A byte pipe: PIPE_TYPE_BYTE is 0, and _winapi doesn't export it.
|
||||
pipe = _winapi.CreateNamedPipe(name, _winapi.PIPE_ACCESS_INBOUND, _winapi.PIPE_WAIT, 1, 0, 0, 0, _winapi.NULL)
|
||||
|
||||
def wait():
|
||||
try:
|
||||
_winapi.ConnectNamedPipe(pipe, False)
|
||||
except OSError as e:
|
||||
if e.winerror != 535: # ERROR_PIPE_CONNECTED: Stop connected first
|
||||
raise
|
||||
|
||||
return wait
|
||||
os.mkfifo(name)
|
||||
return lambda: os.open(name, os.O_RDONLY)
|
||||
|
||||
|
||||
def watch(wait, ready, save):
|
||||
ready.set()
|
||||
wait()
|
||||
# Saved first: Stop ends the process after its termination timeout, which can be short.
|
||||
save()
|
||||
_thread.interrupt_main()
|
||||
# A run blocked in a call that the interrupt does not wake is ended here.
|
||||
time.sleep(1.5)
|
||||
os._exit(130)
|
||||
|
||||
|
||||
def cprofile(out):
|
||||
import cProfile
|
||||
|
||||
profiler = cProfile.Profile()
|
||||
|
||||
def save():
|
||||
profiler.disable()
|
||||
profiler.dump_stats(os.path.join(out, "profile.pstats"))
|
||||
|
||||
return profiler.enable, save
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
profiler, out, target = args[0], args[1], args[2:]
|
||||
stop_file = None
|
||||
if target[:1] == ["--stop"]:
|
||||
stop_file, target = target[1], target[2:]
|
||||
start, save = {"cprofile": cprofile}[profiler](out)
|
||||
save = Once(save)
|
||||
if stop_file:
|
||||
# The watcher blocks before profiling starts, so it stays out of the profile.
|
||||
ready = threading.Event()
|
||||
threading.Thread(target=watch, args=(stop_waiter(stop_file), ready, save), daemon=True).start()
|
||||
ready.wait()
|
||||
start()
|
||||
try:
|
||||
run(target)
|
||||
finally:
|
||||
save()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,11 +1,10 @@
|
||||
//! Profiling `fixtures/python-profiling` under cProfile with a real Python 3, to the end and
|
||||
//! when Stop interrupts it. Without `python3` (`python` on Windows) on the search path the
|
||||
//! when Stop interrupts it; exit codes, `-c` code and `-m` modules run as Python runs them. Without `python3` (`python` on Windows) on the search path the
|
||||
//! tests return early.
|
||||
|
||||
use ide_profiler::{Profile, ProfileMode, ProfilePrepared, collect, prepare};
|
||||
use ide_run::RunConfig;
|
||||
use std::collections::BTreeMap;
|
||||
#[cfg(unix)]
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
@@ -93,3 +92,90 @@ fn a_stopped_run_still_writes_its_profile() {
|
||||
// One completed fib(22) followed by one completed fib(18).
|
||||
assert!(method(&p, "fib").calls.unwrap() >= 65_674.0, "both completed passes were profiled");
|
||||
}
|
||||
|
||||
/// Waits up to a minute: a run that hangs fails the test instead of the whole suite.
|
||||
fn finish(mut child: std::process::Child) -> std::process::ExitStatus {
|
||||
for _ in 0..600 {
|
||||
if let Some(status) = child.try_wait().unwrap() {
|
||||
return status;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
child.kill().unwrap();
|
||||
panic!("the profiled run did not end");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_runs_exit_code_and_c_code_are_kept() {
|
||||
let Some(python) = python() else { return };
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let (mut cmd, spec) =
|
||||
plan(&python, &["-c", "import sys\ndef work(): return sum(range(9))\nwork()\nsys.exit(3)"], out.path());
|
||||
assert_eq!(finish(cmd.spawn().unwrap()).code(), Some(3));
|
||||
let p = collect(&spec).unwrap();
|
||||
assert_eq!(method(&p, "work (<string>:2)").calls, Some(1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_stays_main_so_multiprocessing_and_atexit_find_its_functions() {
|
||||
let Some(python) = python() else { return };
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
std::fs::write(
|
||||
project.path().join("pooled.py"),
|
||||
"import atexit, multiprocessing as mp, pickle\n\ndef square(x):\n return x * x\n\nif __name__ == '__main__':\n with mp.get_context('spawn').Pool(2) as pool:\n print(pool.map(square, [1, 2, 3]))\n atexit.register(lambda: print(len(pickle.dumps(square)) > 0))\n",
|
||||
)
|
||||
.unwrap();
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let (mut cmd, spec) = plan(&python, &["-m", "pooled"], out.path());
|
||||
// A free-threaded CPython (3.14t) hangs a Pool under cProfile, with `-m cProfile` too.
|
||||
cmd.current_dir(project.path()).env("PYTHON_GIL", "1");
|
||||
let mut child = cmd.spawn().unwrap();
|
||||
let mut printed = String::new();
|
||||
std::io::Read::read_to_string(&mut child.stdout.take().unwrap(), &mut printed).unwrap();
|
||||
// The module is still `__main__` when atexit callbacks pickle its functions.
|
||||
assert_eq!(printed.lines().collect::<Vec<_>>(), ["[1, 4, 9]", "True"]);
|
||||
assert!(finish(child).success());
|
||||
collect(&spec).unwrap();
|
||||
}
|
||||
|
||||
/// What Stop does on Windows: its stop command opens the pipe the launcher waits on (a FIFO
|
||||
/// elsewhere). The profile is saved and the run interrupted; the watcher thread that waited
|
||||
/// for Stop stays out of the profile.
|
||||
#[test]
|
||||
fn the_stop_pipe_ends_the_run_and_keeps_its_profile() {
|
||||
let Some(python) = python() else { return };
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let code = "print('started', flush=True)\nwhile True:\n sum(range(1000))";
|
||||
let c = config(&python, &["-c", code]);
|
||||
let ProfilePrepared::Ready { mut launch, spec, .. } =
|
||||
prepare(&fixture(), &c, out.path(), ProfileMode::Cpu, "cprofile")
|
||||
else {
|
||||
panic!("not ready");
|
||||
};
|
||||
let fifo = out.path().join("stop");
|
||||
if launch.extras.stop_command.is_none() {
|
||||
let at = launch.args.iter().position(|a| a == "-c").unwrap();
|
||||
launch.args.splice(at..at, ["--stop".to_owned(), fifo.to_string_lossy().into_owned()]);
|
||||
}
|
||||
let mut cmd = Command::new(&launch.command);
|
||||
cmd.args(&launch.args).current_dir(fixture()).stdout(Stdio::piped());
|
||||
let mut child = cmd.spawn().unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(child.stdout.take().unwrap()).read_line(&mut line).unwrap();
|
||||
assert_eq!(line.trim(), "started");
|
||||
// A watcher that polled would be profiled meanwhile, charged to the program's frames.
|
||||
std::thread::sleep(std::time::Duration::from_millis(500));
|
||||
match &launch.extras.stop_command {
|
||||
#[cfg(windows)]
|
||||
Some(stop) => {
|
||||
use std::os::windows::process::CommandExt;
|
||||
assert!(Command::new("cmd").arg("/C").raw_arg(stop).status().unwrap().success());
|
||||
}
|
||||
_ => drop(std::fs::OpenOptions::new().write(true).open(&fifo).unwrap()),
|
||||
}
|
||||
assert!(!finish(child).success());
|
||||
let p = collect(&spec).unwrap();
|
||||
let names: Vec<_> = p.methods.iter().map(|m| p.frames[m.frame as usize].name.as_str()).collect();
|
||||
assert!(names.iter().any(|n| n.contains("sum")), "{names:?}");
|
||||
assert!(!names.iter().any(|n| ["sleep", "exists", "watch"].iter().any(|w| n.contains(w))), "{names:?}");
|
||||
}
|
||||
@@ -24,6 +24,11 @@ pub struct ContainerRun<'a> {
|
||||
pub endpoint_env: &'a BTreeMap<String, String>,
|
||||
/// Variables of the configuration's `.env` files, already read.
|
||||
pub file_env: &'a BTreeMap<String, String>,
|
||||
/// Variables the container gets elsewhere: the Compose service's `environment`, and the
|
||||
/// `.env` / `.flaskenv` a development server reads. Not passed: only consulted.
|
||||
pub service_env: &'a BTreeMap<String, String>,
|
||||
/// The Compose service's published ports: `(port here, port in the container)`.
|
||||
pub service_ports: &'a [(u16, u16)],
|
||||
/// Container name, unique per run.
|
||||
pub name: &'a str,
|
||||
/// `--user uid:gid`; `None` keeps the image's user.
|
||||
@@ -61,6 +66,100 @@ pub fn default_container_root(root: &Path) -> String {
|
||||
format!("/workspaces/{}", if name.is_empty() { "project" } else { &name })
|
||||
}
|
||||
|
||||
/// The file here of `container_path` (a traceback line), through the mount whose container
|
||||
/// folder is the longest prefix of it: `(folder here, folder in the container)`. `None`
|
||||
/// outside every mount, and for `..`.
|
||||
pub fn mounted_file(container_path: &str, mounts: &[(std::path::PathBuf, String)]) -> Option<std::path::PathBuf> {
|
||||
let (local, rest) = mounts
|
||||
.iter()
|
||||
.filter_map(|(local, folder)| {
|
||||
let rest = container_path.strip_prefix(folder.trim_end_matches('/'))?.strip_prefix('/')?;
|
||||
Some((local, folder.trim_end_matches('/').len(), rest))
|
||||
})
|
||||
.max_by_key(|(_, len, _)| *len)
|
||||
.map(|(local, _, rest)| (local, rest))?;
|
||||
let parts: Vec<&str> = rest.split('/').filter(|c| !c.is_empty() && *c != ".").collect();
|
||||
(!parts.is_empty() && !parts.contains(&"..")).then(|| parts.iter().fold(local.clone(), |p, c| p.join(c)))
|
||||
}
|
||||
|
||||
/// A development server `program args` runs, and the port it listens on in the container.
|
||||
/// They listen on `127.0.0.1` by default, which a published port can't reach: Django's
|
||||
/// `runserver`, `flask run`, `uvicorn` and `fastapi dev` are made to listen on all interfaces
|
||||
/// unless the command, or a variable `set` finds (the configuration, its env files, the
|
||||
/// service's `environment`, `.env` / `.flaskenv`), already chooses an address.
|
||||
fn dev_server(
|
||||
program: &str,
|
||||
args: &mut Vec<String>,
|
||||
env: &mut BTreeMap<String, String>,
|
||||
set: &dyn Fn(&str) -> Option<String>,
|
||||
) -> Option<u16> {
|
||||
let name = |s: &str| s.rsplit('/').next().unwrap_or(s).trim_end_matches(".py").to_owned();
|
||||
// `words[0]` is the program: `words[i]` is `args[i - 1]`.
|
||||
let words: Vec<String> = std::iter::once(program).chain(args.iter().map(String::as_str)).map(name).collect();
|
||||
let option = |args: &[String], names: &[&str]| -> Option<String> {
|
||||
args.iter().enumerate().find_map(|(i, a)| {
|
||||
names.iter().find_map(|n| {
|
||||
if a == n { args.get(i + 1).cloned() } else { a.strip_prefix(&format!("{n}=")).map(str::to_owned) }
|
||||
})
|
||||
})
|
||||
};
|
||||
let port = |given: Option<String>, default: u16| given.and_then(|p| p.trim().parse().ok()).unwrap_or(default);
|
||||
// The word after `tool` and its options (`flask --app x run`): its index in `words`.
|
||||
let subcommand = |tool: &[&str], sub: &[&str]| {
|
||||
let start = words.iter().position(|w| tool.contains(&w.as_str()))? + 1;
|
||||
let mut i = start;
|
||||
while let Some(w) = words.get(i).filter(|w| w.starts_with('-')) {
|
||||
i += if matches!(w.as_str(), "--app" | "-A" | "--env-file" | "-e") { 2 } else { 1 };
|
||||
}
|
||||
words.get(i).filter(|w| sub.contains(&w.as_str())).map(|_| i - 1)
|
||||
};
|
||||
if let Some(i) = subcommand(&["manage", "django-admin", "django"], &["runserver"]) {
|
||||
// The first positional argument after `runserver` is `[address:]port`.
|
||||
let mut at = i + 1;
|
||||
while let Some(a) = args.get(at) {
|
||||
if matches!(a.as_str(), "--settings" | "--pythonpath" | "-v" | "--verbosity") {
|
||||
at += 2;
|
||||
} else if a.starts_with('-') {
|
||||
at += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return Some(match args.get(at).cloned() {
|
||||
None => {
|
||||
args.insert(i + 1, "0.0.0.0:8000".into());
|
||||
8000
|
||||
}
|
||||
Some(p) if p.chars().all(|c| c.is_ascii_digit()) => {
|
||||
args[at] = format!("0.0.0.0:{p}");
|
||||
port(Some(p), 8000)
|
||||
}
|
||||
Some(address) => port(address.rsplit(':').next().map(str::to_owned), 8000),
|
||||
});
|
||||
}
|
||||
let host = option(args, &["--host", "-h"]).is_some();
|
||||
if subcommand(&["flask"], &["run"]).is_some() {
|
||||
if !host && set("FLASK_RUN_HOST").is_none() {
|
||||
env.insert("FLASK_RUN_HOST".into(), "0.0.0.0".into());
|
||||
}
|
||||
return Some(port(option(args, &["--port", "-p"]).or_else(|| set("FLASK_RUN_PORT")), 5000));
|
||||
}
|
||||
if words.iter().any(|w| w == "uvicorn") {
|
||||
if !host && set("UVICORN_HOST").is_none() {
|
||||
env.insert("UVICORN_HOST".into(), "0.0.0.0".into());
|
||||
}
|
||||
return Some(port(option(args, &["--port"]).or_else(|| set("UVICORN_PORT")), 8000));
|
||||
}
|
||||
if let Some(i) = subcommand(&["fastapi"], &["dev", "run"]) {
|
||||
// `fastapi run` listens on all interfaces already.
|
||||
if !host && words[i + 1] == "dev" {
|
||||
args.extend(["--host".into(), "0.0.0.0".into()]);
|
||||
}
|
||||
return Some(port(option(args, &["--port"]), 8000));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A container name for a run of `config_id`: Docker allows `[a-zA-Z0-9][a-zA-Z0-9_.-]*`.
|
||||
pub fn container_name(config_id: &str, unique: &str) -> String {
|
||||
let id: String = config_id
|
||||
@@ -74,13 +173,19 @@ pub fn container_name(config_id: &str, unique: &str) -> String {
|
||||
/// `config` as a local run of the docker CLI that runs it in a new container.
|
||||
pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<RunConfig> {
|
||||
let target = run.target;
|
||||
let command = remote_command(config, target, run.root, run.container_root);
|
||||
let mut command = remote_command(config, target, run.root, run.container_root);
|
||||
let set = |key: &str| [&command.env, run.file_env, run.service_env].into_iter().find_map(|e| e.get(key).cloned());
|
||||
let mut added = BTreeMap::new();
|
||||
let server = if command.shell_line.is_none() {
|
||||
dev_server(&command.program.clone(), &mut command.args, &mut added, &set)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
command.env.extend(added);
|
||||
// Variables go by name (`-e NAME`) so their values stay out of the command line
|
||||
// echoed in the console; the docker CLI reads them from its own environment.
|
||||
let mut env: BTreeMap<String, String> = run.file_env.clone();
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "doctest" | "django-test")
|
||||
&& !command.env.contains_key("PYTHONUNBUFFERED")
|
||||
{
|
||||
if ide_run::is_python_kind(&config.kind) && !command.env.contains_key("PYTHONUNBUFFERED") {
|
||||
env.insert("PYTHONUNBUFFERED".into(), "1".into());
|
||||
}
|
||||
env.extend(command.env.clone());
|
||||
@@ -128,6 +233,13 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
|
||||
for port in target.ports.iter().map(|p| p.trim()).filter(|p| !p.is_empty()) {
|
||||
args.extend(["--publish".into(), port.to_owned()]);
|
||||
}
|
||||
// A development server on a target without ports of its own: its port, on this machine's
|
||||
// loopback interface only (the service's mapping when it has one; `compose run` publishes
|
||||
// none of them).
|
||||
if let Some(port) = server.filter(|_| target.ports.iter().all(|p| p.trim().is_empty())) {
|
||||
let here = run.service_ports.iter().find(|(_, inside)| *inside == port).map_or(port, |(here, _)| *here);
|
||||
args.extend(["--publish".into(), format!("127.0.0.1:{here}:{port}")]);
|
||||
}
|
||||
if let Some((uid, gid)) = run.user {
|
||||
args.extend(["--user".into(), format!("{uid}:{gid}")]);
|
||||
}
|
||||
@@ -156,7 +268,15 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
|
||||
}
|
||||
(Some(line), None) => args.extend(["sh".into(), "-c".into(), line]),
|
||||
(None, Some(debug)) => {
|
||||
args.extend(debug_command(&command.program, &command.args, target, debug.port, run.container_root)?)
|
||||
let bootstrap = format!("{DEBUG_DIR}/{DEBUG_BOOTSTRAP_NAME}");
|
||||
args.extend(debug_command(
|
||||
&command.program,
|
||||
&command.args,
|
||||
target,
|
||||
debug.port,
|
||||
run.container_root,
|
||||
&bootstrap,
|
||||
)?)
|
||||
}
|
||||
(None, None) => {
|
||||
args.push(command.program);
|
||||
@@ -227,16 +347,17 @@ fn is_python(program: &str) -> bool {
|
||||
name == "python" || name == "python2" || name.starts_with("python3")
|
||||
}
|
||||
|
||||
/// The container's command line that runs `program args` under [`DEBUG_BOOTSTRAP`]:
|
||||
/// `python [options] <bootstrap> <port> <folder> (script | -m module | -c code) args`.
|
||||
/// The command line that runs `program args` under [`DEBUG_BOOTSTRAP`] (at `bootstrap` in the
|
||||
/// container or on the SSH host): `python [options] <bootstrap> <port> <folder> (script | -m module | -c code) args`.
|
||||
/// A console script (`pytest`) runs as a module of the interpreter next to it, or of the
|
||||
/// target's; `uv run …` and the like keep the manager in front.
|
||||
fn debug_command(
|
||||
pub(crate) fn debug_command(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
target: &RunTarget,
|
||||
port: u16,
|
||||
folder: &str,
|
||||
bootstrap: &str,
|
||||
) -> IdeResult<Vec<String>> {
|
||||
let tool_module = |tool: &str, rest: &[String]| -> Vec<String> {
|
||||
let module = tool.rsplit('/').next().unwrap_or(tool).to_owned();
|
||||
@@ -250,7 +371,7 @@ fn debug_command(
|
||||
{
|
||||
if args[1].starts_with('-') {
|
||||
return Err(IdeError::invalid(
|
||||
"container debugging does not support runner options before the executable: use `uv run python script.py` or `uv run pytest` with options after the script or module",
|
||||
"debugging on a run target does not support runner options before the executable: use `uv run python script.py` or `uv run pytest` with options after the script or module",
|
||||
));
|
||||
}
|
||||
if is_python(&args[1]) {
|
||||
@@ -286,7 +407,7 @@ fn debug_command(
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
line.extend([format!("{DEBUG_DIR}/{DEBUG_BOOTSTRAP_NAME}"), port.to_string(), folder.to_owned()]);
|
||||
line.extend([bootstrap.to_owned(), port.to_string(), folder.to_owned()]);
|
||||
line.extend(rest.iter().cloned());
|
||||
Ok(line)
|
||||
}
|
||||
@@ -303,28 +424,55 @@ fn shell_word(word: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The project's folder in the container of a Compose `service`, from the JSON of
|
||||
/// `docker compose config --format json`: the target of a bind mount of the project
|
||||
/// or a folder above it.
|
||||
pub fn compose_container_root(config_json: &str, service: &str, root: &Path) -> IdeResult<String> {
|
||||
/// What `docker compose config --format json` says of a service.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ComposeService {
|
||||
/// Bind mounts: `(source here, target in the container)`.
|
||||
pub mounts: Vec<(String, String)>,
|
||||
/// Published ports: `(port here, port in the container)`.
|
||||
pub ports: Vec<(u16, u16)>,
|
||||
/// `environment:` (a variable without a value is empty).
|
||||
pub environment: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// The mounts, ports and environment of a Compose `service`, from the JSON of `docker
|
||||
/// compose config --format json`.
|
||||
pub fn compose_service(config_json: &str, service: &str) -> IdeResult<ComposeService> {
|
||||
let model: serde_json::Value = serde_json::from_str(config_json)
|
||||
.map_err(|e| IdeError::internal(format!("cannot read `docker compose config`: {e}")))?;
|
||||
let Some(svc) = model.pointer(&format!("/services/{}", service.replace('~', "~0").replace('/', "~1"))) else {
|
||||
return Err(IdeError::not_found(format!("the Compose files have no service '{service}'")));
|
||||
};
|
||||
let mounts = svc.get("volumes").and_then(|v| v.as_array()).into_iter().flatten();
|
||||
let list = |key: &str| svc.get(key).and_then(|v| v.as_array()).into_iter().flatten();
|
||||
let number = |v: Option<&serde_json::Value>| match v? {
|
||||
serde_json::Value::Number(n) => n.as_u64().and_then(|n| u16::try_from(n).ok()),
|
||||
serde_json::Value::String(s) => s.parse().ok(),
|
||||
_ => None,
|
||||
};
|
||||
Ok(ComposeService {
|
||||
mounts: list("volumes")
|
||||
.filter(|m| m.get("type").and_then(|t| t.as_str()) == Some("bind"))
|
||||
.filter_map(|m| Some((m.get("source")?.as_str()?.to_owned(), m.get("target")?.as_str()?.to_owned())))
|
||||
.collect(),
|
||||
ports: list("ports").filter_map(|p| Some((number(p.get("published"))?, number(p.get("target"))?))).collect(),
|
||||
environment: svc
|
||||
.get("environment")
|
||||
.and_then(|e| e.as_object())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|(k, v)| (k.clone(), v.as_str().unwrap_or_default().to_owned()))
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The project's folder in the container of a Compose `service`, from the JSON of
|
||||
/// `docker compose config --format json`: the target of a bind mount of the project
|
||||
/// or a folder above it.
|
||||
pub fn compose_container_root(config_json: &str, service: &str, root: &Path) -> IdeResult<String> {
|
||||
let mut best: Option<(usize, String)> = None;
|
||||
for m in mounts {
|
||||
if m.get("type").and_then(|t| t.as_str()) != Some("bind") {
|
||||
continue;
|
||||
}
|
||||
let (Some(source), Some(target)) =
|
||||
(m.get("source").and_then(|s| s.as_str()), m.get("target").and_then(|t| t.as_str()))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Ok(rel) = root.strip_prefix(source) else { continue };
|
||||
let depth = Path::new(source).components().count();
|
||||
for (source, target) in compose_service(config_json, service)?.mounts {
|
||||
let Ok(rel) = root.strip_prefix(&source) else { continue };
|
||||
let depth = Path::new(&source).components().count();
|
||||
if best.as_ref().is_none_or(|(d, _)| depth > *d) {
|
||||
let rel = crate::mapping::posix(rel);
|
||||
let target = target.trim_end_matches('/');
|
||||
@@ -380,6 +528,8 @@ mod tests {
|
||||
docker: "/usr/local/bin/docker",
|
||||
endpoint_env: endpoint,
|
||||
file_env: files,
|
||||
service_env: files,
|
||||
service_ports: &[],
|
||||
name: "openidea-app-1",
|
||||
user: Some((501, 20)),
|
||||
debug: None,
|
||||
@@ -466,6 +616,27 @@ mod tests {
|
||||
);
|
||||
assert_eq!(out.env["DATA"], "/app/data");
|
||||
|
||||
// A development server: on all interfaces, its port published on the loopback
|
||||
// interface only, through the service's own mapping when it has one.
|
||||
c.args = vec!["manage.py".into(), "runserver".into()];
|
||||
let out = container_config(&c, &r).unwrap().args.join(" ");
|
||||
assert!(out.contains("--publish 127.0.0.1:8000:8000") && !out.contains("--service-ports"), "{out}");
|
||||
assert!(out.ends_with("web python3 manage.py runserver 0.0.0.0:8000"), "{out}");
|
||||
r.service_ports = &[(8080, 8000)];
|
||||
let out = container_config(&c, &r).unwrap().args.join(" ");
|
||||
assert!(out.contains("--publish 127.0.0.1:8080:8000"), "{out}");
|
||||
let ports = RunTarget { ports: vec!["8000:8000".into()], ..target.clone() };
|
||||
let out = container_config(&c, &run(&ports, &none, &none)).unwrap().args.join(" ");
|
||||
assert!(
|
||||
out.contains("--publish 8000:8000") && !out.contains("127.0.0.1:8000"),
|
||||
"the target's own ports: {out}"
|
||||
);
|
||||
// A host the env file sets is the user's.
|
||||
c.args = vec!["-m".into(), "flask".into(), "run".into()];
|
||||
let files = BTreeMap::from([("FLASK_RUN_HOST".to_owned(), "127.0.0.1".to_owned())]);
|
||||
let out = container_config(&c, &run(&target, &none, &files)).unwrap();
|
||||
assert_eq!(out.env["FLASK_RUN_HOST"], "127.0.0.1");
|
||||
|
||||
let target = RunTarget { kind: RunTargetKind::Compose, name: "c".into(), ..Default::default() };
|
||||
assert!(container_config(&c, &run(&target, &none, &none)).unwrap_err().message.contains("no service"));
|
||||
}
|
||||
@@ -570,6 +741,75 @@ mod tests {
|
||||
assert!(args.contains("openidea/debug:ro python:3.12") && !args.contains("debugpy-lib"), "{args}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_files_printed_in_the_container_through_the_longest_mount() {
|
||||
let root = Path::new("project");
|
||||
let mounts = [
|
||||
(root.to_path_buf(), "/app/".to_owned()),
|
||||
(root.join("config").join("prod"), "/app/config".to_owned()),
|
||||
(root.join("src"), "/code".to_owned()),
|
||||
];
|
||||
assert_eq!(mounted_file("/app/pkg/main.py", &mounts), Some(root.join("pkg").join("main.py")));
|
||||
assert_eq!(mounted_file("/app/./main.py", &mounts), Some(root.join("main.py")));
|
||||
assert_eq!(mounted_file("/app/config/db.py", &mounts), Some(root.join("config").join("prod").join("db.py")));
|
||||
assert_eq!(mounted_file("/code/mypkg/a.py", &mounts), Some(root.join("src").join("mypkg").join("a.py")));
|
||||
for outside in ["/application/main.py", "/app", "/app/", "/app/../etc/passwd", "/usr/lib/x.py"] {
|
||||
assert_eq!(mounted_file(outside, &mounts), None, "{outside}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn development_servers_listen_on_all_interfaces() {
|
||||
let elsewhere = BTreeMap::from([("UVICORN_HOST".to_owned(), "127.0.0.1".to_owned())]);
|
||||
let run = |program: &str, args: &[&str]| {
|
||||
let mut args: Vec<String> = args.iter().map(|a| a.to_string()).collect();
|
||||
let mut env = BTreeMap::new();
|
||||
let set = |k: &str| elsewhere.get(k).cloned();
|
||||
let port = dev_server(program, &mut args, &mut env, &set);
|
||||
let env: Vec<String> = env.into_iter().map(|(k, v)| format!("{k}={v}")).collect();
|
||||
(port, args.join(" "), env.join(" "))
|
||||
};
|
||||
let out = |port: Option<u16>, args: &str, env: &str| (port, args.to_owned(), env.to_owned());
|
||||
assert_eq!(
|
||||
run("python3", &["manage.py", "runserver"]),
|
||||
out(Some(8000), "manage.py runserver 0.0.0.0:8000", "")
|
||||
);
|
||||
assert_eq!(
|
||||
run("/usr/bin/python", &["/w/manage.py", "runserver", "--noreload"]),
|
||||
out(Some(8000), "/w/manage.py runserver 0.0.0.0:8000 --noreload", "")
|
||||
);
|
||||
assert_eq!(
|
||||
run("python", &["manage.py", "runserver", "--settings", "x.dev", "8001"]),
|
||||
out(Some(8001), "manage.py runserver --settings x.dev 0.0.0.0:8001", "")
|
||||
);
|
||||
assert_eq!(
|
||||
run("python", &["manage.py", "runserver", "127.0.0.1:9000"]),
|
||||
out(Some(9000), "manage.py runserver 127.0.0.1:9000", "")
|
||||
);
|
||||
assert_eq!(
|
||||
run("python", &["-m", "django", "runserver"]),
|
||||
out(Some(8000), "-m django runserver 0.0.0.0:8000", "")
|
||||
);
|
||||
assert_eq!(run("django-admin", &["runserver"]), out(Some(8000), "runserver 0.0.0.0:8000", ""));
|
||||
assert_eq!(run("python", &["-m", "flask", "run"]), out(Some(5000), "-m flask run", "FLASK_RUN_HOST=0.0.0.0"));
|
||||
assert_eq!(
|
||||
run("flask", &["--app", "web", "run", "--port", "5001"]),
|
||||
out(Some(5001), "--app web run --port 5001", "FLASK_RUN_HOST=0.0.0.0")
|
||||
);
|
||||
assert_eq!(run("flask", &["run", "--host", "::", "-p", "7000"]), out(Some(7000), "run --host :: -p 7000", ""));
|
||||
assert_eq!(run("uvicorn", &["app:app", "--port=9001"]), out(Some(9001), "app:app --port=9001", ""));
|
||||
assert_eq!(run("fastapi", &["dev", "main.py"]), out(Some(8000), "dev main.py --host 0.0.0.0", ""));
|
||||
assert_eq!(run("fastapi", &["run", "main.py"]), out(Some(8000), "run main.py", ""));
|
||||
for (program, args) in [
|
||||
("python", &["manage.py", "migrate"][..]),
|
||||
("pytest", &["tests"]),
|
||||
("poetry", &["run", "flask", "db", "upgrade"]),
|
||||
("uv", &["run", "flask", "shell"]),
|
||||
] {
|
||||
assert_eq!(run(program, args).0, None, "{program} {args:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn compose_container_root_follows_the_project_bind_mount() {
|
||||
@@ -584,6 +824,18 @@ mod tests {
|
||||
}}"#;
|
||||
let root = Path::new("/work/proj");
|
||||
assert_eq!(compose_container_root(json, "web", root).unwrap(), "/app", "the closest mount wins");
|
||||
assert_eq!(
|
||||
compose_service(json, "web").unwrap().mounts,
|
||||
[("/work".to_owned(), "/src".to_owned()), ("/work/proj".to_owned(), "/app/".to_owned())]
|
||||
);
|
||||
let served = r#"{"services": {"web": {
|
||||
"ports": [{"target": 8000, "published": "8080"}, {"target": 9000}],
|
||||
"environment": {"FLASK_RUN_HOST": "127.0.0.1", "EMPTY": null}
|
||||
}}}"#;
|
||||
let web = compose_service(served, "web").unwrap();
|
||||
assert_eq!(web.ports, [(8080, 8000)]);
|
||||
assert_eq!(web.environment["FLASK_RUN_HOST"], "127.0.0.1");
|
||||
assert_eq!(web.environment["EMPTY"], "");
|
||||
assert_eq!(compose_container_root(json, "worker", root).unwrap(), "/src/proj");
|
||||
assert!(compose_container_root(json, "db", root).unwrap_err().message.contains("does not mount"));
|
||||
assert_eq!(compose_container_root(json, "api", root).unwrap_err().kind, ide_core::error::ErrorKind::NotFound);
|
||||
|
||||
Loaded 100 of 725 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача