дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-26 03:14:38 +02:00
Порівняти коміти
91
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
0329678124 | ||
|
|
2924c0f8e5 | ||
|
|
082420b5bb | ||
|
|
9a5b44bebb | ||
|
|
2203938491 | ||
|
|
503bbb2f02 | ||
|
|
ab6fca01c4 | ||
|
|
0a27d02f4d | ||
|
|
97b8928e4f | ||
|
|
53fd3683e2 | ||
|
|
27bef6956e | ||
|
|
3563f70810 | ||
|
|
7a46774fda | ||
|
|
2ad979af66 | ||
|
|
f5a95dcc21 | ||
|
|
1ed6f7241b | ||
|
|
0d880b9d35 | ||
|
|
95068f5885 | ||
|
|
15d926a5d8 | ||
|
|
7da58637c2 | ||
|
|
b1be3c6a09 | ||
|
|
5792e7d9b6 | ||
|
|
ab7cc02561 | ||
|
|
a7b5758f5a | ||
|
|
e85ffa2ae8 | ||
|
|
2c10b63f76 | ||
|
|
44d0f40b13 | ||
|
|
f28d8da3a1 | ||
|
|
822a93abac | ||
|
|
08956b615e | ||
|
|
6c1eba9d82 | ||
|
|
cdb6cc7c0d | ||
|
|
181a2ea03e | ||
|
|
d44e2414ca | ||
|
|
3bb994062d | ||
|
|
2ea47873cf | ||
|
|
c55fd9b86e | ||
|
|
922bbf493a | ||
|
|
c0626b2728 | ||
|
|
0d368ba947 | ||
|
|
3a1e47d872 | ||
|
|
d1f84ef364 | ||
|
|
00693334f7 | ||
|
|
285c7187fb | ||
|
|
1602e4b530 | ||
|
|
5217f8570b | ||
|
|
c3b3534f08 | ||
|
|
aeec0e6759 | ||
|
|
d1a597898d | ||
|
|
94d209c99c | ||
|
|
44f01b5ce6 | ||
|
|
14d7fd0061 | ||
|
|
b9cfd54742 | ||
|
|
f6a0152488 | ||
|
|
234703c7e9 | ||
|
|
aac924517c | ||
|
|
b1347dd331 | ||
|
|
fc2496c3f0 | ||
|
|
0f26b72d07 | ||
|
|
ad09a76212 | ||
|
|
8568a70a05 | ||
|
|
a20207110e | ||
|
|
74b2d5f5d7 | ||
|
|
297b15a7b1 | ||
|
|
97144421d2 | ||
|
|
200ed6a528 | ||
|
|
4666c4b9a5 | ||
|
|
ce43a7aa70 | ||
|
|
f911196f7d | ||
|
|
8dea5904f2 | ||
|
|
c7d32f9e23 | ||
|
|
3f9512056d | ||
|
|
1283af8a41 | ||
|
|
d37b96002b | ||
|
|
364bb5ef50 | ||
|
|
4d503ef976 | ||
|
|
75b1704f78 | ||
|
|
06d78cf524 | ||
|
|
fff2c7110c | ||
|
|
9fbd57ed15 | ||
|
|
aea0b33585 | ||
|
|
e537dd43a0 | ||
|
|
c821ab144c | ||
|
|
6767a5ff8c | ||
|
|
a233d85fcc | ||
|
|
4e675c1171 | ||
|
|
8ebeaa2663 | ||
|
|
ed7b0f88ef | ||
|
|
9d4e778c7b | ||
|
|
c8e3fe9d2e | ||
|
|
4410da60a2 |
No files matched your search
@@ -3,6 +3,8 @@ on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
types: [opened, synchronize, reopened]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
@@ -69,6 +71,15 @@ jobs:
|
||||
- run: cargo build --locked -p ide-host --bin openidea-server --target x86_64-unknown-linux-musl
|
||||
- run: target/x86_64-unknown-linux-musl/debug/openidea-server --version
|
||||
|
||||
deny:
|
||||
name: Cargo deny
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: taiki-e/install-action@cargo-deny
|
||||
- run: cargo deny check
|
||||
|
||||
frontend:
|
||||
name: Frontend
|
||||
runs-on: ubuntu-22.04
|
||||
@@ -82,6 +93,7 @@ jobs:
|
||||
- run: pnpm typecheck
|
||||
- run: pnpm lint
|
||||
- run: pnpm format:check
|
||||
- run: pnpm knip
|
||||
- run: pnpm test
|
||||
- run: pnpm build
|
||||
|
||||
|
||||
@@ -117,6 +117,8 @@ jobs:
|
||||
releaseId: ${{ needs.create-release.outputs.release_id }}
|
||||
tagName: ${{ env.TAG }}
|
||||
args: --target ${{ matrix.target }}
|
||||
# The parallel builds would race on one latest.json; `updater-manifest` writes it once.
|
||||
uploadUpdaterJson: false
|
||||
# tauri-action notarizes the .app but not the DMG around it; notarize and
|
||||
# staple the DMG too, then replace the uploaded asset.
|
||||
- name: Notarize DMG
|
||||
@@ -172,8 +174,65 @@ jobs:
|
||||
if command -v sha256sum >/dev/null; then sha256sum "$ASSET"; else shasum -a 256 "$ASSET"; fi > "$ASSET.sha256"
|
||||
gh release upload "$TAG" "$ASSET" "$ASSET.sha256" --clobber
|
||||
|
||||
# The updater manifest (latest.json), built once from the signed bundles every build uploaded.
|
||||
# Fails when a platform is missing, so a release never ships a manifest without it.
|
||||
updater-manifest:
|
||||
needs: [create-release, build]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@v7
|
||||
env:
|
||||
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
|
||||
with:
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const release_id = Number(process.env.RELEASE_ID);
|
||||
const tag = process.env.TAG;
|
||||
const assets = await github.paginate(github.rest.repos.listReleaseAssets, { owner, repo, release_id });
|
||||
const sigs = assets.filter((a) => a.name.endsWith(".sig"));
|
||||
if (sigs.length === 0) {
|
||||
core.notice("no signed bundles (TAURI_SIGNING_PRIVATE_KEY unset): skipping latest.json");
|
||||
return;
|
||||
}
|
||||
// Bundle suffix → updater platform keys, as tauri-action names them.
|
||||
const kinds = [
|
||||
[/_amd64\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
|
||||
[/_amd64\.deb$/, ["linux-x86_64-deb"]],
|
||||
[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]],
|
||||
[/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
|
||||
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
|
||||
[/_x64_en-US\.msi$/, ["windows-x86_64", "windows-x86_64-msi"]],
|
||||
[/_x64-setup\.exe$/, ["windows-x86_64-nsis"]],
|
||||
];
|
||||
const platforms = {};
|
||||
for (const sig of sigs) {
|
||||
const bundle = sig.name.slice(0, -".sig".length);
|
||||
const kind = kinds.find(([re]) => re.test(bundle));
|
||||
if (!kind) continue;
|
||||
const { data } = await github.rest.repos.getReleaseAsset({
|
||||
owner, repo, asset_id: sig.id, headers: { accept: "application/octet-stream" },
|
||||
});
|
||||
const signature = Buffer.from(data).toString("utf8").trim();
|
||||
const url = `https://github.com/${owner}/${repo}/releases/download/${tag}/${encodeURIComponent(bundle)}`;
|
||||
for (const key of kind[1]) platforms[key] = { signature, url };
|
||||
}
|
||||
const missing = kinds.flatMap(([, keys]) => keys).filter((k) => !platforms[k]);
|
||||
if (missing.length) {
|
||||
core.setFailed(`latest.json would miss ${missing.join(", ")}`);
|
||||
return;
|
||||
}
|
||||
const manifest = { version: tag.replace(/^v/, ""), notes: "", pub_date: new Date().toISOString(), platforms };
|
||||
const old = assets.find((a) => a.name === "latest.json");
|
||||
if (old) await github.rest.repos.deleteReleaseAsset({ owner, repo, asset_id: old.id });
|
||||
await github.rest.repos.uploadReleaseAsset({
|
||||
owner, repo, release_id, name: "latest.json",
|
||||
data: JSON.stringify(manifest, null, 2),
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
core.info(`latest.json: ${Object.keys(platforms).sort().join(", ")}`);
|
||||
|
||||
publish:
|
||||
needs: [create-release, build, server]
|
||||
needs: [create-release, build, server, updater-manifest]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@v7
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
"dist",
|
||||
"target",
|
||||
"src/bindings.ts",
|
||||
"src/editor/core/cm/angular/parser*.ts",
|
||||
"docs/plugins/themes.md",
|
||||
"pnpm-lock.yaml",
|
||||
"**/*.toml",
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
"src-tauri",
|
||||
"crates",
|
||||
"src/bindings.ts",
|
||||
"src/editor/core/cm/angular/parser*.ts",
|
||||
"fixtures",
|
||||
"plugins",
|
||||
"test-results",
|
||||
|
||||
Створено
+372
-84
@@ -128,9 +128,6 @@ name = "arbitrary"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
|
||||
dependencies = [
|
||||
"derive_arbitrary",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arc-swap"
|
||||
@@ -314,6 +311,19 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "asynchronous-codec"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a860072022177f903e59730004fb5dc13db9275b79bb2aef7ba8ce831956c233"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-sink",
|
||||
"futures-util",
|
||||
"memchr",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "atk"
|
||||
version = "0.18.2"
|
||||
@@ -358,6 +368,29 @@ version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "aws-lc-rs"
|
||||
version = "1.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53"
|
||||
dependencies = [
|
||||
"aws-lc-sys",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aws-lc-sys"
|
||||
version = "0.47.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cmake",
|
||||
"dunce",
|
||||
"fs_extra",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base16ct"
|
||||
version = "1.0.0"
|
||||
@@ -388,6 +421,18 @@ version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "bb8"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "457d7ed3f888dfd2c7af56d4975cade43c622f74bdcddfed6d4352f57acc6310"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"parking_lot",
|
||||
"portable-atomic",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bcrypt-pbkdf"
|
||||
version = "0.11.0"
|
||||
@@ -748,6 +793,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"jobserver",
|
||||
"libc",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
@@ -907,6 +954,15 @@ dependencies = [
|
||||
"hashbrown 0.16.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cmake"
|
||||
version = "0.1.58"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cmov"
|
||||
version = "0.5.4"
|
||||
@@ -959,6 +1015,12 @@ dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "connection-string"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "510ca239cf13b7f8d16a2b48f263de7b4f8c566f0af58d901031473c76afb1e3"
|
||||
|
||||
[[package]]
|
||||
name = "console"
|
||||
version = "0.16.6"
|
||||
@@ -1336,9 +1398,9 @@ checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
|
||||
|
||||
[[package]]
|
||||
name = "crypto-bigint"
|
||||
version = "0.7.5"
|
||||
version = "0.7.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1a52aa3fcda4e6302a9f48734f234d35d4721b96f8fe07d073f07ce9df4f0271"
|
||||
checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11"
|
||||
dependencies = [
|
||||
"cpubits",
|
||||
"ctutils",
|
||||
@@ -1422,9 +1484,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ctutils"
|
||||
version = "0.4.3"
|
||||
version = "0.4.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574"
|
||||
checksum = "a2376ffd6f96d8a9db59875b4b6b0237d6900b5baf64279714e05493ce64828a"
|
||||
dependencies = [
|
||||
"cmov",
|
||||
"subtle",
|
||||
@@ -1628,17 +1690,6 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_arbitrary"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_more"
|
||||
version = "2.1.1"
|
||||
@@ -2238,6 +2289,12 @@ dependencies = [
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs_extra"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
|
||||
|
||||
[[package]]
|
||||
name = "fsevent-sys"
|
||||
version = "4.1.0"
|
||||
@@ -2342,6 +2399,12 @@ version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
|
||||
|
||||
[[package]]
|
||||
name = "futures-timer"
|
||||
version = "3.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968"
|
||||
|
||||
[[package]]
|
||||
name = "futures-util"
|
||||
version = "0.3.34"
|
||||
@@ -3974,13 +4037,15 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
"ide-tools",
|
||||
"ide-vcs",
|
||||
"ide-vfs",
|
||||
"parking_lot",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -3995,7 +4060,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4009,7 +4074,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4024,24 +4089,32 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"specta-typescript",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
"tokio-util",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4055,7 +4128,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -4072,8 +4145,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"bb8",
|
||||
"dirs 6.0.0",
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4084,14 +4158,16 @@ dependencies = [
|
||||
"specta",
|
||||
"sqlx",
|
||||
"tempfile",
|
||||
"tiberius",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4103,9 +4179,20 @@ dependencies = [
|
||||
"which",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
"serde",
|
||||
"specta",
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4119,10 +4206,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"ide-agent",
|
||||
"ide-analysis",
|
||||
"ide-build",
|
||||
@@ -4135,6 +4223,7 @@ dependencies = [
|
||||
"ide-jsonrpc",
|
||||
"ide-language",
|
||||
"ide-lsp",
|
||||
"ide-notebook",
|
||||
"ide-remote",
|
||||
"ide-run",
|
||||
"ide-sdk",
|
||||
@@ -4152,15 +4241,17 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"specta-typescript",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4178,7 +4269,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4200,7 +4291,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4216,7 +4307,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4227,6 +4318,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"tempfile",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"tracing",
|
||||
"tree-sitter",
|
||||
@@ -4270,7 +4362,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"globset",
|
||||
@@ -4288,12 +4380,34 @@ dependencies = [
|
||||
"tokio",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"tracing",
|
||||
"which",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
"jupyter-protocol",
|
||||
"jupyter-zmq-client",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"specta-typescript",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"uuid",
|
||||
"windows-sys 0.61.2",
|
||||
"zeromq",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4311,7 +4425,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4324,7 +4438,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"globset",
|
||||
"ide-core",
|
||||
@@ -4341,7 +4455,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4356,12 +4470,12 @@ dependencies = [
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"toml_edit 0.25.17+spec-1.1.0",
|
||||
"tracing",
|
||||
"zip 2.4.2",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4375,13 +4489,12 @@ dependencies = [
|
||||
"tempfile",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"tracing",
|
||||
"which",
|
||||
"zip 2.4.2",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"globset",
|
||||
@@ -4401,7 +4514,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4414,7 +4527,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4433,7 +4546,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4448,7 +4561,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4461,7 +4574,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4473,7 +4586,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4489,16 +4602,18 @@ dependencies = [
|
||||
"tempfile",
|
||||
"tracing",
|
||||
"which",
|
||||
"zip 2.4.2",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"gix",
|
||||
"ide-core",
|
||||
"ignore",
|
||||
"libc",
|
||||
"regex-lite",
|
||||
"serde",
|
||||
@@ -4511,11 +4626,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"gix",
|
||||
"globset",
|
||||
"ide-core",
|
||||
"ignore",
|
||||
@@ -4527,12 +4643,12 @@ dependencies = [
|
||||
"tempfile",
|
||||
"tracing",
|
||||
"trash",
|
||||
"zip 2.4.2",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"open",
|
||||
@@ -4548,7 +4664,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4565,7 +4681,7 @@ dependencies = [
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"toml_edit 0.25.17+spec-1.1.0",
|
||||
"tracing",
|
||||
"zip 2.4.2",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4934,6 +5050,16 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jobserver"
|
||||
version = "0.1.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
|
||||
dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.106"
|
||||
@@ -4967,6 +5093,41 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jupyter-protocol"
|
||||
version = "2.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf199c30e61505042f5c0d79a33b5a71c552ea8b64243ff3498b1f4592d8e692"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"futures",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jupyter-zmq-client"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f59bf6241faf6a8c06416c351756be9a79976e8faad220604b9a26f568270ab0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"data-encoding",
|
||||
"dirs 6.0.0",
|
||||
"jupyter-protocol",
|
||||
"ring",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"uuid",
|
||||
"zeromq",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keccak"
|
||||
version = "0.2.2"
|
||||
@@ -5973,7 +6134,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dirs 6.0.0",
|
||||
@@ -5987,6 +6148,7 @@ dependencies = [
|
||||
"ide-dap",
|
||||
"ide-db",
|
||||
"ide-docker",
|
||||
"ide-fonts",
|
||||
"ide-github",
|
||||
"ide-host",
|
||||
"ide-http",
|
||||
@@ -5994,6 +6156,7 @@ dependencies = [
|
||||
"ide-jsonrpc",
|
||||
"ide-language",
|
||||
"ide-lsp",
|
||||
"ide-notebook",
|
||||
"ide-plugin",
|
||||
"ide-profiler",
|
||||
"ide-remote",
|
||||
@@ -6506,6 +6669,12 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
|
||||
|
||||
[[package]]
|
||||
name = "pretty-hex"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a65843dfefbafd3c879c683306959a6de478443ffe9c9adf02f5976432402d7"
|
||||
|
||||
[[package]]
|
||||
name = "primefield"
|
||||
version = "0.14.0"
|
||||
@@ -7175,6 +7344,7 @@ version = "0.23.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"log",
|
||||
"once_cell",
|
||||
"ring",
|
||||
@@ -7238,6 +7408,7 @@ version = "0.103.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"untrusted",
|
||||
@@ -7261,6 +7432,12 @@ dependencies = [
|
||||
"wait-timeout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "saa"
|
||||
version = "5.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bd85992a680de788217d9c70b74aa7685b108cf1aba02f728fb27f1b27199ad1"
|
||||
|
||||
[[package]]
|
||||
name = "salsa20"
|
||||
version = "0.11.0"
|
||||
@@ -7280,6 +7457,16 @@ dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scc"
|
||||
version = "3.8.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d5f8ca67c4f6208caf824037a6a9df0211b4e0937fccc4f543441f294d04511"
|
||||
dependencies = [
|
||||
"saa",
|
||||
"sdd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schannel"
|
||||
version = "0.1.29"
|
||||
@@ -7358,6 +7545,15 @@ dependencies = [
|
||||
"sha2 0.11.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sdd"
|
||||
version = "4.8.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a31877eee03686b905845993b5d9809a220c9dd5a10e9d6021d7ca67384c9070"
|
||||
dependencies = [
|
||||
"saa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sec1"
|
||||
version = "0.8.1"
|
||||
@@ -7372,6 +7568,15 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "secrecy"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e891af845473308773346dc847b2c23ee78fe442e0472ac50e22a18a93d3ae5a"
|
||||
dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework"
|
||||
version = "3.7.0"
|
||||
@@ -7638,6 +7843,12 @@ dependencies = [
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1_smol"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"
|
||||
|
||||
[[package]]
|
||||
name = "sha1dc"
|
||||
version = "0.1.5"
|
||||
@@ -8657,11 +8868,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-updater"
|
||||
version = "2.14.0"
|
||||
version = "2.14.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7259989d4fe11b2bf51f7d671642249b1837c4ae2da1430dc713ae38f98ceeec"
|
||||
checksum = "d957abbcb3f9f6c76d22a3a0f012f30880640d0bccb5634d2b12a9937e4c872b"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"base64 0.23.1",
|
||||
"dirs 7.0.0",
|
||||
"flate2",
|
||||
"futures-util",
|
||||
@@ -8686,7 +8897,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"url",
|
||||
"windows-sys 0.61.2",
|
||||
"zip 4.6.1",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8915,6 +9126,51 @@ dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiberius"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e07324791de2bdaed058af4aa433a0b5ec5c0beac407a9797419c19805df2415"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"asynchronous-codec",
|
||||
"byteorder",
|
||||
"bytes",
|
||||
"connection-string",
|
||||
"encoding_rs",
|
||||
"enumflags2",
|
||||
"futures-timer",
|
||||
"futures-util",
|
||||
"libc",
|
||||
"num-traits",
|
||||
"once_cell",
|
||||
"pin-project-lite",
|
||||
"pretty-hex",
|
||||
"rustls-native-certs",
|
||||
"rustls-pki-types",
|
||||
"rustls-webpki",
|
||||
"secrecy",
|
||||
"thiserror 2.0.21",
|
||||
"tiberius-macros",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
"uuid",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiberius-macros"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "907fed5ea55695d902cc3359fffa4a35021dfa9b95ab4eb9c8376d42ffb9eec8"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time"
|
||||
version = "0.3.55"
|
||||
@@ -8973,9 +9229,9 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.54.0"
|
||||
version = "1.54.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a0c168a474b95bfecfe908a65d4bdffc523144b649a74c09c286afb35d53e0bc"
|
||||
checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"libc",
|
||||
@@ -9040,6 +9296,7 @@ checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-io",
|
||||
"futures-sink",
|
||||
"futures-util",
|
||||
"libc",
|
||||
@@ -9726,6 +9983,12 @@ dependencies = [
|
||||
"utf-8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typed-path"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e"
|
||||
|
||||
[[package]]
|
||||
name = "typeid"
|
||||
version = "1.0.3"
|
||||
@@ -9862,6 +10125,7 @@ dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"js-sys",
|
||||
"serde_core",
|
||||
"sha1_smol",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
@@ -10391,9 +10655,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webpki-root-certs"
|
||||
version = "1.0.9"
|
||||
version = "1.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"
|
||||
checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
@@ -10467,6 +10731,17 @@ version = "2.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c"
|
||||
|
||||
[[package]]
|
||||
name = "win_uds"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7dd30a1a28a3799479cbf4e17284a220ea9ff6bad098a9d0224543a5d1efe1da"
|
||||
dependencies = [
|
||||
"async-io",
|
||||
"futures-io",
|
||||
"socket2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi"
|
||||
version = "0.3.9"
|
||||
@@ -11205,6 +11480,31 @@ version = "1.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
|
||||
|
||||
[[package]]
|
||||
name = "zeromq"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "efb2c254fd8f366755335c9e43b865f8484fe3bd717d65ffe7c3f28852863030"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"asynchronous-codec",
|
||||
"bytes",
|
||||
"crossbeam-queue",
|
||||
"futures",
|
||||
"log",
|
||||
"num-traits",
|
||||
"once_cell",
|
||||
"parking_lot",
|
||||
"rand 0.9.5",
|
||||
"regex",
|
||||
"scc",
|
||||
"thiserror 1.0.69",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"uuid",
|
||||
"win_uds",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerotrie"
|
||||
version = "0.2.5"
|
||||
@@ -11240,33 +11540,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "2.4.2"
|
||||
version = "9.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50"
|
||||
checksum = "1156b39d142a34b999c2310a50455e0cb3760bf7efad0122f796d813bee26ccb"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
"crc32fast",
|
||||
"crossbeam-utils",
|
||||
"displaydoc",
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"indexmap 2.14.2",
|
||||
"memchr",
|
||||
"thiserror 2.0.21",
|
||||
"nix 0.31.3",
|
||||
"typed-path",
|
||||
"windows-sys 0.61.2",
|
||||
"zopfli",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "4.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
"crc32fast",
|
||||
"indexmap 2.14.2",
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zlib-rs"
|
||||
version = "0.6.8"
|
||||
|
||||
+9
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.23"
|
||||
version = "0.1.27"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -36,9 +36,11 @@ ide-web = { path = "crates/ide-web" }
|
||||
ide-spell = { path = "crates/ide-spell" }
|
||||
ide-agent = { path = "crates/ide-agent" }
|
||||
ide-clipboard = { path = "crates/ide-clipboard" }
|
||||
ide-fonts = { path = "crates/ide-fonts" }
|
||||
ide-ssh = { path = "crates/ide-ssh" }
|
||||
ide-remote = { path = "crates/ide-remote" }
|
||||
ide-host = { path = "crates/ide-host" }
|
||||
ide-notebook = { path = "crates/ide-notebook" }
|
||||
|
||||
# serialization & IPC typing
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
@@ -74,6 +76,7 @@ trash = "5"
|
||||
blake3 = "1"
|
||||
dunce = "1"
|
||||
dirs = "6"
|
||||
zip = { version = "9", default-features = false, features = ["deflate"] }
|
||||
|
||||
# search, index, language
|
||||
grep-searcher = "0.1"
|
||||
@@ -84,6 +87,9 @@ redb = "4"
|
||||
tree-sitter = "0.25"
|
||||
|
||||
# protocols & integrations
|
||||
jupyter-zmq-client = { version = "=2.0.0", default-features = false, features = ["tokio-runtime", "ring"] }
|
||||
jupyter-protocol = "=2.0.3"
|
||||
zeromq = { version = "0.6", default-features = false, features = ["tokio-runtime", "tcp-transport"] }
|
||||
lsp-types = "0.97"
|
||||
gix = { version = "0.89", default-features = false }
|
||||
portable-pty = "0.9"
|
||||
@@ -91,6 +97,8 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls-no-p
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||
rustls-platform-verifier = "0.7"
|
||||
sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "tls-rustls-ring-webpki", "sqlite", "postgres", "mysql"] }
|
||||
tiberius = { version = "0.13", default-features = false, features = ["tds73", "rustls", "sql-browser-tokio"] }
|
||||
bb8 = "0.9"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
|
||||
# testing
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
<a href="#benchmark">Benchmark</a>
|
||||
·
|
||||
<a href="#build">Build</a>
|
||||
·
|
||||
<a href="https://discord.gg/2Zy4yn7gP">Discord</a>
|
||||
</p>
|
||||
|
||||
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
|
||||
@@ -54,6 +56,15 @@ pnpm tauri dev
|
||||
|
||||
Rust 1.96, Node 22, pnpm and the [Tauri prerequisites](https://v2.tauri.app/start/prerequisites/).
|
||||
|
||||
Native notebook execution tests are opt-in and need two distinct Python environments
|
||||
with `ipykernel` installed:
|
||||
|
||||
```sh
|
||||
OPENIDEA_TEST_PYTHON=/first/env/bin/python \
|
||||
OPENIDEA_TEST_PYTHON_SECOND=/second/env/bin/python \
|
||||
cargo test -p ide-notebook --test kernel_runtime -- --ignored --test-threads=1
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
[Apache 2.0](LICENSE). Bundled third-party assets are listed in [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md).
|
||||
|
||||
@@ -28,6 +28,19 @@ icon set, copied unmodified (some renamed) from JetBrains' open-source repositor
|
||||
|
||||
At render time `src/ui/icons.tsx` may recolour monochrome icons to `currentColor`.
|
||||
|
||||
## JetBrains IntelliJ Platform diff algorithm
|
||||
|
||||
`src/features/vcs/comparison/**` is a TypeScript port of the text comparison of
|
||||
[intellij-community](https://github.com/JetBrains/intellij-community) (Apache-2.0):
|
||||
`platform/util/diff` (`com.intellij.util.diff`: Diff, Reindexer, MyersLCS,
|
||||
PatienceIntLCS, UniqueLCS; `com.intellij.diff.comparison`: ByLineRt, ByWordRt,
|
||||
ByCharRt, ChunkOptimizer, ChangeCorrector, LineFragmentSplitter, TrimUtil,
|
||||
ComparisonUtil, iterables) and `platform/diff-impl` (ComparisonManagerImpl's
|
||||
`compareLinesInner` and `processBlocks`). `__tests__/ideaCases.json` is converted
|
||||
from its tests (`LineComparisonUtilTest`, `WordComparisonUtilTest`,
|
||||
`SplitComparisonUtilTest`). Modified from the originals. Copyright 2000-2026
|
||||
JetBrains s.r.o. and contributors. Apache License 2.0 (below).
|
||||
|
||||
`src/ui/openidea/**` holds OpenIDEA's own file-type icons drawn in the expui style for
|
||||
languages whose JetBrains icons are not open source (Go, Rust, Ruby, Dart, Lua, Zig,
|
||||
Svelte, …). Those using the page-with-corner-badge layout (`goMod`, `goWork`,
|
||||
@@ -98,6 +111,18 @@ shell and css dictionaries of [cspell-dicts](https://github.com/streetsidesoftwa
|
||||
(October 2026): lowercased, filtered and merged by OpenIDEA. Copyright Street Side Software;
|
||||
MIT licence, full text in `crates/ide-spell/src/dict/LICENSE-cspell-dicts`.
|
||||
|
||||
## CodeMirror Angular template language
|
||||
|
||||
`src/editor/core/cm/angular/` (`angular.grammar`, `tokens.ts`, `index.ts` and the
|
||||
`parser.ts` generated from them) is derived from
|
||||
[@codemirror/lang-angular](https://github.com/codemirror/lang-angular) 0.1.4
|
||||
(commit `ecc5038f`). Copyright (C) 2018-2021 by Marijn Haverbeke and others; MIT
|
||||
licence, full text in `src/editor/core/cm/angular/LICENSE`. Modifications by
|
||||
OpenIDEA: control-flow blocks (`@if`, `@for`, `@switch`, `@defer`, ...) and `@let`
|
||||
declarations, key and animation binding names (`(keydown.enter)`, `[@fade]`,
|
||||
`(@fade.done)`), runs of text that entities split (`a && b`) parsed as one, and one
|
||||
token for `{` and `}`.
|
||||
|
||||
## nvim-treesitter queries
|
||||
|
||||
`crates/ide-syntax/queries/<grammar>/locals.scm` are derived from the `locals.scm`
|
||||
|
||||
@@ -6,6 +6,8 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
encoding_rs.workspace = true
|
||||
ide-vfs.workspace = true
|
||||
ide-core.workspace = true
|
||||
ide-jsonrpc.workspace = true
|
||||
ide-vcs.workspace = true
|
||||
|
||||
@@ -4,6 +4,39 @@
|
||||
use crate::model::{AgentCommand, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentUsage};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Cursor exposes execution modes over ACP, but leaves approval policy to its client.
|
||||
pub(crate) const CURSOR_APPROVAL: &str = "openidea.cursor.approval";
|
||||
|
||||
pub(crate) fn add_client_options(provider: &str, config: &mut Vec<AgentConfigOption>) {
|
||||
if provider != "cursor" || config.iter().any(|o| o.id == CURSOR_APPROVAL) {
|
||||
return;
|
||||
}
|
||||
config.push(AgentConfigOption {
|
||||
id: CURSOR_APPROVAL.into(),
|
||||
name: "Approvals".into(),
|
||||
description: Some("Tool approvals for this Cursor conversation".into()),
|
||||
category: Some("approval".into()),
|
||||
current: Some("ask".into()),
|
||||
via: AgentConfigVia::Option,
|
||||
values: vec![
|
||||
AgentConfigValue {
|
||||
value: "ask".into(),
|
||||
name: "Ask for approval".into(),
|
||||
description: Some("Show permission requests from Cursor".into()),
|
||||
},
|
||||
AgentConfigValue {
|
||||
value: "bypass".into(),
|
||||
name: "Bypass approvals".into(),
|
||||
description: Some("Automatically approve tool requests in this conversation".into()),
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn bypass_approvals(provider: &str, config: &[AgentConfigOption]) -> bool {
|
||||
provider == "cursor" && config.iter().any(|o| o.id == CURSOR_APPROVAL && o.current.as_deref() == Some("bypass"))
|
||||
}
|
||||
|
||||
/// The settings in a `session/new` or `session/load` result: its select `configOptions`,
|
||||
/// plus the older `modes` / `models` fields for what those don't cover.
|
||||
pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
|
||||
@@ -64,7 +97,7 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
|
||||
pub(crate) fn merge_update(config: &mut Vec<AgentConfigOption>, options: &Value) {
|
||||
let fresh = parse_options(options);
|
||||
let covered = |o: &AgentConfigOption| fresh.iter().any(|f| f.category.is_some() && f.category == o.category);
|
||||
config.retain(|o| o.via != AgentConfigVia::Option && !covered(o));
|
||||
config.retain(|o| o.id == CURSOR_APPROVAL || (o.via != AgentConfigVia::Option && !covered(o)));
|
||||
let legacy = std::mem::take(config);
|
||||
config.extend(fresh);
|
||||
config.extend(legacy);
|
||||
|
||||
@@ -46,6 +46,8 @@ const STDERR_LINES: usize = 20;
|
||||
/// Updates of a session's state rather than its conversation.
|
||||
const SESSION_STATE: [&str; 5] =
|
||||
["session_info_update", "config_option_update", "current_mode_update", "available_commands_update", "usage_update"];
|
||||
/// A native agent's own update: it is about to retry a failed API request (see [`AgentRetry`]).
|
||||
pub(crate) const RETRY_UPDATE: &str = "openidea_retry";
|
||||
/// Referenced files up to this size are embedded in the prompt (when the agent takes it).
|
||||
const MAX_EMBED: u64 = 256 * 1024;
|
||||
/// How long a probe waits for the agent to answer `initialize`.
|
||||
@@ -112,7 +114,13 @@ impl Shared {
|
||||
}
|
||||
|
||||
fn known_config(&self, provider: &str) -> Vec<AgentConfigOption> {
|
||||
self.known.lock().get(provider).map(|k| k.config.clone()).unwrap_or_default()
|
||||
let mut config = self.known.lock().get(provider).map(|k| k.config.clone()).unwrap_or_default();
|
||||
config::add_client_options(provider, &mut config);
|
||||
// Approval bypass belongs to the conversation, never to another new task.
|
||||
if let Some(o) = config.iter_mut().find(|o| o.id == config::CURSOR_APPROVAL) {
|
||||
o.current = Some("ask".into());
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
/// The commands the agent offered last time in this project.
|
||||
@@ -264,6 +272,7 @@ impl AgentManager {
|
||||
if matches!(f.task.status, AgentStatus::Running | AgentStatus::NeedsInput | AgentStatus::Starting) {
|
||||
f.task.status = AgentStatus::Ready;
|
||||
}
|
||||
f.task.retry = None;
|
||||
let task = Task::restore(f, shared.clone());
|
||||
task.state.lock().conversation.settle(now_ms());
|
||||
tasks.insert(task.id.clone(), task);
|
||||
@@ -305,8 +314,8 @@ impl AgentManager {
|
||||
}
|
||||
|
||||
/// The slash commands to complete for `provider`, in `task`'s directory or (without one)
|
||||
/// in the project: what the agent offered last time there, plus, for Claude Code, the
|
||||
/// skills and custom commands on disk it has not listed.
|
||||
/// in the project: what the agent offered last time there, unadvertised builtins,
|
||||
/// and, for Claude Code, skills and custom commands on disk it has not listed.
|
||||
pub async fn commands(&self, provider: &str, task: Option<&str>) -> IdeResult<Vec<AgentCommand>> {
|
||||
let (provider, offered, cwd) = match task {
|
||||
Some(id) => {
|
||||
@@ -316,6 +325,14 @@ impl AgentManager {
|
||||
}
|
||||
None => (provider.to_owned(), self.shared.known_commands(provider), self.shared.paths.project_root.clone()),
|
||||
};
|
||||
// Commands the agent implements itself and never lists (its CLI builtins):
|
||||
// merged without duplicating what `availableCommands` or the disk offer.
|
||||
let mut offered = offered;
|
||||
for &(name, description) in builtin_commands(&provider) {
|
||||
if !offered.iter().any(|c| c.name == name) {
|
||||
offered.push(AgentCommand { name: name.to_owned(), description: description.to_owned(), hint: None });
|
||||
}
|
||||
}
|
||||
if provider != "claude" && provider != "claude-acp" {
|
||||
return Ok(offered);
|
||||
}
|
||||
@@ -389,6 +406,7 @@ impl AgentManager {
|
||||
queue: Vec::new(),
|
||||
capabilities: self.shared.probes.lock().get(&spec.id).map(|p| p.capabilities).unwrap_or_default(),
|
||||
resets_ms: None,
|
||||
retry: None,
|
||||
};
|
||||
let file = TaskFile {
|
||||
task: task.clone(),
|
||||
@@ -512,7 +530,7 @@ impl AgentManager {
|
||||
o.clone()
|
||||
};
|
||||
let live = task.live.lock().clone().filter(|l| !l.peer.is_closed());
|
||||
if let Some(live) = live {
|
||||
if let Some(live) = live.filter(|_| option != config::CURSOR_APPROVAL) {
|
||||
let (method, mut params) = config::set_request(&target, &value);
|
||||
params["sessionId"] = json!(live.session);
|
||||
let reply: Value =
|
||||
@@ -529,7 +547,12 @@ impl AgentManager {
|
||||
o.current = Some(value);
|
||||
}
|
||||
s.task.model = model_of(&s.task.config).or(s.task.model.take());
|
||||
let provider = s.task.provider.clone();
|
||||
let config = s.task.config.clone();
|
||||
drop(s);
|
||||
task.shared.remember(&provider, Some(&config), None);
|
||||
}
|
||||
task.approve_pending();
|
||||
task.persist();
|
||||
task.emit_task();
|
||||
Ok(())
|
||||
@@ -577,6 +600,7 @@ impl AgentManager {
|
||||
usage: None,
|
||||
queue: Vec::new(),
|
||||
resets_ms: None,
|
||||
retry: None,
|
||||
..s.task.clone()
|
||||
};
|
||||
TaskFile {
|
||||
@@ -736,6 +760,26 @@ impl AgentManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns an archived task to the active list without starting the agent.
|
||||
pub fn unarchive(&self, id: &str) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
{
|
||||
let mut s = task.state.lock();
|
||||
if s.task.status != AgentStatus::Archived {
|
||||
return Ok(());
|
||||
}
|
||||
if s.busy {
|
||||
return Err(IdeError::invalid("the task is still stopping"));
|
||||
}
|
||||
s.task.status = AgentStatus::Ready;
|
||||
s.task.error = None;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
task.persist();
|
||||
task.emit_task();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Forgets the task; with `remove_worktree` also deletes its worktree (the branch stays).
|
||||
pub async fn delete(&self, id: &str, remove_worktree: bool) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
@@ -784,7 +828,8 @@ impl AgentManager {
|
||||
|
||||
impl Task {
|
||||
fn restore(file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
|
||||
let task = file.task;
|
||||
let mut task = file.task;
|
||||
config::add_client_options(&task.provider, &mut task.config);
|
||||
let conversation = Conversation::restore(file.entries, file.subagents);
|
||||
Arc::new(Self {
|
||||
id: task.id.clone(),
|
||||
@@ -830,9 +875,22 @@ impl Task {
|
||||
self.shared.emit(AgentEvent::Task { task });
|
||||
}
|
||||
|
||||
/// Shows (or clears) the agent's pending retry; emitted only when it changes.
|
||||
fn set_retry(&self, retry: Option<AgentRetry>) {
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
if s.task.retry == retry {
|
||||
return;
|
||||
}
|
||||
s.task.retry = retry;
|
||||
}
|
||||
self.emit_task();
|
||||
}
|
||||
|
||||
fn set_status(&self, status: AgentStatus, error: Option<String>) {
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
s.task.retry = None;
|
||||
s.task.status = status;
|
||||
s.task.error = error;
|
||||
s.task.updated_ms = now_ms();
|
||||
@@ -1156,10 +1214,16 @@ impl Task {
|
||||
let s = self.state.lock();
|
||||
(if known { reported } else { s.task.config.clone() }, s.wanted.clone())
|
||||
};
|
||||
self.shared.remember(&provider_id, Some(&options), None);
|
||||
config::add_client_options(&provider_id, &mut options);
|
||||
for choice in &wanted {
|
||||
// An option the session doesn't offer yet is set once it does (`apply_late_choices`).
|
||||
let Some(o) = options.iter().find(|o| o.id == choice.id).cloned() else { continue };
|
||||
if o.id == config::CURSOR_APPROVAL {
|
||||
if o.values.iter().any(|v| v.value == choice.value) {
|
||||
options.iter_mut().find(|o| o.id == choice.id).unwrap().current = Some(choice.value.clone());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let already = known && o.current.as_deref() == Some(choice.value.as_str());
|
||||
if already || !o.values.iter().any(|v| v.value == choice.value) {
|
||||
continue;
|
||||
@@ -1179,6 +1243,7 @@ impl Task {
|
||||
Err(e) => tracing::warn!("agent task {}: setting {} to {} failed: {e}", self.id, o.id, choice.value),
|
||||
}
|
||||
}
|
||||
self.shared.remember(&provider_id, Some(&options), None);
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
s.task.model = model_of(&options).or(s.task.model.take());
|
||||
@@ -1203,7 +1268,7 @@ impl Task {
|
||||
s.wanted
|
||||
.iter()
|
||||
.filter_map(|c| {
|
||||
let o = s.task.config.iter().find(|o| o.id == c.id)?;
|
||||
let o = s.task.config.iter().find(|o| o.id == c.id && o.id != config::CURSOR_APPROVAL)?;
|
||||
let due = o.current.as_deref() != Some(c.value.as_str())
|
||||
&& o.values.iter().any(|v| v.value == c.value)
|
||||
&& sent.insert((c.id.clone(), c.value.clone()));
|
||||
@@ -1264,6 +1329,12 @@ impl Task {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if kind == RETRY_UPDATE {
|
||||
if !self.replaying.load(Ordering::Acquire) {
|
||||
self.set_retry(retry_of(update, now_ms()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if kind == "session_info_update" {
|
||||
// The agent's own title for the session replaces the first line of the prompt.
|
||||
let title = update.get("title").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty());
|
||||
@@ -1332,6 +1403,8 @@ impl Task {
|
||||
}
|
||||
|
||||
fn apply(self: &Arc<Self>, session: Option<&str>, kind: &str, update: &Value) {
|
||||
// Output again: the retried request went through.
|
||||
self.set_retry(None);
|
||||
let applied = self.state.lock().conversation.apply(session, update, now_ms());
|
||||
self.mark_dirty(applied);
|
||||
// A subagent can start or finish after the turn that started it: saved right away.
|
||||
@@ -1374,6 +1447,7 @@ impl Task {
|
||||
let entry = self.push_entry(AgentEntry::Permission { id, title, options: options.clone(), chosen: None });
|
||||
self.permissions.lock().insert(id, tx);
|
||||
self.set_status(AgentStatus::NeedsInput, None);
|
||||
self.approve_pending();
|
||||
|
||||
let answer = rx.recv().ok().flatten();
|
||||
let name = answer
|
||||
@@ -1397,6 +1471,22 @@ impl Task {
|
||||
}
|
||||
}
|
||||
|
||||
fn approve_pending(&self) {
|
||||
let s = self.state.lock();
|
||||
if self.cancel_pending.load(Ordering::Acquire) || !config::bypass_approvals(&s.task.provider, &s.task.config) {
|
||||
return;
|
||||
}
|
||||
let mut pending = self.permissions.lock();
|
||||
for entry in s.conversation.main.entries.iter().rev() {
|
||||
if let AgentEntry::Permission { id, options, chosen: None, .. } = entry
|
||||
&& let Some(option) = options.iter().find(|o| o.kind == "allow_once")
|
||||
&& let Some(reply) = pending.remove(id)
|
||||
{
|
||||
let _ = reply.send(Some(option.id.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_permissions(&self) {
|
||||
for (_, reply) in self.permissions.lock().drain() {
|
||||
let _ = reply.send(None);
|
||||
@@ -1556,10 +1646,31 @@ fn is_zero(n: &u32) -> bool {
|
||||
*n == 0
|
||||
}
|
||||
|
||||
/// The retry a [`RETRY_UPDATE`] announces, timed from `now`.
|
||||
fn retry_of(update: &Value, now: f64) -> Option<AgentRetry> {
|
||||
let n = |k: &str| update.get(k).and_then(Value::as_u64);
|
||||
Some(AgentRetry {
|
||||
attempt: u32::try_from(n("attempt")?).unwrap_or(u32::MAX),
|
||||
max_retries: n("maxRetries").and_then(|m| u32::try_from(m).ok()),
|
||||
retry_at_ms: now + n("retryDelayMs").unwrap_or(0) as f64,
|
||||
error: update.get("error").and_then(Value::as_str).filter(|e| !e.is_empty()).map(str::to_owned),
|
||||
})
|
||||
}
|
||||
|
||||
fn model_of(config: &[AgentConfigOption]) -> Option<String> {
|
||||
config.iter().find(|o| o.category.as_deref() == Some("model")).and_then(|o| o.current.clone())
|
||||
}
|
||||
|
||||
/// Commands the agent implements on its own and never lists in `availableCommands` —
|
||||
/// its CLI builtins, passed through as prompt text (e.g. `/compact`). `(name, description)`.
|
||||
fn builtin_commands(provider: &str) -> &'static [(&'static str, &'static str)] {
|
||||
match provider {
|
||||
// OpenCode ACP handles `/compact` via session.summarize but omits it from its command list.
|
||||
"opencode" => &[("compact", "compact the conversation")],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
fn file_name(path: &Path) -> String {
|
||||
path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
@@ -81,6 +81,21 @@ pub struct AgentTask {
|
||||
/// When a [`AgentStatus::Limited`] task's limit resets (ms since the epoch), if the agent said.
|
||||
#[serde(default)]
|
||||
pub resets_ms: Option<f64>,
|
||||
/// The agent is retrying a failed API request (connection lost, overloaded…); cleared
|
||||
/// by its next output or any status change.
|
||||
#[serde(default)]
|
||||
pub retry: Option<AgentRetry>,
|
||||
}
|
||||
|
||||
/// An API request the agent is about to retry.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentRetry {
|
||||
pub attempt: u32,
|
||||
pub max_retries: Option<u32>,
|
||||
/// When the next attempt starts (ms since the epoch).
|
||||
pub retry_at_ms: f64,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// One value of a select-type session setting.
|
||||
|
||||
@@ -296,7 +296,7 @@ impl Shim {
|
||||
let mut cmd = std::process::Command::new(&self.config.program);
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
let out = cmd.arg("--version").envs(ide_core::process::shell_env()).output().ok()?;
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
let text = ide_core::output_encoding::decode_tool_output(&out.stdout);
|
||||
text.split_whitespace().next().filter(|v| out.status.success() && !v.is_empty()).map(str::to_owned)
|
||||
}
|
||||
|
||||
|
||||
@@ -917,6 +917,20 @@ fn pending_starts_round_trip() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_retries_are_announced() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), true);
|
||||
let out = t.on_message(&json!({"type": "system", "subtype": "api_retry", "attempt": 3, "max_retries": 10,
|
||||
"retry_delay_ms": 4000, "error_status": null, "error": "Connection error."}));
|
||||
assert_eq!(out.len(), 1);
|
||||
assert_eq!(out[0].session, "s");
|
||||
assert_eq!(
|
||||
out[0].update,
|
||||
json!({"sessionUpdate": crate::RETRY_UPDATE, "attempt": 3, "maxRetries": 10, "retryDelayMs": 4000,
|
||||
"error": "Connection error."})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_text_is_not_sent_twice() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), true);
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! Agent tool use that launched them: their messages carry it as `parent_tool_use_id`.
|
||||
|
||||
use super::tools;
|
||||
use crate::RETRY_UPDATE;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::path::PathBuf;
|
||||
@@ -427,6 +428,23 @@ impl Translator {
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
// Claude Code retries a failed API request on its own; without this the turn looks stuck.
|
||||
Some("api_retry") => {
|
||||
let n = |k: &str| msg.get(k).and_then(Value::as_u64);
|
||||
let error = msg.get("error").and_then(|e| {
|
||||
e.as_str().map(str::to_owned).or_else(|| e.get("message")?.as_str().map(str::to_owned))
|
||||
});
|
||||
vec![Update {
|
||||
session: self.root.clone(),
|
||||
update: json!({
|
||||
"sessionUpdate": RETRY_UPDATE,
|
||||
"attempt": n("attempt").unwrap_or(1),
|
||||
"maxRetries": n("max_retries"),
|
||||
"retryDelayMs": n("retry_delay_ms").unwrap_or(0),
|
||||
"error": error,
|
||||
}),
|
||||
}]
|
||||
}
|
||||
Some("task_notification") if self.children.get(&tool_use).is_some_and(|c| c.background != Some(false)) => {
|
||||
let stop = match msg.get("status").and_then(Value::as_str) {
|
||||
Some("failed") => "error",
|
||||
|
||||
@@ -199,7 +199,12 @@ fn invalid(message: impl Into<String>) -> ResponseError {
|
||||
fn from_codex(e: RpcError) -> ResponseError {
|
||||
match e {
|
||||
RpcError::Server { code, message, data } => {
|
||||
let code = if message.to_lowercase().contains("auth") { AUTH_REQUIRED } else { code };
|
||||
// Protocol errors can list method names containing "auth"; they are not sign-in failures.
|
||||
let protocol = matches!(
|
||||
code,
|
||||
codes::PARSE_ERROR | codes::INVALID_REQUEST | codes::METHOD_NOT_FOUND | codes::INVALID_PARAMS
|
||||
);
|
||||
let code = if !protocol && message.to_lowercase().contains("auth") { AUTH_REQUIRED } else { code };
|
||||
ResponseError { code, message, data }
|
||||
}
|
||||
RpcError::Closed => error(codes::INTERNAL_ERROR, "Codex exited"),
|
||||
@@ -426,10 +431,48 @@ impl CodexShim {
|
||||
async fn rollback(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session = str_param(params, "sessionId")?;
|
||||
let turns = params.get("turns").and_then(Value::as_u64).filter(|n| *n > 0).ok_or_else(|| invalid("turns"))?;
|
||||
self.call("thread/rollback", json!({ "threadId": session, "numTurns": turns })).await?;
|
||||
match self.call("thread/rollback", json!({ "threadId": session, "numTurns": turns })).await {
|
||||
Ok(_) => {}
|
||||
Err(e)
|
||||
if e.code == codes::METHOD_NOT_FOUND
|
||||
|| (e.code == codes::INVALID_REQUEST
|
||||
&& e.message.contains("unknown variant `thread/rollback`")) =>
|
||||
{
|
||||
self.revert(session, turns).await?;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
Ok(json!({}))
|
||||
}
|
||||
|
||||
/// New Codex versions replace rollback counts with an exclusive turn id.
|
||||
async fn revert(&self, session: &str, mut remaining: u64) -> Result<(), ResponseError> {
|
||||
let mut cursor = Value::Null;
|
||||
let mut seen = HashSet::new();
|
||||
loop {
|
||||
let page = self
|
||||
.call(
|
||||
"thread/turns/list",
|
||||
json!({ "threadId": session, "sortDirection": "desc", "limit": remaining.min(100), "cursor": cursor }),
|
||||
)
|
||||
.await?;
|
||||
let turns = page.get("data").and_then(Value::as_array).ok_or_else(|| invalid("Codex returned no turns"))?;
|
||||
if remaining <= turns.len() as u64 {
|
||||
let before = str_param(&turns[remaining as usize - 1], "id")?;
|
||||
self.call("thread/revert", json!({ "threadId": session, "beforeTurnId": before })).await?;
|
||||
return Ok(());
|
||||
}
|
||||
remaining -= turns.len() as u64;
|
||||
let next = page.get("nextCursor").and_then(Value::as_str);
|
||||
let Some(next) = next.filter(|next| seen.insert((*next).to_owned())) else {
|
||||
return Err(invalid(
|
||||
"Codex history has fewer turns than the conversation; reload the task before editing",
|
||||
));
|
||||
};
|
||||
cursor = json!(next);
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops following the session's thread (codex unloads it once nothing follows it).
|
||||
async fn close(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session = str_param(params, "sessionId")?;
|
||||
|
||||
@@ -593,6 +593,104 @@ async fn resume_replays_history_then_forks_and_rolls_back() {
|
||||
assert_eq!(sent(&frames, "thread/unsubscribe")[0]["params"], json!({"threadId": thread}));
|
||||
}
|
||||
|
||||
async fn rollback_replies(turns: u32, replies: Vec<(&str, Value)>) -> (Result<Value, RpcError>, Vec<Value>) {
|
||||
let frames = replies
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.flat_map(|(i, (method, mut reply))| {
|
||||
let id = i + 1;
|
||||
reply["id"] = json!(id);
|
||||
[(true, json!({ "id": id, "method": method })), (false, reply)]
|
||||
})
|
||||
.collect();
|
||||
let transcript = Transcript { meta: Value::Null, frames };
|
||||
let (ours, theirs) = tokio::io::duplex(1 << 16);
|
||||
let acp = attach(Arc::new(Client::default()), |events| {
|
||||
let (read, write) = tokio::io::split(ours);
|
||||
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
|
||||
})
|
||||
.unwrap();
|
||||
let (read, write) = tokio::io::split(theirs);
|
||||
let player = tokio::spawn(async move { play(&transcript, read, write).await });
|
||||
let result = request(&acp, "_openidea/rollback", json!({ "sessionId": "s", "turns": turns })).await;
|
||||
let (sent, _read, _write) = player.await.unwrap();
|
||||
acp.kill();
|
||||
(result, sent)
|
||||
}
|
||||
|
||||
fn removed_rollback() -> Value {
|
||||
json!({ "error": { "code": -32600, "message": "Invalid request: unknown variant `thread/rollback`, expected one of `thread/revert`, `account/gatewayOAuth/read`, `getAuthStatus`" } })
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn removed_rollback_reverts_before_the_target_turn_across_pages() {
|
||||
let (result, frames) = rollback_replies(
|
||||
3,
|
||||
vec![
|
||||
("thread/rollback", removed_rollback()),
|
||||
(
|
||||
"thread/turns/list",
|
||||
json!({ "result": { "data": [{ "id": "last" }, { "id": "middle" }], "nextCursor": "older" } }),
|
||||
),
|
||||
(
|
||||
"thread/turns/list",
|
||||
json!({ "result": { "data": [{ "id": "edited" }, { "id": "retained" }], "nextCursor": null } }),
|
||||
),
|
||||
("thread/revert", json!({ "result": { "thread": { "id": "s", "turns": [] } } })),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result.unwrap(), json!({}));
|
||||
let pages = sent(&frames, "thread/turns/list");
|
||||
assert_eq!(pages[0]["params"], json!({ "threadId": "s", "sortDirection": "desc", "limit": 3, "cursor": null }));
|
||||
assert_eq!(pages[1]["params"]["cursor"], "older");
|
||||
assert_eq!(pages[1]["params"]["limit"], 1);
|
||||
assert_eq!(sent(&frames, "thread/revert")[0]["params"], json!({ "threadId": "s", "beforeTurnId": "edited" }));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn method_not_found_reverts_the_latest_turn() {
|
||||
let (result, frames) = rollback_replies(
|
||||
1,
|
||||
vec![
|
||||
("thread/rollback", json!({ "error": { "code": -32601, "message": "Method not found" } })),
|
||||
("thread/turns/list", json!({ "result": { "data": [{ "id": "last" }], "nextCursor": null } })),
|
||||
("thread/revert", json!({ "result": {} })),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result.unwrap(), json!({}));
|
||||
assert_eq!(sent(&frames, "thread/revert")[0]["params"]["beforeTurnId"], "last");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn rollback_refusals_are_not_retried_as_revert() {
|
||||
let (result, frames) = rollback_replies(
|
||||
1,
|
||||
vec![("thread/rollback", json!({ "error": { "code": -32600, "message": "a turn is still running" } }))],
|
||||
)
|
||||
.await;
|
||||
assert!(result.unwrap_err().to_string().contains("a turn is still running"));
|
||||
assert_eq!(frames.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn incomplete_or_repeated_history_pages_do_not_revert_the_wrong_turn() {
|
||||
for next in [Value::Null, json!("older")] {
|
||||
let (result, frames) = rollback_replies(
|
||||
3,
|
||||
vec![
|
||||
("thread/rollback", removed_rollback()),
|
||||
("thread/turns/list", json!({ "result": { "data": [{ "id": "last" }], "nextCursor": "older" } })),
|
||||
("thread/turns/list", json!({ "result": { "data": [], "nextCursor": next } })),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert!(result.unwrap_err().to_string().contains("reload the task"));
|
||||
assert!(sent(&frames, "thread/revert").is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn steering_adds_to_the_running_turn() {
|
||||
let (results, _client, frames, _) = replay(Scenario::Steer).await;
|
||||
|
||||
@@ -21,18 +21,26 @@ use std::sync::Arc;
|
||||
/// The newest install of `command` on the `PATH` a child sees, by its `--version`.
|
||||
/// Several installs are common (npm, Homebrew, the vendor's own installer), and the first
|
||||
/// on `PATH` is often an old one that the service no longer serves the current models to.
|
||||
/// A path, or a name found once (or not at all), is used as it is.
|
||||
/// A path, or a name not found on `PATH`, is used as it is; a single match returns its
|
||||
/// resolved path so Windows `PATHEXT` shims (`claude.cmd`, `codex.cmd`) start.
|
||||
pub(crate) fn newest_install(command: &str) -> String {
|
||||
if Path::new(command).components().count() > 1 {
|
||||
let path = ide_core::process::host_var_os("PATH")
|
||||
.or_else(|| ide_core::process::shell_env().find(|(k, _)| *k == "PATH").map(|(_, v)| v.to_owned()))
|
||||
.unwrap_or_default();
|
||||
newest_install_in(command, &path)
|
||||
}
|
||||
|
||||
fn newest_install_in(command: &str, search: &std::ffi::OsStr) -> String {
|
||||
if Path::new(command).components().count() > 1 || Path::new(command).is_absolute() {
|
||||
return command.to_owned();
|
||||
}
|
||||
let path = ide_core::process::host_var_os("PATH")
|
||||
.or_else(|| ide_core::process::shell_env().find(|(k, _)| *k == "PATH").map(|(_, v)| v.to_owned()));
|
||||
let pathext = ide_core::process::host_var_os("PATHEXT");
|
||||
let names =
|
||||
ide_core::process::executable_names(command, cfg!(windows), pathext.as_deref().and_then(|p| p.to_str()));
|
||||
let mut seen = Vec::new();
|
||||
let candidates: Vec<PathBuf> = path
|
||||
.iter()
|
||||
.flat_map(std::env::split_paths)
|
||||
.map(|dir| dir.join(command))
|
||||
let candidates: Vec<PathBuf> = std::env::split_paths(search)
|
||||
.filter(|d| !d.as_os_str().is_empty())
|
||||
.flat_map(|dir| names.iter().map(move |n| dir.join(n)))
|
||||
.filter(|p| p.is_file())
|
||||
.filter(|p| {
|
||||
let real = dunce::canonicalize(p).unwrap_or_else(|_| p.clone());
|
||||
@@ -42,7 +50,7 @@ pub(crate) fn newest_install(command: &str) -> String {
|
||||
})
|
||||
.collect();
|
||||
if candidates.len() < 2 {
|
||||
return command.to_owned();
|
||||
return candidates.into_iter().next().map_or_else(|| command.to_owned(), |p| p.to_string_lossy().into_owned());
|
||||
}
|
||||
candidates
|
||||
.into_iter()
|
||||
@@ -56,7 +64,7 @@ fn version_of(program: &Path) -> Option<Vec<u64>> {
|
||||
let mut cmd = std::process::Command::new(program);
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
let out = cmd.arg("--version").envs(ide_core::process::shell_env()).output().ok()?;
|
||||
parse_version(&String::from_utf8_lossy(&out.stdout))
|
||||
parse_version(&ide_core::output_encoding::decode_tool_output(&out.stdout))
|
||||
}
|
||||
|
||||
fn parse_version(text: &str) -> Option<Vec<u64>> {
|
||||
@@ -66,16 +74,6 @@ fn parse_version(text: &str) -> Option<Vec<u64>> {
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn versions_are_read_from_either_side_of_the_name() {
|
||||
assert_eq!(parse_version("codex-cli 0.164.0\n"), Some(vec![0, 164, 0]));
|
||||
assert_eq!(parse_version("2.1.312 (Claude Code)"), Some(vec![2, 1, 312]));
|
||||
assert_eq!(parse_version("v1.2"), Some(vec![1, 2]));
|
||||
assert_eq!(parse_version("no version here"), None);
|
||||
assert!(parse_version("codex-cli 0.164.0") > parse_version("codex-cli 0.147.0"));
|
||||
}
|
||||
|
||||
/// The agent side of an in-process ACP connection.
|
||||
pub(crate) trait Shim: Handler {
|
||||
/// Called once, before any message arrives: the connection to the client, for
|
||||
@@ -94,3 +92,56 @@ pub(crate) fn serve<S: Shim>(shim: Arc<S>, client: Arc<dyn Handler>) -> Peer {
|
||||
shim.attach(to_client);
|
||||
Peer::connect_framed(or, ow, client, Framing::Lines)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn versions_are_read_from_either_side_of_the_name() {
|
||||
assert_eq!(parse_version("codex-cli 0.164.0\n"), Some(vec![0, 164, 0]));
|
||||
assert_eq!(parse_version("2.1.312 (Claude Code)"), Some(vec![2, 1, 312]));
|
||||
assert_eq!(parse_version("v1.2"), Some(vec![1, 2]));
|
||||
assert_eq!(parse_version("no version here"), None);
|
||||
assert!(parse_version("codex-cli 0.164.0") > parse_version("codex-cli 0.147.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newest_install_resolves_single_candidate_and_keeps_missing_or_paths() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let a = dir.path().join("a");
|
||||
let b = dir.path().join("b");
|
||||
std::fs::create_dir_all(&a).unwrap();
|
||||
std::fs::create_dir_all(&b).unwrap();
|
||||
std::fs::write(a.join("claude"), "#!/bin/sh\n").unwrap();
|
||||
std::fs::write(b.join("claude.cmd"), "@echo off\n").unwrap();
|
||||
let search = std::env::join_paths([&a, &b]).unwrap();
|
||||
if cfg!(windows) {
|
||||
assert_eq!(newest_install_in("claude", &search), b.join("claude.cmd").to_string_lossy());
|
||||
} else {
|
||||
assert_eq!(newest_install_in("claude", &search), a.join("claude").to_string_lossy());
|
||||
}
|
||||
assert_eq!(newest_install_in("nope", &search), "nope");
|
||||
assert_eq!(newest_install_in("bin/claude", &search), "bin/claude");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn newest_install_compares_versions_across_path_entries() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let old = dir.path().join("old");
|
||||
let new = dir.path().join("new");
|
||||
for (path, version) in [(&old, "2.9.0"), (&new, "2.10.0")] {
|
||||
std::fs::create_dir_all(path).unwrap();
|
||||
let executable = path.join("agent");
|
||||
std::fs::write(&executable, format!("#!/bin/sh\necho {version}\n")).unwrap();
|
||||
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
for paths in [[&old, &new], [&new, &old]] {
|
||||
let search = std::env::join_paths(paths).unwrap();
|
||||
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -335,7 +335,7 @@ pub fn mark_updates(paths: &RegistryPaths, providers: &mut [AgentProvider]) {
|
||||
|
||||
/// HTTPS only, redirects included. Tests serve downloads over `file://`.
|
||||
fn http() -> IdeResult<Http> {
|
||||
let http = Http::new(&ide_tools::default_search_path())?;
|
||||
let http = Http::new(&ide_core::tool_path::search_path())?;
|
||||
Ok(if cfg!(test) { http } else { http.https_only() })
|
||||
}
|
||||
|
||||
|
||||
@@ -185,7 +185,23 @@ pub(crate) fn recorder(out: PathBuf) -> Connector {
|
||||
let file = Arc::new(Mutex::new(String::new()));
|
||||
let connections = Arc::new(Mutex::new(0u32));
|
||||
Arc::new(move |spec, cwd, client, on_stderr| {
|
||||
let mut cmd = tokio::process::Command::new(&spec.command);
|
||||
let program = {
|
||||
let path = Path::new(&spec.command);
|
||||
if path.components().count() > 1 || path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
let search = spec
|
||||
.env
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
.map(|(_, v)| std::ffi::OsString::from(v))
|
||||
.or_else(|| ide_core::process::shell_env().find(|(k, _)| k == "PATH").map(|(_, v)| v))
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"))
|
||||
.unwrap_or_default();
|
||||
ide_core::process::find_executable(&spec.command, &search).unwrap_or_else(|| path.to_path_buf())
|
||||
}
|
||||
};
|
||||
let mut cmd = tokio::process::Command::new(&program);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
let mut child = cmd
|
||||
.args(&spec.args)
|
||||
|
||||
@@ -210,7 +210,7 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
let names = |c: Vec<AgentCommand>| c.into_iter().map(|c| c.name).collect::<Vec<_>>();
|
||||
|
||||
let mgr_a = manager_at(&a, &models, Arc::new(FakeAgent::default()));
|
||||
// Before any session: the skills on disk.
|
||||
// Before any session: only the skills on disk.
|
||||
assert_eq!(names(mgr_a.commands("claude", None).await.unwrap()), ["triage"]);
|
||||
let task = mgr_a
|
||||
.create(NewAgentTask {
|
||||
@@ -227,6 +227,8 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
assert_eq!(names(mgr_a.commands("claude", Some(&task.id)).await.unwrap()), ["review", "triage"]);
|
||||
// Other agents get only what they offered.
|
||||
assert!(mgr_a.commands("codex", None).await.unwrap().is_empty());
|
||||
mgr_a.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr_a, &task.id, AgentStatus::Ready).await;
|
||||
mgr_a.shutdown();
|
||||
|
||||
// Another project shares the settings but not the commands.
|
||||
@@ -239,6 +241,45 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
assert_eq!(names(mgr_a.providers().into_iter().find(|p| p.id == "claude").unwrap().commands), ["review"]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metadata() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager_at(tmp.path(), &tmp.path().join("models.json"), agent);
|
||||
for provider in ["claude", "claude-acp", "opencode2", "codex", "custom"] {
|
||||
assert!(mgr.commands(provider, None).await.unwrap().is_empty(), "{provider}");
|
||||
}
|
||||
let commands = mgr.commands("opencode", None).await.unwrap();
|
||||
assert_eq!(commands.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["compact"]);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("Hello"),
|
||||
provider: "opencode".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let advertised = AgentCommand {
|
||||
name: "compact".into(),
|
||||
description: "Agent supplied description".into(),
|
||||
hint: Some("instructions".into()),
|
||||
};
|
||||
mgr.task(&task.id).unwrap().state.lock().task.commands = vec![advertised.clone()];
|
||||
// The task's provider wins over the caller's provider; metadata is not replaced.
|
||||
let commands = mgr.commands("claude", Some(&task.id)).await.unwrap();
|
||||
assert_eq!(commands.len(), 1);
|
||||
assert_eq!(commands[0].name, advertised.name);
|
||||
assert_eq!(commands[0].description, advertised.description);
|
||||
assert_eq!(commands[0].hint, advertised.hint);
|
||||
// Finish the in-process agent before Tokio stops driving its permission response.
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
async fn wait_for(mgr: &AgentManager, id: &str, status: AgentStatus) {
|
||||
for _ in 0..500 {
|
||||
let task = mgr.task(id).unwrap();
|
||||
@@ -709,3 +750,110 @@ async fn usage_limits_and_late_settings() {
|
||||
let config = mgr.task(&task.id).unwrap().state.lock().task.config.clone();
|
||||
assert_eq!(config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("high"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_updates_become_a_countdown() {
|
||||
let update =
|
||||
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 })
|
||||
);
|
||||
assert_eq!(retry_of(&json!({"sessionUpdate": RETRY_UPDATE}), 0.0), None, "no attempt");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cursor_approval_switch_resolves_pending_and_survives_restart() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let new = || NewAgentTask {
|
||||
prompt: text("Fix"),
|
||||
provider: "cursor".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
};
|
||||
let task = mgr.create(new()).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
mgr.set_config(&task.id, config::CURSOR_APPROVAL, "bypass".into()).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert!(
|
||||
mgr.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|e| matches!(e, AgentEntry::Permission { chosen: Some(name), .. } if name == "Allow"))
|
||||
);
|
||||
// Agent config updates must not erase the client's approval setting.
|
||||
mgr.prompt(&task.id, text("late option"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let t = mgr.task(&task.id).unwrap();
|
||||
assert!(config::bypass_approvals("cursor", &t.state.lock().task.config));
|
||||
t.kill();
|
||||
mgr.prompt(&task.id, text("Fix again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert!(!agent.calls.lock().iter().any(|c| c.contains("bypass")));
|
||||
assert!(!config::bypass_approvals("cursor", &mgr.shared.known_config("cursor")));
|
||||
mgr.set_config(&task.id, config::CURSOR_APPROVAL, "ask".into()).await.unwrap();
|
||||
mgr.prompt(&task.id, text("Fix once more"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
// An unrelated new conversation still asks, even after the cache was updated.
|
||||
let other = mgr.create(new()).await.unwrap();
|
||||
wait_for(&mgr, &other.id, AgentStatus::NeedsInput).await;
|
||||
mgr.cancel(&other.id, None).unwrap();
|
||||
wait_for(&mgr, &other.id, AgentStatus::Ready).await;
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cursor_approval_choice_applies_before_first_prompt() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("Fix"),
|
||||
provider: "cursor".into(),
|
||||
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn archived_tasks_can_be_restored_and_continue_their_session() {
|
||||
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("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
mgr.archive(&task.id).unwrap();
|
||||
assert!(mgr.prompt(&task.id, text("again"), false).await.is_err());
|
||||
mgr.unarchive(&task.id).unwrap();
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Ready);
|
||||
assert!(mgr.task(&task.id).unwrap().live.lock().is_none());
|
||||
assert_eq!(mgr.entries(&task.id, None).unwrap().len(), entries.len());
|
||||
drop(mgr);
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Ready);
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert!(agent.calls.lock().iter().any(|call| call == "session/load"));
|
||||
assert_eq!(mgr.entries(&task.id, None).unwrap().len(), entries.len() + 2);
|
||||
mgr.unarchive(&task.id).unwrap();
|
||||
}
|
||||
@@ -96,7 +96,12 @@ pub(crate) fn without_untouched(changes: Vec<AgentChange>, before: &BTreeMap<Str
|
||||
}
|
||||
|
||||
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
|
||||
repo_at(cwd)?.file_at(path, Some(rev))
|
||||
let repo = repo_at(cwd)?;
|
||||
let encoding = match ide_vfs::load_text(path) {
|
||||
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
|
||||
Err(_) => ide_vfs::detect_encoding(&repo.file_bytes_at(path, Some(rev))?.unwrap_or_default(), None),
|
||||
};
|
||||
repo.file_at(path, Some(rev), encoding)
|
||||
}
|
||||
|
||||
/// A short ASCII branch-safe name from the task title.
|
||||
|
||||
@@ -234,6 +234,9 @@ fn maven_steps(root: &Path, model: &BuildModel, kind: BuildKind, module: Option<
|
||||
let Some(module) = module else { return Ok(tops.iter().map(|p| step(p, &[])).collect()) };
|
||||
// The reactor root containing the module builds it with what it depends on (`-pl … -am`).
|
||||
let rel = rel_str(root, module);
|
||||
if !m.projects.iter().any(|p| p.dir == rel) {
|
||||
return Err(IdeError::not_found("no linked Maven project found for module"));
|
||||
}
|
||||
let top = tops
|
||||
.iter()
|
||||
.filter(|t| t.dir.is_empty() || rel == t.dir || rel.starts_with(&format!("{}/", t.dir)))
|
||||
|
||||
@@ -39,8 +39,19 @@ pub struct BuildModel {
|
||||
/// Static model of the builds under `root`, merged with the sync results cached in `cache_dir`.
|
||||
/// Parent POMs are looked up in `maven_repo` (the configured local repository), else the default one.
|
||||
pub fn load(root: &Path, cache_dir: &Path, maven_repo: Option<PathBuf>) -> BuildModel {
|
||||
load_linked(root, cache_dir, maven_repo, &ide_core::settings::MavenSettings::default())
|
||||
}
|
||||
|
||||
/// Loads only linked Maven reactors, retaining an empty model so projects can be re-added.
|
||||
pub fn load_linked(
|
||||
root: &Path,
|
||||
cache_dir: &Path,
|
||||
maven_repo: Option<PathBuf>,
|
||||
settings: &ide_core::settings::MavenSettings,
|
||||
) -> BuildModel {
|
||||
let maven = maven::is_maven_project(root).then(|| {
|
||||
let mut m = maven::load_with_repo(root, maven_repo.or_else(maven::default_local_repo));
|
||||
maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m);
|
||||
sync::apply_maven_cache(root, cache_dir, &mut m);
|
||||
m
|
||||
});
|
||||
|
||||
@@ -967,6 +967,67 @@ pub(crate) fn load_with_repo(root: &Path, local_repo: Option<PathBuf>) -> MavenM
|
||||
model
|
||||
}
|
||||
|
||||
/// Shared linkage decision for every Maven consumer, including modules outside a reactor directory.
|
||||
#[derive(Default)]
|
||||
pub struct UnlinkedProjects {
|
||||
poms: std::collections::BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl UnlinkedProjects {
|
||||
pub fn load(root: &Path, settings: &ide_core::settings::MavenSettings) -> Self {
|
||||
if settings.unlinked_projects.is_empty() {
|
||||
return Self::default();
|
||||
}
|
||||
Self::from_model(&load(root), settings)
|
||||
}
|
||||
|
||||
pub fn from_model(model: &MavenModel, settings: &ide_core::settings::MavenSettings) -> Self {
|
||||
let mut result = Self::default();
|
||||
let mut pending = settings.unlinked_projects.clone();
|
||||
while let Some(pom) = pending.pop() {
|
||||
let pom = normalized_pom(&pom);
|
||||
if !result.poms.insert(pom.clone()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(project) = model.projects.iter().find(|p| normalized_pom(&p.pom) == pom) {
|
||||
pending.extend(project.modules.iter().cloned());
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub fn contains(&self, pom: &str) -> bool {
|
||||
self.poms.contains(&normalized_pom(pom))
|
||||
}
|
||||
|
||||
pub fn poms(&self) -> impl Iterator<Item = &str> {
|
||||
self.poms.iter().map(String::as_str)
|
||||
}
|
||||
|
||||
pub fn filter(&self, model: &mut MavenModel) {
|
||||
model.projects.retain(|p| !self.contains(&p.pom));
|
||||
for project in &mut model.projects {
|
||||
project.modules.retain(|p| !self.contains(p));
|
||||
}
|
||||
model.profiles.retain(|p| model.projects.iter().any(|project| project.profiles.contains(&p.id)));
|
||||
}
|
||||
}
|
||||
|
||||
fn normalized_pom(pom: &str) -> String {
|
||||
let pom = pom.replace('\\', "/");
|
||||
let mut parts = Vec::new();
|
||||
for part in pom.split('/') {
|
||||
match part {
|
||||
"" | "." => {}
|
||||
".." if parts.last().is_some_and(|p| *p != "..") => {
|
||||
parts.pop();
|
||||
}
|
||||
part => parts.push(part),
|
||||
}
|
||||
}
|
||||
parts.join("/")
|
||||
}
|
||||
|
||||
/// Every POM of the model (for change detection).
|
||||
pub fn build_files(root: &Path, model: &MavenModel) -> Vec<PathBuf> {
|
||||
model.projects.iter().map(|p| root.join(&p.pom)).collect()
|
||||
@@ -1459,3 +1520,45 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod linkage_tests {
|
||||
use super::*;
|
||||
use ide_core::settings::MavenSettings;
|
||||
|
||||
#[test]
|
||||
fn excludes_reactor_modules_and_profiles_but_keeps_other_roots() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for (name, body) in [
|
||||
(
|
||||
"a",
|
||||
"<modules><module>child</module><module>../shared</module></modules><profiles><profile><id>only-a</id></profile></profiles>",
|
||||
),
|
||||
("a/child", ""),
|
||||
("shared", ""),
|
||||
("b", ""),
|
||||
] {
|
||||
std::fs::create_dir_all(root.join(name)).unwrap();
|
||||
std::fs::write(
|
||||
root.join(name).join("pom.xml"),
|
||||
format!("<project><artifactId>{name}</artifactId>{body}</project>"),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let original = load_with_repo(root, None);
|
||||
let settings = MavenSettings { unlinked_projects: vec!["./a/pom.xml".into()], ..Default::default() };
|
||||
let unlinked = UnlinkedProjects::from_model(&original, &settings);
|
||||
assert!(unlinked.contains("a/child/pom.xml"));
|
||||
assert!(unlinked.contains("shared/pom.xml"));
|
||||
assert!(unlinked.contains("a/../shared/pom.xml"));
|
||||
assert!(!unlinked.contains("b/pom.xml"));
|
||||
let mut model = original.clone();
|
||||
unlinked.filter(&mut model);
|
||||
assert_eq!(model.projects.iter().map(|p| p.pom.as_str()).collect::<Vec<_>>(), ["b/pom.xml"]);
|
||||
assert!(model.profiles.is_empty());
|
||||
let mut restored = original.clone();
|
||||
UnlinkedProjects::from_model(&original, &MavenSettings::default()).filter(&mut restored);
|
||||
assert_eq!(restored, original);
|
||||
}
|
||||
}
|
||||
@@ -45,8 +45,12 @@ pub(crate) fn run(
|
||||
mut on_line: impl FnMut(Stream, &str),
|
||||
) -> IdeResult<Output> {
|
||||
tracing::info!("build: {program} {} (in {})", args.join(" "), cwd.display());
|
||||
// Output is read as UTF-8: JVMs on Windows are told to write it (see `ide_core::output_encoding`).
|
||||
let encoding =
|
||||
ide_core::output_encoding::fix(program, args, env, |k| std::env::var(k).ok(), "UTF-8", cfg!(windows));
|
||||
let mut command = Command::new(program);
|
||||
command.args(args).current_dir(cwd).envs(env).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
command.args(args).current_dir(cwd).envs(env).envs(encoding.env).stdin(Stdio::null());
|
||||
command.stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
@@ -64,7 +68,7 @@ pub(crate) fn run(
|
||||
match reader.read_until(b'\n', &mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(_) => {
|
||||
let line = String::from_utf8_lossy(&buf);
|
||||
let line = ide_core::output_encoding::decode_tool_output(&buf);
|
||||
let line = line.trim_end_matches(['\n', '\r']).to_owned();
|
||||
if tx.send((kind, line)).is_err() {
|
||||
break;
|
||||
@@ -86,6 +90,7 @@ pub(crate) fn run(
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok((_, line)) if encoding.notice.as_ref() == Some(&line) => {}
|
||||
Ok((stream, line)) => {
|
||||
on_line(stream, &line);
|
||||
text.push_str(&line);
|
||||
|
||||
@@ -23,6 +23,7 @@ pub struct SyncProgress {
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SyncOptions {
|
||||
pub maven_settings: ide_core::settings::MavenSettings,
|
||||
/// `-o` / `--offline`.
|
||||
pub offline: bool,
|
||||
/// Maven profiles (`-P`), `!id` deactivates.
|
||||
@@ -31,6 +32,8 @@ pub struct SyncOptions {
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Maven launcher replacing the project's `mvnw` / `mvn` (Settings › Maven home).
|
||||
pub maven_command: Option<String>,
|
||||
/// Resolved Gradle launcher from Settings.
|
||||
pub gradle_command: Option<String>,
|
||||
/// Maven options before the goals (`-s`, `-Dmaven.repo.local=`).
|
||||
pub maven_options: Vec<String>,
|
||||
}
|
||||
@@ -198,7 +201,8 @@ pub fn sync_maven(
|
||||
cancel: &CancellationToken,
|
||||
progress: &dyn Fn(SyncProgress),
|
||||
) -> IdeResult<()> {
|
||||
let model = maven::load(root);
|
||||
let mut model = maven::load(root);
|
||||
maven::UnlinkedProjects::from_model(&model, &options.maven_settings).filter(&mut model);
|
||||
std::fs::create_dir_all(cache_dir)?;
|
||||
let mut cache =
|
||||
MavenCache { hash: hash_files(&maven::build_files(root, &model)), verbose: true, ..MavenCache::default() };
|
||||
@@ -266,7 +270,14 @@ pub fn sync_gradle(
|
||||
args.push("--offline".into());
|
||||
}
|
||||
progress(SyncProgress { message: "Loading Gradle tasks".into(), fraction: None });
|
||||
let out = run(&model.command, &args, &root.join(&model.dir), &options.env, cancel, |_| {})?;
|
||||
let out = run(
|
||||
options.gradle_command.as_deref().unwrap_or(&model.command),
|
||||
&args,
|
||||
&root.join(&model.dir),
|
||||
&options.env,
|
||||
cancel,
|
||||
|_| {},
|
||||
)?;
|
||||
let cache = GradleCache {
|
||||
hash: hash_files(&gradle::build_files(root, &model)),
|
||||
at_ms: now_ms(),
|
||||
@@ -280,6 +291,29 @@ pub fn sync_gradle(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn gradle_sync_uses_resolved_command_and_environment() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::write(root.join("build.gradle"), "").unwrap();
|
||||
let launcher = root.join("configured-gradle");
|
||||
std::fs::write(&launcher, "#!/bin/sh\nprintf '%s\\n' \"$JAVA_HOME\" \"$GRADLE_USER_HOME\" > actual-env\n")
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let options = SyncOptions {
|
||||
gradle_command: Some(launcher.to_string_lossy().into_owned()),
|
||||
env: BTreeMap::from([
|
||||
("JAVA_HOME".into(), "/jdk21".into()),
|
||||
("GRADLE_USER_HOME".into(), "/gradle-cache".into()),
|
||||
]),
|
||||
..Default::default()
|
||||
};
|
||||
sync_gradle(root, &root.join("cache"), &options, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(root.join("actual-env")).unwrap(), "/jdk21\n/gradle-cache\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caches_merge_and_go_stale() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
[package]
|
||||
name = "ide-clipboard"
|
||||
description = "The OS clipboard's file list (Explorer <-> project view): Windows CF_HDROP read/write, no window or message loop"
|
||||
description = "The OS clipboard's file list (Explorer <-> project view): Windows CF_HDROP or macOS NSPasteboard file URLs, no window or message loop"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2 = { version = "0.6", default-features = false, features = ["std"] }
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSDictionary", "NSEnumerator", "NSObject", "NSString", "NSURL", "NSValue"] }
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSPasteboard"] }
|
||||
@@ -7,9 +7,12 @@
|
||||
//! in full rather than rendered on demand, so no window or message loop is
|
||||
//! needed and the list survives after `CloseClipboard`.
|
||||
//!
|
||||
//! Other platforms keep file lists elsewhere (`public.file-url` on macOS,
|
||||
//! `text/uri-list` on X11) and are not wired up: [`files`] is empty and
|
||||
//! [`set_files`] fails there.
|
||||
//! macOS keeps one `public.file-url` item per file on the general
|
||||
//! `NSPasteboard`; `NSURL` reads and writes them, so Finder's copies paste here
|
||||
//! and ours paste in Finder.
|
||||
//!
|
||||
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
|
||||
//! empty and [`set_files`] fails there.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -218,7 +221,78 @@ mod imp {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
#[cfg(target_os = "macos")]
|
||||
mod imp {
|
||||
use objc2::ClassType;
|
||||
use objc2::rc::{Retained, autoreleasepool};
|
||||
use objc2::runtime::{AnyClass, AnyObject, ProtocolObject};
|
||||
use objc2_app_kit::{
|
||||
NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
|
||||
};
|
||||
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSURL};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// `NSURL` as the one class to read, limited to file URLs: a web link the
|
||||
/// user copied is not a file to paste.
|
||||
fn read_file_urls<R>(
|
||||
f: impl FnOnce(&NSPasteboard, &NSArray<AnyClass>, &NSDictionary<NSPasteboardReadingOptionKey, AnyObject>) -> R,
|
||||
) -> R {
|
||||
autoreleasepool(|_| {
|
||||
let board = NSPasteboard::generalPasteboard();
|
||||
let classes = NSArray::from_slice(&[NSURL::class()]);
|
||||
let yes = NSNumber::new_bool(true);
|
||||
// SAFETY: the key is an AppKit constant, valid for the process' lifetime.
|
||||
let key = unsafe { NSPasteboardURLReadingFileURLsOnlyKey };
|
||||
let options = NSDictionary::from_slices(&[key], &[yes.as_ref() as &AnyObject]);
|
||||
f(&board, &classes, &options)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn has_files() -> bool {
|
||||
// SAFETY: the class list holds `NSURL`, which reads from pasteboards,
|
||||
// and the option takes an `NSNumber`.
|
||||
read_file_urls(|board, classes, options| unsafe {
|
||||
board.canReadObjectForClasses_options(classes, Some(options))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn files() -> Vec<PathBuf> {
|
||||
read_file_urls(|board, classes, options| {
|
||||
// SAFETY: as in `has_files`; every object read for `NSURL` is one.
|
||||
let Some(objects) = (unsafe { board.readObjectsForClasses_options(classes, Some(options)) }) else {
|
||||
return Vec::new();
|
||||
};
|
||||
objects
|
||||
.iter()
|
||||
.filter_map(|object| object.downcast::<NSURL>().ok())
|
||||
.filter_map(|url| url.to_file_path())
|
||||
// Finder ends a folder's URL in `/`; the project view names it without.
|
||||
.map(|path| path.components().collect())
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
autoreleasepool(|_| {
|
||||
// Folders get a directory URL (ending in `/`), as Finder writes them.
|
||||
let urls: Vec<Retained<NSURL>> = paths
|
||||
.iter()
|
||||
.filter_map(|p| if p.is_dir() { NSURL::from_directory_path(p) } else { NSURL::from_file_path(p) })
|
||||
.collect();
|
||||
if urls.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let writers: Vec<&ProtocolObject<dyn NSPasteboardWriting>> =
|
||||
urls.iter().map(|url| ProtocolObject::from_ref(&**url)).collect();
|
||||
let board = NSPasteboard::generalPasteboard();
|
||||
// Replacing the list also drops the text the user copied before.
|
||||
board.clearContents();
|
||||
board.writeObjects(&NSArray::from_slice(&writers))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(windows, target_os = "macos")))]
|
||||
mod imp {
|
||||
use std::path::PathBuf;
|
||||
|
||||
|
||||
@@ -7,9 +7,16 @@ license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
dunce.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
specta-typescript.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio-util.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_Globalization"] }
|
||||
@@ -32,10 +32,13 @@ pub enum IdeEvent {
|
||||
doc: DocId,
|
||||
dirty: bool,
|
||||
},
|
||||
/// An open document's language changed (Settings › File Types, Override File Type).
|
||||
/// An open document's language changed (Settings › File Types, Override File
|
||||
/// Type), or its UI mode (a framework's root marker appeared or went).
|
||||
DocLanguage {
|
||||
doc: DocId,
|
||||
language: crate::LanguageId,
|
||||
/// See `DocumentInfo::ui_mode`.
|
||||
ui_mode: Option<String>,
|
||||
},
|
||||
/// Full replacement of diagnostics for one file from one producer.
|
||||
Diagnostics {
|
||||
@@ -112,11 +115,22 @@ pub enum IdeEvent {
|
||||
id: u64,
|
||||
prompt: String,
|
||||
kind: AskpassKind,
|
||||
/// The dialog offers "Remember" for the answer (git HTTPS passwords).
|
||||
remember: bool,
|
||||
},
|
||||
/// Prompt `id` was answered (in any window) or gave up.
|
||||
AskpassDone {
|
||||
id: u64,
|
||||
},
|
||||
/// The kernel of an open notebook changed state (`starting`, `idle`, `busy`,
|
||||
/// `dead`); `message` says why it failed to start or died.
|
||||
NotebookKernel {
|
||||
/// Backend document incarnation; stale queued events cannot target a reopen.
|
||||
id: String,
|
||||
path: crate::IpcPath,
|
||||
state: String,
|
||||
message: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
/// What an askpass prompt asks for.
|
||||
|
||||
@@ -12,6 +12,7 @@ pub mod ignored;
|
||||
pub mod inspection_settings;
|
||||
pub mod ipc_path;
|
||||
pub mod jsonc;
|
||||
pub mod output_encoding;
|
||||
pub mod process;
|
||||
pub mod project_dir;
|
||||
pub mod proxy_settings;
|
||||
@@ -19,6 +20,8 @@ pub mod remote_settings;
|
||||
pub mod settings;
|
||||
pub mod task;
|
||||
pub mod text;
|
||||
pub mod tool_path;
|
||||
pub mod version_managers;
|
||||
pub mod workflow_settings;
|
||||
|
||||
pub use error::{IdeError, IdeResult};
|
||||
|
||||
@@ -0,0 +1,489 @@
|
||||
//! Makes the output of JVM and Python processes match the encoding the IDE decodes.
|
||||
//!
|
||||
//! On Windows both write piped output in the ANSI code page (GBK on a Chinese
|
||||
//! system: `System.out.println`, `javac` errors, Maven / Gradle logs, `print`), while
|
||||
//! the console decodes the configured encoding (UTF-8 by default). They are told
|
||||
//! which one to use:
|
||||
//! - `java`: `stdout.encoding` / `stderr.encoding` (JDK 19+) and their `sun.*`
|
||||
//! forerunners (JDK 8–18) on the command line, plus `file.encoding=UTF-8` for a
|
||||
//! UTF-8 console, the default charset of JDK 18+, which logging frameworks' console
|
||||
//! appenders write in on older JDKs too.
|
||||
//! - Build tools and launcher scripts (Maven, Gradle, sbt, …): the same `std*.encoding`
|
||||
//! properties in `JAVA_TOOL_OPTIONS`, the one variable every JVM reads, so the JVMs
|
||||
//! they fork get them too (`spring-boot:run`, Surefire, `bootRun`, test workers).
|
||||
//! Each JVM then reports "Picked up JAVA_TOOL_OPTIONS: …" on stderr (which a build tool
|
||||
//! may copy to its stdout); that line is hidden again ([`NoticeFilter`]). `file.encoding` is left alone there: it would change
|
||||
//! how a build reads sources that declare no encoding.
|
||||
//! - Python: `PYTHONIOENCODING`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Decodes complete lines or collected output from IDE-managed tools, preferring UTF-8.
|
||||
/// Windows launcher/native diagnostics fall back to the system ANSI code page.
|
||||
/// Callers must buffer incomplete lines so multibyte characters are never split.
|
||||
/// Run consoles and protocol streams have their own encoding contracts.
|
||||
pub fn decode_tool_output(bytes: &[u8]) -> String {
|
||||
#[cfg(windows)]
|
||||
// SAFETY: GetACP is an argument-less query with no preconditions.
|
||||
let code_page = unsafe { windows_sys::Win32::Globalization::GetACP() };
|
||||
#[cfg(not(windows))]
|
||||
let code_page = 65001;
|
||||
decode_tool_output_with_code_page(bytes, code_page)
|
||||
}
|
||||
|
||||
fn decode_tool_output_with_code_page(bytes: &[u8], code_page: u32) -> String {
|
||||
if let Ok(text) = std::str::from_utf8(bytes) {
|
||||
return text.to_owned();
|
||||
}
|
||||
let encoding = encoding_for_code_page(code_page).unwrap_or(encoding_rs::UTF_8);
|
||||
// Collected output can mix UTF-8 JVM lines with native launcher diagnostics.
|
||||
let mut text = String::new();
|
||||
for line in bytes.split_inclusive(|b| *b == b'\n') {
|
||||
match std::str::from_utf8(line) {
|
||||
Ok(line) => text.push_str(line),
|
||||
Err(_) => text.push_str(&encoding.decode_without_bom_handling(line).0),
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn encoding_for_code_page(cp: u32) -> Option<&'static encoding_rs::Encoding> {
|
||||
Some(match cp {
|
||||
65001 => encoding_rs::UTF_8,
|
||||
936 => encoding_rs::GBK,
|
||||
54936 => encoding_rs::GB18030,
|
||||
950 => encoding_rs::BIG5,
|
||||
932 => encoding_rs::SHIFT_JIS,
|
||||
949 => encoding_rs::EUC_KR,
|
||||
866 => encoding_rs::IBM866,
|
||||
874 => encoding_rs::WINDOWS_874,
|
||||
1250 => encoding_rs::WINDOWS_1250,
|
||||
1251 => encoding_rs::WINDOWS_1251,
|
||||
1252 => encoding_rs::WINDOWS_1252,
|
||||
1253 => encoding_rs::WINDOWS_1253,
|
||||
1254 => encoding_rs::WINDOWS_1254,
|
||||
1255 => encoding_rs::WINDOWS_1255,
|
||||
1256 => encoding_rs::WINDOWS_1256,
|
||||
1257 => encoding_rs::WINDOWS_1257,
|
||||
1258 => encoding_rs::WINDOWS_1258,
|
||||
20866 => encoding_rs::KOI8_R,
|
||||
21866 => encoding_rs::KOI8_U,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
const STD_PROPERTIES: &[&str] = &["stdout.encoding", "stderr.encoding", "sun.stdout.encoding", "sun.stderr.encoding"];
|
||||
const FILE_ENCODING: &str = "file.encoding";
|
||||
const TOOL_OPTIONS: &str = "JAVA_TOOL_OPTIONS";
|
||||
|
||||
/// Build tools and launcher scripts that run on (and may fork) JVMs.
|
||||
const JVM_TOOLS: &[&str] =
|
||||
&["mvn", "mvnw", "mvnd", "gradle", "gradlew", "sbt", "ant", "kotlin", "kotlinc", "groovy", "scala", "jbang"];
|
||||
|
||||
/// What a launch needs: `-D` options to put first on a `java` command line,
|
||||
/// environment variables to set, and the notice line its JVMs print because of them.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct EncodingFix {
|
||||
pub java_args: Vec<String>,
|
||||
pub env: Vec<(String, String)>,
|
||||
/// "Picked up JAVA_TOOL_OPTIONS: …" for a variable set here alone, to drop from the output.
|
||||
pub notice: Option<String>,
|
||||
}
|
||||
|
||||
pub fn is_utf8(encoding: &str) -> bool {
|
||||
matches!(encoding.trim().to_ascii_lowercase().replace('_', "-").as_str(), "utf-8" | "utf8")
|
||||
}
|
||||
|
||||
/// File name of `command` without a Windows executable extension: `C:\jdk\bin\java.exe` → `java`.
|
||||
fn program_name(command: &str) -> String {
|
||||
let name = command.rsplit(['/', '\\']).next().unwrap_or(command).to_ascii_lowercase();
|
||||
for ext in [".exe", ".cmd", ".bat"] {
|
||||
if let Some(stem) = name.strip_suffix(ext) {
|
||||
return stem.to_owned();
|
||||
}
|
||||
}
|
||||
name
|
||||
}
|
||||
|
||||
fn sets(text: &str, properties: &[&str]) -> bool {
|
||||
properties.iter().any(|p| text.contains(&format!("-D{p}=")))
|
||||
}
|
||||
|
||||
fn options(properties: &[&str], encoding: &str) -> Vec<String> {
|
||||
properties.iter().map(|p| format!("-D{p}={encoding}")).collect()
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Kind {
|
||||
Java,
|
||||
JvmTool,
|
||||
Python,
|
||||
Other,
|
||||
}
|
||||
|
||||
fn kind(program: &str) -> Kind {
|
||||
let name = program_name(program);
|
||||
if name == "java" || name == "javaw" {
|
||||
Kind::Java
|
||||
} else if JVM_TOOLS.contains(&name.as_str()) {
|
||||
Kind::JvmTool
|
||||
} else if is_python(&name) {
|
||||
Kind::Python
|
||||
} else {
|
||||
Kind::Other
|
||||
}
|
||||
}
|
||||
|
||||
/// The options for a launch of `program` (`args`, environment `vars` over the
|
||||
/// `inherited` one) whose output is decoded as `encoding`; nothing when the
|
||||
/// process already writes it (UTF-8 off Windows) or the user chose the options.
|
||||
pub fn fix(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
vars: &BTreeMap<String, String>,
|
||||
inherited: impl Fn(&str) -> Option<String>,
|
||||
encoding: &str,
|
||||
windows: bool,
|
||||
) -> EncodingFix {
|
||||
fix_kind(kind(program), Some(args), vars, inherited, encoding, windows)
|
||||
}
|
||||
|
||||
/// [`fix`] for a command line run by the shell (`cmd /C "mvn spring-boot:run"`), whose
|
||||
/// arguments cannot be changed: its first word decides, and only variables are set.
|
||||
pub fn fix_command_line(
|
||||
line: &str,
|
||||
vars: &BTreeMap<String, String>,
|
||||
inherited: impl Fn(&str) -> Option<String>,
|
||||
encoding: &str,
|
||||
windows: bool,
|
||||
) -> EncodingFix {
|
||||
let line = line.trim_start();
|
||||
let first = match line.chars().next() {
|
||||
Some(q @ ('"' | '\'')) => line[1..].split(q).next(),
|
||||
_ => line.split(char::is_whitespace).next(),
|
||||
}
|
||||
.unwrap_or_default();
|
||||
fix_kind(kind(first), None, vars, inherited, encoding, windows)
|
||||
}
|
||||
|
||||
fn fix_kind(
|
||||
kind: Kind,
|
||||
args: Option<&[String]>,
|
||||
vars: &BTreeMap<String, String>,
|
||||
inherited: impl Fn(&str) -> Option<String>,
|
||||
encoding: &str,
|
||||
windows: bool,
|
||||
) -> EncodingFix {
|
||||
let encoding = encoding.trim();
|
||||
let mut out = EncodingFix::default();
|
||||
if encoding.is_empty() || (!windows && is_utf8(encoding)) {
|
||||
return out;
|
||||
}
|
||||
let current = |key: &str| vars.get(key).cloned().or_else(|| inherited(key)).unwrap_or_default();
|
||||
let tool_options = current(TOOL_OPTIONS);
|
||||
match (kind, args) {
|
||||
(Kind::Java, Some(args)) => {
|
||||
let java_options = format!("{} {tool_options}", current("JDK_JAVA_OPTIONS"));
|
||||
let chosen =
|
||||
|properties: &[&str]| args.iter().any(|a| sets(a, properties)) || sets(&java_options, properties);
|
||||
if !chosen(STD_PROPERTIES) {
|
||||
out.java_args = options(STD_PROPERTIES, encoding);
|
||||
}
|
||||
if is_utf8(encoding) && !chosen(&[FILE_ENCODING]) {
|
||||
out.java_args.push(format!("-D{FILE_ENCODING}=UTF-8"));
|
||||
}
|
||||
}
|
||||
(Kind::Java | Kind::JvmTool, _) => {
|
||||
if !sets(&tool_options, STD_PROPERTIES) {
|
||||
let added = options(STD_PROPERTIES, encoding).join(" ");
|
||||
let value = match tool_options.trim() {
|
||||
"" => {
|
||||
out.notice = Some(format!("Picked up {TOOL_OPTIONS}: {added}"));
|
||||
added
|
||||
}
|
||||
own => format!("{own} {added}"),
|
||||
};
|
||||
out.env.push((TOOL_OPTIONS.to_owned(), value));
|
||||
}
|
||||
}
|
||||
(Kind::Python, _) if current("PYTHONIOENCODING").trim().is_empty() => {
|
||||
out.env.push(("PYTHONIOENCODING".to_owned(), encoding.to_owned()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `vmArgs` of a launch by java-debug, which decodes the JVM's output as `encoding`
|
||||
/// (its launch attribute, UTF-8 when unset) and sets `file.encoding` itself.
|
||||
pub fn java_debug_vm_args(vm_args: &str, encoding: Option<&str>, windows: bool) -> Option<String> {
|
||||
let encoding = encoding.map(str::trim).filter(|e| !e.is_empty()).unwrap_or("UTF-8");
|
||||
if (!windows && is_utf8(encoding)) || sets(vm_args, STD_PROPERTIES) {
|
||||
return None;
|
||||
}
|
||||
let added = options(STD_PROPERTIES, encoding).join(" ");
|
||||
Some(match vm_args.trim() {
|
||||
"" => added,
|
||||
own => format!("{own} {added}"),
|
||||
})
|
||||
}
|
||||
|
||||
/// `python`, `python3`, `python3.12`, `py`, and the runners that start one.
|
||||
fn is_python(name: &str) -> bool {
|
||||
name == "python"
|
||||
|| name == "py"
|
||||
|| name.strip_prefix("python").is_some_and(|v| v.chars().all(|c| c.is_ascii_digit() || c == '.'))
|
||||
|| matches!(name, "uv" | "poetry" | "pdm" | "pytest" | "pipenv")
|
||||
}
|
||||
|
||||
/// Drops whole lines equal to `notice` from a stream of decoded text (the
|
||||
/// [`EncodingFix::notice`] each JVM prints), passing everything else through.
|
||||
/// The start of a line is held back only while it can still become the notice.
|
||||
#[derive(Debug)]
|
||||
pub struct NoticeFilter {
|
||||
notice: String,
|
||||
held: String,
|
||||
at_line_start: bool,
|
||||
}
|
||||
|
||||
impl NoticeFilter {
|
||||
pub fn new(notice: String) -> Self {
|
||||
Self { notice, held: String::new(), at_line_start: true }
|
||||
}
|
||||
|
||||
pub fn filter(&mut self, text: &str, out: &mut String) {
|
||||
for piece in text.split_inclusive('\n') {
|
||||
if !self.at_line_start && self.held.is_empty() {
|
||||
out.push_str(piece);
|
||||
self.at_line_start = piece.ends_with('\n');
|
||||
continue;
|
||||
}
|
||||
self.held.push_str(piece);
|
||||
if self.held.ends_with('\n') {
|
||||
if self.held.trim_end_matches(['\n', '\r']) != self.notice {
|
||||
out.push_str(&self.held);
|
||||
}
|
||||
self.held.clear();
|
||||
self.at_line_start = true;
|
||||
} else if !self.could_be_notice() {
|
||||
out.push_str(&self.held);
|
||||
self.held.clear();
|
||||
self.at_line_start = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The held text is the start of the notice, or all of it before a `\r\n`.
|
||||
fn could_be_notice(&self) -> bool {
|
||||
match self.held.strip_suffix('\r') {
|
||||
Some(line) => line == self.notice,
|
||||
None => self.notice.starts_with(self.held.as_str()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The held-back start of a line, at the end of the stream.
|
||||
pub fn finish(&mut self) -> String {
|
||||
std::mem::take(&mut self.held)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tool_output_prefers_utf8() {
|
||||
for cp in [936, 1252, 65001, 0] {
|
||||
for text in ["", "plain ASCII\r\n", "中文 café 🦀\n"] {
|
||||
assert_eq!(decode_tool_output_with_code_page(text.as_bytes(), cp), text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_output_decodes_native_diagnostics_and_mixed_lines() {
|
||||
const GBK: &[u8] = b"\xcf\xb5\xcd\xb3\xd5\xd2\xb2\xbb\xb5\xbd\xd6\xb8\xb6\xa8\xb5\xc4\xc2\xb7\xbe\xb6\xa1\xa3";
|
||||
assert_eq!(decode_tool_output_with_code_page(GBK, 936), "系统找不到指定的路径。");
|
||||
let mut mixed = "JVM: 中文\r\n".as_bytes().to_vec();
|
||||
mixed.extend_from_slice(GBK);
|
||||
mixed.extend_from_slice(b"\r\nlast");
|
||||
assert_eq!(decode_tool_output_with_code_page(&mixed, 936), "JVM: 中文\r\n系统找不到指定的路径。\r\nlast");
|
||||
assert_eq!(decode_tool_output_with_code_page(b"caf\xe9", 1252), "café");
|
||||
for cp in [65001, 0] {
|
||||
assert_eq!(decode_tool_output_with_code_page(b"a\xffb", cp), "a�b");
|
||||
}
|
||||
}
|
||||
|
||||
const STD_UTF8: [&str; 4] = [
|
||||
"-Dstdout.encoding=UTF-8",
|
||||
"-Dstderr.encoding=UTF-8",
|
||||
"-Dsun.stdout.encoding=UTF-8",
|
||||
"-Dsun.stderr.encoding=UTF-8",
|
||||
];
|
||||
const TOOL_UTF8: &str =
|
||||
"-Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8";
|
||||
|
||||
fn vars(vars: &[(&str, &str)]) -> BTreeMap<String, String> {
|
||||
vars.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect()
|
||||
}
|
||||
|
||||
fn run(program: &str, args: &[&str], env: &[(&str, &str)], encoding: &str, windows: bool) -> EncodingFix {
|
||||
let args: Vec<String> = args.iter().map(|a| (*a).to_owned()).collect();
|
||||
fix(program, &args, &vars(env), |_| None, encoding, windows)
|
||||
}
|
||||
|
||||
fn tool_env(f: &EncodingFix) -> Option<&str> {
|
||||
f.env.iter().find(|(k, _)| k == TOOL_OPTIONS).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_launches_write_the_console_encoding_on_windows() {
|
||||
let mut expected: Vec<&str> = STD_UTF8.to_vec();
|
||||
expected.push("-Dfile.encoding=UTF-8");
|
||||
// A source-file launch through the Oracle `javapath` shim, and an Application / Spring Boot launch.
|
||||
let java = "C:/Program Files/Common Files/Oracle/Java/javapath/java.exe";
|
||||
for program in [java, "java", "javaw.exe", r"C:\jdk\bin\java.exe", "JAVA.EXE"] {
|
||||
for args in [&["Main.java"][..], &["-cp", "a;b", "org.dromara.DromaraApplication"]] {
|
||||
let f = run(program, args, &[], "UTF-8", true);
|
||||
assert_eq!(f.java_args, expected, "{program}");
|
||||
assert!(f.env.is_empty() && f.notice.is_none());
|
||||
}
|
||||
}
|
||||
// Another console encoding: the streams follow it, the default charset stays the platform's.
|
||||
assert_eq!(
|
||||
run("java", &["-cp", "x", "a.Main"], &[], "GBK", true).java_args,
|
||||
[
|
||||
"-Dstdout.encoding=GBK",
|
||||
"-Dstderr.encoding=GBK",
|
||||
"-Dsun.stdout.encoding=GBK",
|
||||
"-Dsun.stderr.encoding=GBK"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_changes_where_output_already_matches() {
|
||||
for (program, args) in [("java", vec!["Main.java"]), ("mvn", vec!["package"]), ("python3", vec!["a.py"])] {
|
||||
assert_eq!(run(program, &args, &[], "UTF-8", false), EncodingFix::default(), "{program}");
|
||||
assert_eq!(run(program, &args, &[], "utf8", false), EncodingFix::default(), "{program}");
|
||||
assert_eq!(run(program, &args, &[], "", true), EncodingFix::default(), "{program}");
|
||||
}
|
||||
for program in ["node", "cargo", "go", "npm.cmd", "cmd.exe", "javac-wrapper"] {
|
||||
assert_eq!(run(program, &[], &[], "UTF-8", true), EncodingFix::default(), "{program}");
|
||||
}
|
||||
// A console set to another encoding elsewhere still gets it.
|
||||
assert_eq!(run("java", &["Main"], &[], "GBK", false).java_args.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_chosen_by_the_user_win() {
|
||||
let f = run("java", &["-Dstdout.encoding=GBK", "Main"], &[], "UTF-8", true);
|
||||
assert_eq!(f.java_args, ["-Dfile.encoding=UTF-8"]);
|
||||
let f = run("java", &["-Dfile.encoding=GBK", "Main"], &[], "UTF-8", true);
|
||||
assert_eq!(f.java_args, STD_UTF8);
|
||||
for key in ["JDK_JAVA_OPTIONS", TOOL_OPTIONS] {
|
||||
let f = run("java", &["Main"], &[(key, "-Dsun.stdout.encoding=GBK -Dfile.encoding=GBK")], "UTF-8", true);
|
||||
assert!(f.java_args.is_empty(), "{key}");
|
||||
}
|
||||
assert!(run("mvn.cmd", &[], &[(TOOL_OPTIONS, "-Dstdout.encoding=GBK")], "UTF-8", true).env.is_empty());
|
||||
assert!(run("python.exe", &[], &[("PYTHONIOENCODING", "gbk")], "UTF-8", true).env.is_empty());
|
||||
}
|
||||
|
||||
/// Maven's `spring-boot:run` and Surefire, Gradle's `bootRun` and test workers fork JVMs
|
||||
/// that never see `MAVEN_OPTS` / `GRADLE_OPTS`: the options go where every JVM reads them.
|
||||
#[test]
|
||||
fn build_tools_reach_the_jvms_they_fork() {
|
||||
for program in [
|
||||
"mvn.cmd",
|
||||
"mvnw.cmd",
|
||||
r"C:\maven\bin\mvn.cmd",
|
||||
"mvnd.cmd",
|
||||
"gradlew.bat",
|
||||
"gradle.bat",
|
||||
"sbt.bat",
|
||||
"kotlinc.bat",
|
||||
] {
|
||||
let f = run(program, &["spring-boot:run"], &[], "UTF-8", true);
|
||||
assert_eq!(tool_env(&f), Some(TOOL_UTF8), "{program}");
|
||||
assert_eq!(f.notice.as_deref(), Some(format!("Picked up JAVA_TOOL_OPTIONS: {TOOL_UTF8}").as_str()));
|
||||
assert!(f.java_args.is_empty());
|
||||
assert!(!tool_env(&f).unwrap().contains("file.encoding"), "a build's source encoding is left alone");
|
||||
}
|
||||
// Existing options are kept, from the configuration or the inherited environment; the
|
||||
// JVMs then print the user's own variable, which stays visible.
|
||||
let f = run("mvn.cmd", &[], &[(TOOL_OPTIONS, "-javaagent:a.jar")], "UTF-8", true);
|
||||
assert_eq!(tool_env(&f), Some(format!("-javaagent:a.jar {TOOL_UTF8}").as_str()));
|
||||
assert!(f.notice.is_none());
|
||||
let inherited =
|
||||
fix("gradlew.bat", &[], &BTreeMap::new(), |k| (k == TOOL_OPTIONS).then(|| "-Xss4m".into()), "UTF-8", true);
|
||||
assert_eq!(tool_env(&inherited), Some(format!("-Xss4m {TOOL_UTF8}").as_str()));
|
||||
for program in ["python.exe", "python3", "python3.12", "py.exe", "uv.exe", "poetry"] {
|
||||
assert_eq!(
|
||||
run(program, &[], &[], "UTF-8", true).env,
|
||||
[("PYTHONIOENCODING".to_owned(), "UTF-8".to_owned())],
|
||||
"{program}"
|
||||
);
|
||||
}
|
||||
assert_eq!(run("python3", &[], &[], "GBK", false).env, [("PYTHONIOENCODING".to_owned(), "GBK".to_owned())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_command_lines_get_variables_from_their_first_word() {
|
||||
let line = |l: &str| fix_command_line(l, &BTreeMap::new(), |_| None, "UTF-8", true);
|
||||
for l in [
|
||||
"mvn spring-boot:run -pl ruoyi-admin",
|
||||
"\"C:\\Program Files\\Maven\\bin\\mvn.cmd\" test",
|
||||
"java -jar app.jar",
|
||||
] {
|
||||
let f = line(l);
|
||||
assert_eq!(tool_env(&f), Some(TOOL_UTF8), "{l}");
|
||||
assert!(f.java_args.is_empty());
|
||||
}
|
||||
assert_eq!(line("python manage.py runserver").env[0].0, "PYTHONIOENCODING");
|
||||
assert_eq!(line("npm run dev && echo done"), EncodingFix::default());
|
||||
assert_eq!(fix_command_line("mvn test", &BTreeMap::new(), |_| None, "UTF-8", false), EncodingFix::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_debug_launches_write_what_java_debug_decodes() {
|
||||
assert_eq!(java_debug_vm_args("", None, true).as_deref(), Some(TOOL_UTF8));
|
||||
assert_eq!(java_debug_vm_args("-Xmx1g", Some(""), true), Some(format!("-Xmx1g {TOOL_UTF8}")));
|
||||
assert_eq!(java_debug_vm_args("", Some("GBK"), true).unwrap().split(' ').next(), Some("-Dstdout.encoding=GBK"));
|
||||
assert_eq!(java_debug_vm_args("-Dstdout.encoding=GBK", None, true), None);
|
||||
assert_eq!(java_debug_vm_args("-Xmx1g", None, false), None);
|
||||
assert!(java_debug_vm_args("", Some("GBK"), false).is_some());
|
||||
}
|
||||
|
||||
fn filtered(chunks: &[&str]) -> String {
|
||||
let mut f = NoticeFilter::new(format!("Picked up JAVA_TOOL_OPTIONS: {TOOL_UTF8}"));
|
||||
let mut out = String::new();
|
||||
for c in chunks {
|
||||
f.filter(c, &mut out);
|
||||
}
|
||||
out.push_str(&f.finish());
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notice_lines_are_dropped_wherever_the_chunks_split() {
|
||||
let notice = format!("Picked up JAVA_TOOL_OPTIONS: {TOOL_UTF8}");
|
||||
let text =
|
||||
format!("{notice}\r\nerror: one\n{notice}\nPicked up nothing\nPicked up JAVA_TOOL_OPTIONS: -Dx\nlast");
|
||||
let expected = "error: one\nPicked up nothing\nPicked up JAVA_TOOL_OPTIONS: -Dx\nlast";
|
||||
assert_eq!(filtered(&[&text]), expected);
|
||||
// Every split point, also inside the notice and between `\r` and `\n`.
|
||||
for i in 1..text.len() {
|
||||
let (a, b) = text.split_at(i);
|
||||
assert_eq!(filtered(&[a, b]), expected, "split at {i}");
|
||||
}
|
||||
// A line that only starts like it is not held: text mid-line passes through at once.
|
||||
let mut f = NoticeFilter::new(notice.clone());
|
||||
let mut out = String::new();
|
||||
f.filter("Pick a number: ", &mut out);
|
||||
assert_eq!(out, "Pick a number: ");
|
||||
f.filter("Picked", &mut out);
|
||||
assert_eq!(out, "Pick a number: Picked");
|
||||
// A prefix at the end of the stream comes out on finish.
|
||||
assert_eq!(filtered(&["Picked up"]), "Picked up");
|
||||
}
|
||||
}
|
||||
@@ -218,6 +218,25 @@ pub fn executable_names(name: &str, windows: bool, pathext: Option<&str>) -> Vec
|
||||
exts.iter().map(|e| format!("{name}{}", e.to_ascii_lowercase())).collect()
|
||||
}
|
||||
|
||||
/// First `search` directory holding `name` (see [`executable_names`]).
|
||||
pub fn find_executable_in(
|
||||
name: &str,
|
||||
search: &OsStr,
|
||||
windows: bool,
|
||||
pathext: Option<&str>,
|
||||
) -> Option<std::path::PathBuf> {
|
||||
let names = executable_names(name, windows, pathext);
|
||||
std::env::split_paths(search)
|
||||
.filter(|d| !d.as_os_str().is_empty())
|
||||
.find_map(|dir| names.iter().map(|n| dir.join(n)).find(|p| p.is_file()))
|
||||
}
|
||||
|
||||
/// [`find_executable_in`] for this platform (`PATHEXT` from the environment).
|
||||
pub fn find_executable(name: &str, search: &OsStr) -> Option<std::path::PathBuf> {
|
||||
let pathext = host_var_os("PATHEXT");
|
||||
find_executable_in(name, search, cfg!(windows), pathext.as_deref().and_then(|p| p.to_str()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -363,4 +382,23 @@ mod tests {
|
||||
prepare(&mut cmd);
|
||||
assert_eq!(cmd.get_envs().find(|(k, _)| *k == "PATH").and_then(|(_, v)| v), Some(OsStr::new("/custom")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_executable_finds_bare_names_on_the_given_path() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let a = dir.path().join("a");
|
||||
let b = dir.path().join("b");
|
||||
std::fs::create_dir_all(&a).unwrap();
|
||||
std::fs::create_dir_all(&b).unwrap();
|
||||
std::fs::write(a.join("agent"), "#!/bin/sh\n").unwrap();
|
||||
std::fs::write(b.join("agent.cmd"), "@echo off\n").unwrap();
|
||||
let search = std::env::join_paths([&a, &b]).unwrap();
|
||||
if cfg!(windows) {
|
||||
// The `.cmd` shim wins over a POSIX script `Command` can't start.
|
||||
assert_eq!(find_executable("agent", &search), Some(b.join("agent.cmd")));
|
||||
} else {
|
||||
assert_eq!(find_executable("agent", &search), Some(a.join("agent")));
|
||||
}
|
||||
assert_eq!(find_executable("nope", &search), None);
|
||||
}
|
||||
}
|
||||
@@ -563,12 +563,37 @@ pub struct JavaSettings {
|
||||
pub jdtls_vm_args: String,
|
||||
/// Build Tools › Maven.
|
||||
pub maven: MavenSettings,
|
||||
/// Build Tools › Gradle.
|
||||
pub gradle: GradleSettings,
|
||||
}
|
||||
|
||||
/// Build Tools › Gradle.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GradleSettings {
|
||||
/// Empty = Project JDK; otherwise a JDK home.
|
||||
pub jvm: String,
|
||||
pub distribution: GradleDistribution,
|
||||
/// Used only for the local distribution.
|
||||
pub home: String,
|
||||
/// Empty = Gradle's default user home.
|
||||
pub user_home: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GradleDistribution {
|
||||
#[default]
|
||||
Wrapper,
|
||||
Local,
|
||||
}
|
||||
|
||||
/// Build Tools › Maven.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct MavenSettings {
|
||||
/// Project-relative root POMs removed from the Maven project model.
|
||||
pub unlinked_projects: Vec<String>,
|
||||
/// Maven home (or its `mvn` executable); empty = the project's `mvnw`, else `mvn` on `PATH`.
|
||||
pub home: String,
|
||||
/// User `settings.xml` (`-s`); empty = `~/.m2/settings.xml`.
|
||||
@@ -691,3 +716,41 @@ mod tests {
|
||||
assert!(Settings::default().files.file_types.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod maven_linkage_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn maven_linkage_defaults_and_round_trips() {
|
||||
let old: MavenSettings = serde_json::from_str(r#"{"home":"/opt/maven"}"#).unwrap();
|
||||
assert!(old.unlinked_projects.is_empty());
|
||||
let settings =
|
||||
MavenSettings { unlinked_projects: vec!["pom.xml".into(), "services/api/pom.xml".into()], ..old };
|
||||
let encoded = serde_json::to_string(&settings).unwrap();
|
||||
assert!(encoded.contains("unlinkedProjects"));
|
||||
assert_eq!(serde_json::from_str::<MavenSettings>(&encoded).unwrap(), settings);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod gradle_settings_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn defaults_and_round_trip() {
|
||||
let old: JavaSettings = serde_json::from_str(r#"{"jdk":"/jdk"}"#).unwrap();
|
||||
assert_eq!(old.gradle, GradleSettings::default());
|
||||
for distribution in [GradleDistribution::Wrapper, GradleDistribution::Local] {
|
||||
let mut settings = Settings::default();
|
||||
settings.languages.java.gradle = GradleSettings {
|
||||
jvm: "/jdk21".into(),
|
||||
distribution,
|
||||
home: "/gradle".into(),
|
||||
user_home: "/cache/gradle".into(),
|
||||
};
|
||||
let restored: Settings = serde_json::from_str(&serde_json::to_string(&settings).unwrap()).unwrap();
|
||||
assert_eq!(restored.languages.java.gradle, settings.languages.java.gradle);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
//! Where the IDE looks up the executables it runs: language servers, the tools
|
||||
//! their settings come from, installers. An app started from the desktop gets a
|
||||
//! minimal `PATH`, and version managers set theirs up in shell rc files.
|
||||
|
||||
use crate::process::{host_var_os, login_env};
|
||||
use crate::version_managers;
|
||||
use std::collections::HashSet;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Where executables are looked up: this process's `PATH` (the login shell's in the
|
||||
/// app), the login shell's `PATH` as last read, then per-user directories and mise's,
|
||||
/// asdf's and pyenv's shims, for when the shell's setup didn't reach the app. Language server
|
||||
/// launchers, their settings hooks and tool detection all look here, so a settings
|
||||
/// hook finds the executable its server is launched from.
|
||||
pub fn search_path() -> OsString {
|
||||
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from);
|
||||
let shell_path = login_env().and_then(|env| env.iter().find(|(k, _)| k == "PATH").map(|(_, v)| v.clone()));
|
||||
let shims: Vec<PathBuf> = version_managers::managers().iter().map(|m| m.shims()).collect();
|
||||
let dirs = search_dirs(host_var_os("PATH").as_deref(), shell_path.as_deref(), home.as_deref(), &shims);
|
||||
std::env::join_paths(dirs).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Resolves a command on the shared path, or an explicit path relative to `root`.
|
||||
pub fn find_command(command: &str, search: &OsStr, root: &Path) -> Option<PathBuf> {
|
||||
let path = Path::new(command);
|
||||
let explicit = path.parent().is_some_and(|p| !p.as_os_str().is_empty());
|
||||
let pathext = host_var_os("PATHEXT");
|
||||
let names = crate::process::executable_names(command, cfg!(windows), pathext.as_deref().and_then(OsStr::to_str));
|
||||
let dirs = if explicit {
|
||||
vec![root.to_path_buf()]
|
||||
} else {
|
||||
std::env::split_paths(search).filter(|p| !p.as_os_str().is_empty()).map(|p| root.join(p)).collect()
|
||||
};
|
||||
dirs.into_iter().find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| is_executable(p)))
|
||||
}
|
||||
|
||||
fn is_executable(path: &Path) -> bool {
|
||||
let Ok(metadata) = path.metadata() else { return false };
|
||||
if !metadata.is_file() {
|
||||
return false;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
metadata.permissions().mode() & 0o111 != 0
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
true
|
||||
}
|
||||
|
||||
/// [`search_path`]'s directories, in order and once each. Only absolute ones: a
|
||||
/// relative entry (`.`, `node_modules/.bin`) resolves against the project, which
|
||||
/// could then supply the tools the IDE runs. One that can't be joined (a `:` in a
|
||||
/// directory name) is left out rather than failing the whole path.
|
||||
fn search_dirs(
|
||||
process_path: Option<&OsStr>,
|
||||
shell_path: Option<&OsStr>,
|
||||
home: Option<&Path>,
|
||||
shims: &[PathBuf],
|
||||
) -> Vec<PathBuf> {
|
||||
let mut dirs: Vec<PathBuf> = process_path.into_iter().chain(shell_path).flat_map(std::env::split_paths).collect();
|
||||
if let Some(home) = home {
|
||||
dirs.extend(USER_DIRS.iter().map(|d| home.join(d)));
|
||||
dirs.extend(nvm_bins(&home.join(".nvm/versions/node")));
|
||||
}
|
||||
// Version managers' shims after real tool directories: a shim exists for a command any
|
||||
// installed version has, and fails when the selected one lacks it. Before the system's,
|
||||
// as the managers' shell setup puts them.
|
||||
dirs.extend(home.map(|h| h.join(".pyenv/shims")));
|
||||
dirs.extend(shims.iter().cloned());
|
||||
dirs.extend(SYSTEM_DIRS.iter().map(PathBuf::from));
|
||||
let mut seen = HashSet::new();
|
||||
dirs.retain(|d| d.is_absolute() && std::env::join_paths([d]).is_ok() && seen.insert(d.clone()));
|
||||
dirs
|
||||
}
|
||||
|
||||
/// Tool directories below the home directory.
|
||||
const USER_DIRS: &[&str] = &[
|
||||
".cargo/bin",
|
||||
".local/bin",
|
||||
"go/bin",
|
||||
".bun/bin",
|
||||
".deno/bin",
|
||||
".npm-global/bin",
|
||||
".volta/bin",
|
||||
// Set up in shell rc files: fnm's default Node and pnpm's global bin (Linux, then macOS).
|
||||
".local/share/fnm/aliases/default/bin",
|
||||
"Library/Application Support/fnm/aliases/default/bin",
|
||||
".fnm/aliases/default/bin",
|
||||
".local/share/pnpm/bin",
|
||||
".local/share/pnpm",
|
||||
"Library/pnpm/bin",
|
||||
"Library/pnpm",
|
||||
];
|
||||
|
||||
const SYSTEM_DIRS: &[&str] = &["/opt/homebrew/bin", "/usr/local/go/bin", "/usr/local/bin", "/usr/bin", "/bin"];
|
||||
|
||||
/// The `bin` directories of nvm's Node versions in `dir`, newest first.
|
||||
fn nvm_bins(dir: &Path) -> Vec<PathBuf> {
|
||||
let mut versions: Vec<(Vec<u64>, PathBuf)> = std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| (version_key(&e.file_name().to_string_lossy()), e.path().join("bin")))
|
||||
.collect();
|
||||
versions.sort();
|
||||
versions.into_iter().rev().map(|(_, bin)| bin).collect()
|
||||
}
|
||||
|
||||
/// `v22.10.1` as `[22, 10, 1]`: v22 is newer than v9, v20.10 newer than v20.9.
|
||||
fn version_key(name: &str) -> Vec<u64> {
|
||||
name.trim_start_matches('v').split('.').map(|n| n.parse().unwrap_or(0)).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn commands_resolve_on_path_and_explicit_paths_under_root() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bin = dir.path().join("bin");
|
||||
std::fs::create_dir(&bin).unwrap();
|
||||
let name = if cfg!(windows) { "ngserver.cmd" } else { "ngserver" };
|
||||
std::fs::write(bin.join(name), "").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(bin.join(name), std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let search = std::env::join_paths([&bin]).unwrap();
|
||||
assert_eq!(find_command("ngserver", &search, dir.path()), Some(bin.join(name)));
|
||||
assert_eq!(find_command("bin/ngserver", &search, dir.path()), Some(bin.join(name)));
|
||||
assert_eq!(find_command(bin.join(name).to_str().unwrap(), &search, dir.path()), Some(bin.join(name)));
|
||||
assert_eq!(find_command("absent", &search, dir.path()), None);
|
||||
for command in ["bin/ngserver", bin.join(name).to_str().unwrap()] {
|
||||
assert_eq!(find_command(command, OsStr::new(""), dir.path()), Some(bin.join(name)));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn non_executable_files_do_not_shadow_commands() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dirs = [tmp.path().join("first"), tmp.path().join("second")];
|
||||
for (dir, mode) in dirs.iter().zip([0o644, 0o755]) {
|
||||
std::fs::create_dir(dir).unwrap();
|
||||
let file = dir.join("ngserver");
|
||||
std::fs::write(&file, "#!/bin/sh\n").unwrap();
|
||||
std::fs::set_permissions(file, std::fs::Permissions::from_mode(mode)).unwrap();
|
||||
}
|
||||
let path = std::env::join_paths(&dirs).unwrap();
|
||||
assert_eq!(find_command("ngserver", &path, tmp.path()), Some(dirs[1].join("ngserver")));
|
||||
assert_eq!(find_command("first/ngserver", &path, tmp.path()), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn search_dirs_put_the_process_path_first_and_shims_after_real_tools() {
|
||||
let shims = [PathBuf::from("/home/me/.local/share/mise/shims"), "/home/me/.asdf/shims".into()];
|
||||
let dirs = search_dirs(
|
||||
Some(OsStr::new("/usr/bin:.:node_modules/.bin:/opt/tools")),
|
||||
// nushell prints `$PATH` as is.
|
||||
Some(OsStr::new("$PATH:/opt/tools:/home/me/.asdf/shims")),
|
||||
Some(Path::new("/home/me")),
|
||||
&shims,
|
||||
);
|
||||
let at = |d: &str| dirs.iter().position(|p| p == Path::new(d)).unwrap();
|
||||
assert_eq!(dirs[..3], [PathBuf::from("/usr/bin"), "/opt/tools".into(), "/home/me/.asdf/shims".into()]);
|
||||
assert!(at("/home/me/.npm-global/bin") < at("/home/me/.pyenv/shims"));
|
||||
assert!(at("/home/me/.local/share/mise/shims") < at("/usr/local/bin"));
|
||||
assert!(dirs.iter().all(|d| d.is_absolute()));
|
||||
let unique: HashSet<&PathBuf> = dirs.iter().collect();
|
||||
assert_eq!(unique.len(), dirs.len());
|
||||
// A `:` can't be in a `PATH` entry: those below such a home are left out.
|
||||
let dirs = search_dirs(Some(OsStr::new("/usr/bin")), None, Some(Path::new("/home/a:b")), &[]);
|
||||
assert!(dirs.contains(&PathBuf::from("/usr/bin")) && !dirs.iter().any(|d| d.starts_with("/home")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nvm_versions_newest_first() {
|
||||
let dir = std::env::temp_dir().join(format!("openidea-nvm-{}", std::process::id()));
|
||||
for v in ["v9.11.2", "v20.9.0", "v22.1.0", "v20.10.0"] {
|
||||
std::fs::create_dir_all(dir.join(v).join("bin")).unwrap();
|
||||
}
|
||||
let bins = nvm_bins(&dir);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
let names: Vec<_> = bins.iter().map(|b| b.parent().unwrap().file_name().unwrap().to_owned()).collect();
|
||||
assert_eq!(names, ["v22.1.0", "v20.10.0", "v20.9.0", "v9.11.2"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
//! Version managers that keep one install per tool version (mise, asdf): where their
|
||||
//! installs and shims live. SDK detection lists the installs; child processes get the
|
||||
//! shims on `PATH` when the manager's shell hook didn't run (an app started from the Dock,
|
||||
//! `mise activate` only in an interactive rc file).
|
||||
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const MISE: &str = "mise";
|
||||
pub const ASDF: &str = "asdf";
|
||||
|
||||
/// A toolchain the version managers install.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Tool {
|
||||
Java,
|
||||
Node,
|
||||
Python,
|
||||
Go,
|
||||
Maven,
|
||||
Gradle,
|
||||
}
|
||||
|
||||
impl Tool {
|
||||
/// The tool's names in mise and asdf plugins (`nodejs`, `golang` are asdf's).
|
||||
pub fn names(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Tool::Java => &["java"],
|
||||
Tool::Node => &["node", "nodejs"],
|
||||
Tool::Python => &["python"],
|
||||
Tool::Go => &["go", "golang"],
|
||||
Tool::Maven => &["maven"],
|
||||
Tool::Gradle => &["gradle"],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One version manager's data directory (`installs/`, `shims/`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Manager {
|
||||
pub name: &'static str,
|
||||
pub dir: PathBuf,
|
||||
}
|
||||
|
||||
impl Manager {
|
||||
pub fn shims(&self) -> PathBuf {
|
||||
self.dir.join("shims")
|
||||
}
|
||||
|
||||
/// `installs/<tool>/<version>` directories of `tool`, sorted. The alias links mise
|
||||
/// adds next to an install (`21 -> ./21.0.2`, `latest`) are left out; a link to an
|
||||
/// install elsewhere (`mise link`) is kept.
|
||||
pub fn installs(&self, tool: Tool) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
for name in tool.names() {
|
||||
let Ok(entries) = std::fs::read_dir(self.dir.join("installs").join(name)) else { continue };
|
||||
for e in entries.flatten() {
|
||||
let path = e.path();
|
||||
let alias = e.file_type().is_ok_and(|t| t.is_symlink())
|
||||
&& std::fs::read_link(&path).is_ok_and(|t| t.is_relative() && t.components().count() <= 2);
|
||||
if !alias && path.is_dir() {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// The install of `tool` named `version` exactly (alias links included).
|
||||
pub fn install_named(&self, tool: Tool, version: &str) -> Option<PathBuf> {
|
||||
if version.is_empty() || version.contains(['/', '\\']) || version.starts_with('.') {
|
||||
return None;
|
||||
}
|
||||
tool.names().iter().map(|n| self.dir.join("installs").join(n).join(version)).find(|p| p.is_dir())
|
||||
}
|
||||
}
|
||||
|
||||
/// mise's and asdf's data directories that exist, as this process's environment (and the
|
||||
/// login shell's) set them.
|
||||
pub fn managers() -> Vec<Manager> {
|
||||
let lookup = |k: &str| {
|
||||
crate::process::host_var_os(k)
|
||||
.or_else(|| crate::process::login_env()?.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone()))
|
||||
};
|
||||
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from);
|
||||
managers_with(&lookup, home.as_deref()).into_iter().filter(|m| m.dir.is_dir()).collect()
|
||||
}
|
||||
|
||||
/// mise: `MISE_DATA_DIR`, else `$XDG_DATA_HOME/mise`, else `~/.local/share/mise`
|
||||
/// (`%LOCALAPPDATA%\mise` on Windows). asdf: `ASDF_DATA_DIR`, else `~/.asdf`.
|
||||
pub fn managers_with(env: &dyn Fn(&str) -> Option<OsString>, home: Option<&Path>) -> Vec<Manager> {
|
||||
let var = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from);
|
||||
let mise = var("MISE_DATA_DIR")
|
||||
.or_else(|| var("XDG_DATA_HOME").map(|d| d.join("mise")))
|
||||
.or_else(|| if cfg!(windows) { var("LOCALAPPDATA").map(|d| d.join("mise")) } else { None })
|
||||
.or_else(|| home.map(|h| h.join(".local/share/mise")));
|
||||
let asdf = var("ASDF_DATA_DIR").or_else(|| home.map(|h| h.join(".asdf")));
|
||||
let mut out = Vec::new();
|
||||
out.extend(mise.map(|dir| Manager { name: MISE, dir }));
|
||||
out.extend(asdf.map(|dir| Manager { name: ASDF, dir }));
|
||||
out
|
||||
}
|
||||
|
||||
/// Every install of `tool` with the manager it came from, mise's first.
|
||||
pub fn installs(tool: Tool) -> Vec<(PathBuf, &'static str)> {
|
||||
managers().iter().flat_map(|m| m.installs(tool).into_iter().map(|p| (p, m.name))).collect()
|
||||
}
|
||||
|
||||
/// The manager whose installs `path` lies in.
|
||||
pub fn manager_of(path: &Path) -> Option<&'static str> {
|
||||
manager_in(&managers(), path)
|
||||
}
|
||||
|
||||
pub fn manager_in(managers: &[Manager], path: &Path) -> Option<&'static str> {
|
||||
managers.iter().find_map(|m| {
|
||||
let installs = m.dir.join("installs");
|
||||
let real = dunce::canonicalize(&installs).ok();
|
||||
(path.starts_with(&installs) || real.is_some_and(|r| path.starts_with(r))).then_some(m.name)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `path` is a version manager's shim (it picks the version by the working directory).
|
||||
pub fn is_shim(path: &Path) -> bool {
|
||||
path.parent().is_some_and(is_shims_dir)
|
||||
}
|
||||
|
||||
/// Whether `dir` is a version manager's `shims` folder.
|
||||
pub fn is_shims_dir(dir: &Path) -> bool {
|
||||
managers().iter().any(|m| m.shims() == dir)
|
||||
}
|
||||
|
||||
/// `path` (a `PATH` value) with the shims of a manager it doesn't reach yet: mise's in
|
||||
/// front (a mise shim runs the next tool on `PATH` when no version is set), asdf's at the
|
||||
/// end (an asdf shim fails then). A `PATH` that has a manager's shims or installs already
|
||||
/// (its shell hook ran) is left as it is for that manager.
|
||||
pub fn path_with_shims(managers: &[Manager], path: &OsStr) -> OsString {
|
||||
let mut dirs: Vec<PathBuf> = if path.is_empty() { Vec::new() } else { std::env::split_paths(path).collect() };
|
||||
let before = dirs.len();
|
||||
for m in managers {
|
||||
let shims = m.shims();
|
||||
let installs = m.dir.join("installs");
|
||||
if !shims.is_dir() || dirs.iter().any(|d| d == &shims || d.starts_with(&installs)) {
|
||||
continue;
|
||||
}
|
||||
if m.name == MISE {
|
||||
dirs.insert(0, shims);
|
||||
} else {
|
||||
dirs.push(shims);
|
||||
}
|
||||
}
|
||||
if dirs.len() == before {
|
||||
return path.to_owned();
|
||||
}
|
||||
std::env::join_paths(dirs).unwrap_or_else(|_| path.to_owned())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
fn mkdir(p: &Path) {
|
||||
std::fs::create_dir_all(p).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_dirs_follow_the_environment() {
|
||||
let home = Path::new("/home/me");
|
||||
let none = |_: &str| None;
|
||||
let dirs: Vec<_> = managers_with(&none, Some(home)).into_iter().map(|m| (m.name, m.dir)).collect();
|
||||
if !cfg!(windows) {
|
||||
assert_eq!(dirs[0], (MISE, home.join(".local/share/mise")));
|
||||
}
|
||||
assert_eq!(dirs[1], (ASDF, home.join(".asdf")));
|
||||
|
||||
let xdg = |k: &str| (k == "XDG_DATA_HOME").then(|| OsString::from("/xdg"));
|
||||
assert_eq!(managers_with(&xdg, Some(home))[0].dir, Path::new("/xdg/mise"));
|
||||
|
||||
let custom = |k: &str| match k {
|
||||
"MISE_DATA_DIR" => Some(OsString::from("/opt/mise")),
|
||||
"XDG_DATA_HOME" => Some(OsString::from("/xdg")),
|
||||
"ASDF_DATA_DIR" => Some(OsString::from("/opt/asdf")),
|
||||
_ => None,
|
||||
};
|
||||
let dirs: Vec<_> = managers_with(&custom, Some(home)).into_iter().map(|m| m.dir).collect();
|
||||
assert_eq!(dirs, [PathBuf::from("/opt/mise"), PathBuf::from("/opt/asdf")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn installs_skip_alias_links() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mise = Manager { name: MISE, dir: tmp.path().join("mise") };
|
||||
let node = mise.dir.join("installs/node");
|
||||
mkdir(&node.join("20.11.0"));
|
||||
mkdir(&node.join("22.1.0"));
|
||||
std::os::unix::fs::symlink("./22.1.0", node.join("22")).unwrap();
|
||||
std::os::unix::fs::symlink("./22.1.0", node.join("latest")).unwrap();
|
||||
let elsewhere = tmp.path().join("opt-node");
|
||||
mkdir(&elsewhere);
|
||||
std::os::unix::fs::symlink(&elsewhere, node.join("linked")).unwrap();
|
||||
std::fs::write(node.join(".mise.backend.toml"), "").unwrap();
|
||||
|
||||
let names: Vec<_> =
|
||||
mise.installs(Tool::Node).iter().map(|p| p.file_name().unwrap().to_string_lossy().into_owned()).collect();
|
||||
assert_eq!(names, ["20.11.0", "22.1.0", "linked"]);
|
||||
assert_eq!(mise.install_named(Tool::Node, "22"), Some(node.join("22")));
|
||||
assert_eq!(mise.install_named(Tool::Node, "18"), None);
|
||||
assert_eq!(mise.install_named(Tool::Node, "../node"), None);
|
||||
|
||||
// asdf's plugin names.
|
||||
let asdf = Manager { name: ASDF, dir: tmp.path().join("asdf") };
|
||||
mkdir(&asdf.dir.join("installs/golang/1.22.1"));
|
||||
assert_eq!(asdf.installs(Tool::Go), [asdf.dir.join("installs/golang/1.22.1")]);
|
||||
assert_eq!(manager_in(&[mise.clone(), asdf.clone()], &node.join("20.11.0/bin/node")), Some(MISE));
|
||||
assert_eq!(manager_in(&[mise, asdf], tmp.path()), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn shims_join_a_path_the_hook_did_not_set() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mise = Manager { name: MISE, dir: tmp.path().join("mise") };
|
||||
let asdf = Manager { name: ASDF, dir: tmp.path().join("asdf") };
|
||||
let managers = [mise.clone(), asdf.clone()];
|
||||
let path = OsString::from("/usr/bin:/bin");
|
||||
assert_eq!(path_with_shims(&managers, &path), path, "no shims installed");
|
||||
|
||||
mkdir(&mise.shims());
|
||||
mkdir(&asdf.shims());
|
||||
let got = path_with_shims(&managers, &path);
|
||||
let want = format!("{}:/usr/bin:/bin:{}", mise.shims().display(), asdf.shims().display());
|
||||
assert_eq!(got, OsString::from(want));
|
||||
assert_eq!(path_with_shims(&managers, &got), got, "applied once");
|
||||
|
||||
// `mise activate` put an install on PATH: mise is active, only asdf's shims join.
|
||||
let active = format!("{}:/usr/bin", mise.dir.join("installs/node/22.1.0/bin").display());
|
||||
let got = path_with_shims(&managers, OsStr::new(&active));
|
||||
assert_eq!(got, OsString::from(format!("{active}:{}", asdf.shims().display())));
|
||||
}
|
||||
}
|
||||
@@ -213,8 +213,12 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult<CoverageSuite> {
|
||||
.output()
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot run {program}: {e}")))?;
|
||||
if !out.status.success() {
|
||||
let text = String::from_utf8_lossy(&out.stderr).trim().to_owned();
|
||||
let text = if text.is_empty() { String::from_utf8_lossy(&out.stdout).trim().to_owned() } else { text };
|
||||
let text = ide_core::output_encoding::decode_tool_output(&out.stderr).trim().to_owned();
|
||||
let text = if text.is_empty() {
|
||||
ide_core::output_encoding::decode_tool_output(&out.stdout).trim().to_owned()
|
||||
} else {
|
||||
text
|
||||
};
|
||||
return Err(IdeError::not_found(format!("exporting the coverage data failed: {text}")));
|
||||
}
|
||||
let text = read_report(lcov)?;
|
||||
|
||||
@@ -70,8 +70,10 @@ pub async fn build(
|
||||
let on_output = std::sync::Arc::new(on_output);
|
||||
let err_out = on_output.clone();
|
||||
let err_task = tokio::spawn(async move {
|
||||
let mut lines = BufReader::new(stderr).lines();
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
let mut lines = BufReader::new(stderr).split(b'\n');
|
||||
while let Ok(Some(line)) = lines.next_segment().await {
|
||||
let line = ide_core::output_encoding::decode_tool_output(&line);
|
||||
let line = line.trim_end_matches('\r');
|
||||
err_out(format!("{line}\n"));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -893,6 +893,7 @@ fn godot_registry(port: u16, command: &str, args: &[&str]) -> Arc<LanguageRegist
|
||||
block_comment: None,
|
||||
indent: None,
|
||||
ui_mode: None,
|
||||
framework_ui_modes: Vec::new(),
|
||||
tree_sitter: None,
|
||||
language_servers: vec![],
|
||||
debugger: Some(ide_language::DebuggerConfig {
|
||||
|
||||
@@ -16,6 +16,9 @@ tracing.workspace = true
|
||||
parking_lot.workspace = true
|
||||
futures.workspace = true
|
||||
sqlx.workspace = true
|
||||
tiberius.workspace = true
|
||||
bb8.workspace = true
|
||||
tokio-util = { workspace = true, features = ["compat"] }
|
||||
dirs.workspace = true
|
||||
ide-ssh.workspace = true
|
||||
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
//! whatever its type.
|
||||
|
||||
use crate::source::{DataSource, DbDriver, DbSslMode};
|
||||
use bb8::ManageConnection;
|
||||
use bb8::Pool as Bb8Pool;
|
||||
use futures::StreamExt;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -44,10 +47,65 @@ pub struct QueryResult {
|
||||
pub execution_ms: f64,
|
||||
}
|
||||
|
||||
// Keep an empty slot when a connection is discarded after cancellation or rollback failure.
|
||||
pub struct MssqlConnectionManager(tiberius::Config);
|
||||
|
||||
type MssqlClient = tiberius::Client<tokio_util::compat::Compat<tokio::net::TcpStream>>;
|
||||
|
||||
pub struct MssqlConnection(Option<MssqlClient>);
|
||||
|
||||
impl std::ops::Deref for MssqlConnection {
|
||||
type Target = MssqlClient;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.0.as_ref().expect("live SQL Server connection")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::DerefMut for MssqlConnection {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
self.0.as_mut().expect("live SQL Server connection")
|
||||
}
|
||||
}
|
||||
|
||||
impl ManageConnection for MssqlConnectionManager {
|
||||
type Connection = MssqlConnection;
|
||||
type Error = tiberius::error::Error;
|
||||
|
||||
async fn connect(&self) -> Result<Self::Connection, Self::Error> {
|
||||
use tokio_util::compat::TokioAsyncWriteCompatExt;
|
||||
|
||||
let tcp = tokio::net::TcpStream::connect(self.0.get_addr()).await?;
|
||||
tcp.set_nodelay(true)?;
|
||||
let client = match MssqlClient::connect(self.0.clone(), tcp.compat_write()).await {
|
||||
// Preserve the single redirect supported by the previous pool adapter.
|
||||
Err(tiberius::error::Error::Routing { host, port }) => {
|
||||
let mut config = self.0.clone();
|
||||
config.host(host);
|
||||
config.port(port);
|
||||
let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;
|
||||
tcp.set_nodelay(true)?;
|
||||
MssqlClient::connect(config, tcp.compat_write()).await?
|
||||
}
|
||||
result => result?,
|
||||
};
|
||||
Ok(MssqlConnection(Some(client)))
|
||||
}
|
||||
|
||||
async fn is_valid(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> {
|
||||
conn.simple_query("SELECT 1").await?.into_results().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn has_broken(&self, conn: &mut Self::Connection) -> bool {
|
||||
conn.0.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
pub enum Pool {
|
||||
Sqlite(SqlitePool),
|
||||
Postgres(PgPool),
|
||||
Mysql(MySqlPool),
|
||||
SqlServer(Bb8Pool<MssqlConnectionManager>),
|
||||
}
|
||||
|
||||
/// Runs `$body` with `$p` bound to the concrete pool of each driver.
|
||||
@@ -57,6 +115,7 @@ macro_rules! with_pool {
|
||||
Pool::Sqlite($p) => $body,
|
||||
Pool::Postgres($p) => $body,
|
||||
Pool::Mysql($p) => $body,
|
||||
Pool::SqlServer(_) => unreachable!(),
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -79,6 +138,129 @@ pub(crate) fn db_err(e: sqlx::Error) -> IdeError {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mssql_err(e: tiberius::error::Error) -> IdeError {
|
||||
match &e {
|
||||
tiberius::error::Error::Server(d) => {
|
||||
let code = d.code();
|
||||
// Wrong login: SQL Server 18456.
|
||||
let auth = matches!(code, 18452 | 18456 | 18470);
|
||||
IdeError::new(
|
||||
if auth { ErrorKind::PermissionDenied } else { ErrorKind::InvalidInput },
|
||||
format!("[{code}] {}", d.message()),
|
||||
)
|
||||
}
|
||||
tiberius::error::Error::Io { .. } | tiberius::error::Error::Tls(_) => {
|
||||
IdeError::new(ErrorKind::Io, e.to_string())
|
||||
}
|
||||
_ => IdeError::new(ErrorKind::Protocol, e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn mssql_pool_err(e: bb8::RunError<tiberius::error::Error>) -> IdeError {
|
||||
match e {
|
||||
bb8::RunError::User(e) => mssql_err(e),
|
||||
bb8::RunError::TimedOut => IdeError::new(ErrorKind::Io, "timed out connecting to the database"),
|
||||
}
|
||||
}
|
||||
|
||||
const DAYS_1900_01_01: i64 = 693_595;
|
||||
|
||||
/// Formats a proleptic Gregorian date given days since `0001-01-01`.
|
||||
fn format_date(days: i64) -> String {
|
||||
let z = days + 306;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z.rem_euclid(146_097);
|
||||
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
|
||||
let y = yoe + era * 400;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let year = if m <= 2 { y + 1 } else { y };
|
||||
format!("{year:04}-{m:02}-{d:02}")
|
||||
}
|
||||
|
||||
fn format_hms(secs: u64, frac: u64, scale: u8) -> String {
|
||||
let (h, m, s) = (secs / 3600, (secs / 60) % 60, secs % 60);
|
||||
if scale == 0 || frac == 0 {
|
||||
format!("{h:02}:{m:02}:{s:02}")
|
||||
} else {
|
||||
let frac = format!("{frac:0width$}", width = usize::from(scale));
|
||||
format!("{h:02}:{m:02}:{s:02}.{}", frac.trim_end_matches('0'))
|
||||
}
|
||||
}
|
||||
|
||||
fn format_time(t: tiberius::time::Time) -> String {
|
||||
let scale = t.scale().min(7);
|
||||
let div = 10u64.pow(u32::from(scale));
|
||||
format_hms(t.increments() / div, t.increments() % div, scale)
|
||||
}
|
||||
|
||||
fn format_numeric(n: tiberius::numeric::Numeric) -> String {
|
||||
let scale = u32::from(n.scale());
|
||||
if scale == 0 {
|
||||
return n.value().to_string();
|
||||
}
|
||||
let sign = if n.value() < 0 { "-" } else { "" };
|
||||
let abs = n.value().unsigned_abs();
|
||||
let div = 10u128.pow(scale);
|
||||
format!("{sign}{}.{:0width$}", abs / div, abs % div, width = scale as usize)
|
||||
}
|
||||
|
||||
fn tiberius_cell(cell: &tiberius::ColumnData<'_>, ty: tiberius::ColumnType) -> Option<String> {
|
||||
use tiberius::ColumnData as C;
|
||||
match cell {
|
||||
C::U8(v) => v.map(|v| v.to_string()),
|
||||
C::I16(v) => v.map(|v| v.to_string()),
|
||||
C::I32(v) => v.map(|v| v.to_string()),
|
||||
C::I64(v) => v.map(|v| v.to_string()),
|
||||
C::F32(v) => v.map(|v| v.to_string()),
|
||||
C::F64(v) if matches!(ty, tiberius::ColumnType::Money | tiberius::ColumnType::Money4) => {
|
||||
// Beyond ~9e11, money precision is limited by the driver's f64 decoding.
|
||||
v.map(|v| format!("{:.4}", v))
|
||||
}
|
||||
C::F64(v) => v.map(|v| v.to_string()),
|
||||
C::Bit(v) => v.map(|v| v.to_string()),
|
||||
C::String(v) => v.as_deref().map(str::to_owned),
|
||||
C::Guid(v) => v.map(|v| v.to_string()),
|
||||
C::Binary(v) => v.as_deref().map(hex),
|
||||
C::Numeric(v) => v.map(format_numeric),
|
||||
C::Xml(v) => v.as_deref().map(|x| x.as_ref().to_owned()),
|
||||
C::Date(v) => v.map(|d| format_date(i64::from(d.days()))),
|
||||
C::Time(v) => v.map(format_time),
|
||||
C::DateTime(v) => v.map(|dt| {
|
||||
let ms = (u64::from(dt.seconds_fragments()) * 1000 + 150) / 300;
|
||||
format!("{} {}", format_date(DAYS_1900_01_01 + i64::from(dt.days())), format_hms(ms / 1000, ms % 1000, 3))
|
||||
}),
|
||||
C::SmallDateTime(v) => v.map(|dt| {
|
||||
let secs = u64::from(dt.seconds_fragments()) * 60;
|
||||
format!("{} {}", format_date(DAYS_1900_01_01 + i64::from(dt.days())), format_hms(secs, 0, 0))
|
||||
}),
|
||||
C::DateTime2(v) => {
|
||||
v.map(|dt| format!("{} {}", format_date(i64::from(dt.date().days())), format_time(dt.time())))
|
||||
}
|
||||
C::DateTimeOffset(v) => v.map(|dto| {
|
||||
let dt = dto.datetime2();
|
||||
let t = dt.time();
|
||||
let scale = t.scale().min(7);
|
||||
let div = 10u64.pow(u32::from(scale));
|
||||
let utc_secs = i64::from(dt.date().days()) * 86_400 + (t.increments() / div) as i64;
|
||||
let local_secs = utc_secs + i64::from(dto.offset()) * 60;
|
||||
let days = local_secs.div_euclid(86_400);
|
||||
let secs = local_secs.rem_euclid(86_400) as u64;
|
||||
let sign = if dto.offset() < 0 { '-' } else { '+' };
|
||||
let off = dto.offset().unsigned_abs();
|
||||
format!(
|
||||
"{} {}{sign}{:02}:{:02}",
|
||||
format_date(days),
|
||||
format_hms(secs, t.increments() % div, scale),
|
||||
off / 60,
|
||||
off % 60
|
||||
)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
let mut s = String::with_capacity(2 + bytes.len() * 2);
|
||||
s.push_str("0x");
|
||||
@@ -88,10 +270,46 @@ fn hex(bytes: &[u8]) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// How [`cell`] shows a value whose bytes are not text.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Cells {
|
||||
/// Result grids: binary values as `0x…` hex.
|
||||
Display,
|
||||
/// Catalog queries: names and definitions, so bytes are read as UTF-8 whatever the
|
||||
/// column's type (MySQL flags `utf8mb3_bin` catalog columns BINARY, and sends every
|
||||
/// column as binary under `character_set_results = binary`).
|
||||
Text,
|
||||
}
|
||||
|
||||
/// Whether a value of type `ty` is binary data (see [`binary_type`]).
|
||||
fn is_binary<DB: sqlx::Database>(ty: &DB::TypeInfo) -> bool
|
||||
where
|
||||
String: sqlx::Type<DB>,
|
||||
{
|
||||
binary_type(ty.name(), <String as sqlx::Type<DB>>::compatible(ty))
|
||||
}
|
||||
|
||||
/// A BLOB / BINARY type that the driver does not read as text: MySQL flags text in a
|
||||
/// binary collation (`utf8mb4_bin`) BINARY too, and only the `binary` collation is bytes.
|
||||
fn binary_type(name: &str, text: bool) -> bool {
|
||||
let name = name.to_ascii_uppercase();
|
||||
(name.contains("BLOB") || name.contains("BINARY")) && !text
|
||||
}
|
||||
|
||||
/// Bytes as text: UTF-8, else hex (grids) or with invalid sequences replaced (catalog names).
|
||||
fn bytes_text(bytes: Vec<u8>, mode: Cells) -> String {
|
||||
match (String::from_utf8(bytes), mode) {
|
||||
(Ok(s), _) => s,
|
||||
(Err(e), Cells::Display) => hex(e.as_bytes()),
|
||||
(Err(e), Cells::Text) => String::from_utf8_lossy(e.as_bytes()).into_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of column `i` of `row`.
|
||||
fn cell<R: Row>(row: &R, i: usize) -> Option<String>
|
||||
fn cell<R: Row>(row: &R, i: usize, mode: Cells) -> Option<String>
|
||||
where
|
||||
usize: ColumnIndex<R>,
|
||||
String: sqlx::Type<R::Database>,
|
||||
for<'r> String: Decode<'r, R::Database>,
|
||||
for<'r> Vec<u8>: Decode<'r, R::Database>,
|
||||
{
|
||||
@@ -99,18 +317,14 @@ where
|
||||
if raw.is_null() {
|
||||
return None;
|
||||
}
|
||||
let ty = raw.type_info().name().to_ascii_uppercase();
|
||||
if ty.contains("BLOB") || ty.contains("BINARY") {
|
||||
let raw = row.try_get_raw(i).ok()?;
|
||||
if mode == Cells::Display && is_binary::<R::Database>(&raw.type_info()) {
|
||||
return <Vec<u8> as Decode<R::Database>>::decode(raw).ok().map(|b| hex(&b));
|
||||
}
|
||||
match <String as Decode<R::Database>>::decode(raw) {
|
||||
Ok(s) => Some(s),
|
||||
Err(_) => {
|
||||
let raw = row.try_get_raw(i).ok()?;
|
||||
<Vec<u8> as Decode<R::Database>>::decode(raw)
|
||||
.ok()
|
||||
.map(|b| String::from_utf8(b).unwrap_or_else(|e| hex(e.as_bytes())))
|
||||
<Vec<u8> as Decode<R::Database>>::decode(raw).ok().map(|b| bytes_text(b, mode))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -122,9 +336,10 @@ fn result_columns<R: Row>(row: &R) -> Vec<ResultColumn> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Streams the results of `$sql` on executor `$exec`, keeping at most `$max` rows.
|
||||
/// Streams the results of `$sql` on executor `$exec`, keeping at most `$max` rows
|
||||
/// with their cells read as `$mode`.
|
||||
macro_rules! fetch {
|
||||
($exec:expr, $sql:expr, $max:expr) => {{
|
||||
($exec:expr, $sql:expr, $max:expr, $mode:expr) => {{
|
||||
use futures::StreamExt;
|
||||
let mut stream = sqlx::raw_sql(sqlx::AssertSqlSafe($sql.to_owned())).fetch_many($exec);
|
||||
let mut columns: Vec<ResultColumn> = Vec::new();
|
||||
@@ -145,7 +360,7 @@ macro_rules! fetch {
|
||||
has_more = true;
|
||||
break;
|
||||
}
|
||||
rows.push((0..row.len()).map(|i| cell(&row, i)).collect());
|
||||
rows.push((0..row.len()).map(|i| cell(&row, i, $mode)).collect());
|
||||
}
|
||||
Err(e) => {
|
||||
failure = Some(db_err(e));
|
||||
@@ -164,10 +379,41 @@ macro_rules! fetch {
|
||||
/// Columns, rows, rows affected, more rows beyond the limit, time of the first answer.
|
||||
type Fetched = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, Option<u64>, bool, Option<Instant>);
|
||||
|
||||
async fn mssql_command(conn: &mut MssqlClient, sql: &str) -> IdeResult<()> {
|
||||
// Transaction control must be a batch: sp_executesql rejects a changed transaction count.
|
||||
conn.simple_query(sql).await.map_err(mssql_err)?.into_results().await.map_err(mssql_err)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn mssql_fetch(conn: &mut MssqlClient, sql: &str, max: usize) -> IdeResult<Fetched> {
|
||||
let mut stream = conn.simple_query(sql).await.map_err(mssql_err)?;
|
||||
let first = Some(Instant::now());
|
||||
let columns = stream
|
||||
.columns()
|
||||
.await
|
||||
.map_err(mssql_err)?
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|col| ResultColumn { name: col.name().to_owned(), type_name: format!("{:?}", col.column_type()) })
|
||||
.collect();
|
||||
let mut rows = Vec::new();
|
||||
let mut has_more = false;
|
||||
while let Some(item) = stream.next().await {
|
||||
if let tiberius::QueryItem::Row(row) = item.map_err(mssql_err)? {
|
||||
if rows.len() >= max {
|
||||
has_more = true;
|
||||
break;
|
||||
}
|
||||
rows.push(row.cells().map(|(col, cell)| tiberius_cell(cell, col.column_type())).collect());
|
||||
}
|
||||
}
|
||||
Ok((columns, rows, None, has_more, first))
|
||||
}
|
||||
|
||||
/// The server-side id of a connection (to cancel its statement from another one).
|
||||
macro_rules! backend_id {
|
||||
($conn:expr, $sql:expr) => {{
|
||||
let fetched: IdeResult<Fetched> = fetch!($conn, $sql, 1);
|
||||
let fetched: IdeResult<Fetched> = fetch!($conn, $sql, 1, Cells::Text);
|
||||
fetched
|
||||
.ok()
|
||||
.and_then(|f| f.1.into_iter().next())
|
||||
@@ -280,6 +526,7 @@ impl Pool {
|
||||
Pool::Sqlite(_) => DbDriver::Sqlite,
|
||||
Pool::Postgres(_) => DbDriver::Postgres,
|
||||
Pool::Mysql(_) => DbDriver::Mysql,
|
||||
Pool::SqlServer(_) => DbDriver::SqlServer,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -420,20 +667,60 @@ impl Pool {
|
||||
.map_err(db_err)?;
|
||||
Ok(Pool::Mysql(pool))
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
use tiberius::Config;
|
||||
let mut config = Config::new();
|
||||
config.host(&source.host);
|
||||
config.port(source.port.unwrap_or(1433));
|
||||
if !source.user.is_empty() {
|
||||
config.authentication(tiberius::AuthMethod::sql_server(
|
||||
source.user.clone(),
|
||||
password.unwrap_or_default().to_owned(),
|
||||
));
|
||||
}
|
||||
if !source.database.is_empty() {
|
||||
config.database(&source.database);
|
||||
}
|
||||
if matches!(source.ssl, DbSslMode::Disable | DbSslMode::Prefer) {
|
||||
config.trust_cert();
|
||||
}
|
||||
let manager = MssqlConnectionManager(config);
|
||||
let pool = bb8::Pool::builder()
|
||||
.max_size(MAX)
|
||||
.connection_timeout(timeout)
|
||||
.build(manager)
|
||||
.await
|
||||
.map_err(mssql_err)?;
|
||||
let mut conn = pool.get_owned().await.map_err(mssql_pool_err)?;
|
||||
conn.query("SELECT 1", &[]).await.map_err(mssql_err)?.into_results().await.map_err(mssql_err)?;
|
||||
Ok(Pool::SqlServer(pool))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn close(&self) {
|
||||
with_pool!(self, p => p.close().await)
|
||||
match self {
|
||||
Pool::SqlServer(_) => {}
|
||||
_ => with_pool!(self, p => p.close().await),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_closed(&self) -> bool {
|
||||
with_pool!(self, p => p.is_closed())
|
||||
match self {
|
||||
Pool::SqlServer(_) => false,
|
||||
_ => with_pool!(self, p => p.is_closed()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `sql` (no row limit beyond `max`), for introspection.
|
||||
/// Runs `sql` (no row limit beyond `max`), for introspection: cells are text (see [`Cells::Text`]).
|
||||
pub async fn rows(&self, sql: &str, max: usize) -> IdeResult<Vec<Vec<Option<String>>>> {
|
||||
let fetched: IdeResult<Fetched> = with_pool!(self, p => fetch!(p, sql, max));
|
||||
let fetched: IdeResult<Fetched> = match self {
|
||||
Pool::SqlServer(p) => {
|
||||
let mut conn = p.get_owned().await.map_err(mssql_pool_err)?;
|
||||
mssql_fetch(&mut conn, sql, max).await
|
||||
}
|
||||
_ => with_pool!(self, p => fetch!(p, sql, max, Cells::Text)),
|
||||
};
|
||||
Ok(fetched?.1)
|
||||
}
|
||||
|
||||
@@ -452,21 +739,47 @@ impl Pool {
|
||||
/// Runs `statements` in one transaction; each must change `expect_one`
|
||||
/// row when flagged (table editor submits).
|
||||
pub async fn transaction(&self, statements: &[(String, bool)]) -> IdeResult<u64> {
|
||||
with_pool!(self, p => {
|
||||
let mut tx = p.begin().await.map_err(db_err)?;
|
||||
let mut total = 0;
|
||||
for (sql, expect_one) in statements {
|
||||
let done = sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut *tx).await.map_err(db_err)?;
|
||||
let n = done.rows_affected();
|
||||
// MySQL reports 0 for an UPDATE that leaves the row unchanged.
|
||||
if *expect_one && (n > 1 || (n == 0 && !matches!(self, Pool::Mysql(_)))) {
|
||||
return Err(IdeError::invalid(format!("{sql}: expected to change 1 row, changed {n}; nothing was saved")));
|
||||
match self {
|
||||
Pool::SqlServer(p) => {
|
||||
let mut conn = p.get_owned().await.map_err(mssql_pool_err)?;
|
||||
let result = async {
|
||||
mssql_command(&mut conn, "BEGIN TRAN").await?;
|
||||
let mut total = 0;
|
||||
for (sql, expect_one) in statements {
|
||||
let n = conn.execute(sql, &[]).await.map_err(mssql_err)?.total();
|
||||
if *expect_one && n != 1 {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{sql}: expected to change 1 row, changed {n}; nothing was saved"
|
||||
)));
|
||||
}
|
||||
total += n;
|
||||
}
|
||||
mssql_command(&mut conn, "COMMIT TRAN").await?;
|
||||
Ok(total)
|
||||
}
|
||||
total += n;
|
||||
.await;
|
||||
if result.is_err() && mssql_command(&mut conn, "IF @@TRANCOUNT > 0 ROLLBACK TRAN").await.is_err() {
|
||||
// A failed rollback must never return an open transaction to the pool.
|
||||
conn.0.take();
|
||||
}
|
||||
result
|
||||
}
|
||||
tx.commit().await.map_err(db_err)?;
|
||||
Ok(total)
|
||||
})
|
||||
_ => with_pool!(self, p => {
|
||||
let mut tx = p.begin().await.map_err(db_err)?;
|
||||
let mut total = 0;
|
||||
for (sql, expect_one) in statements {
|
||||
let done = sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut *tx).await.map_err(db_err)?;
|
||||
let n = done.rows_affected();
|
||||
// MySQL reports 0 for an UPDATE that leaves the row unchanged.
|
||||
if *expect_one && (n > 1 || (n == 0 && !matches!(self, Pool::Mysql(_)))) {
|
||||
return Err(IdeError::invalid(format!("{sql}: expected to change 1 row, changed {n}; nothing was saved")));
|
||||
}
|
||||
total += n;
|
||||
}
|
||||
tx.commit().await.map_err(db_err)?;
|
||||
Ok(total)
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -476,6 +789,7 @@ pub enum Held {
|
||||
Sqlite(PoolConnection<Sqlite>),
|
||||
Postgres(PoolConnection<Postgres>),
|
||||
Mysql(PoolConnection<MySql>),
|
||||
SqlServer(Box<bb8::PooledConnection<'static, MssqlConnectionManager>>),
|
||||
}
|
||||
|
||||
impl Held {
|
||||
@@ -484,18 +798,25 @@ impl Held {
|
||||
Pool::Sqlite(p) => Held::Sqlite(p.acquire().await.map_err(db_err)?),
|
||||
Pool::Postgres(p) => Held::Postgres(p.acquire().await.map_err(db_err)?),
|
||||
Pool::Mysql(p) => Held::Mysql(p.acquire().await.map_err(db_err)?),
|
||||
Pool::SqlServer(p) => Held::SqlServer(Box::new(p.get_owned().await.map_err(mssql_pool_err)?)),
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs a statement without results (`BEGIN`, `COMMIT`, `ROLLBACK`).
|
||||
pub async fn command(&mut self, sql: &str) -> IdeResult<()> {
|
||||
let sql = sqlx::AssertSqlSafe(sql.to_owned());
|
||||
match self {
|
||||
Held::Sqlite(c) => sqlx::raw_sql(sql).execute(&mut **c).await.map(drop),
|
||||
Held::Postgres(c) => sqlx::raw_sql(sql).execute(&mut **c).await.map(drop),
|
||||
Held::Mysql(c) => sqlx::raw_sql(sql).execute(&mut **c).await.map(drop),
|
||||
Held::SqlServer(c) => mssql_command(c, sql).await,
|
||||
other => {
|
||||
let sql = sqlx::AssertSqlSafe(sql.to_owned());
|
||||
match other {
|
||||
Held::Sqlite(c) => sqlx::raw_sql(sql).execute(&mut **c).await.map(drop),
|
||||
Held::Postgres(c) => sqlx::raw_sql(sql).execute(&mut **c).await.map(drop),
|
||||
Held::Mysql(c) => sqlx::raw_sql(sql).execute(&mut **c).await.map(drop),
|
||||
Held::SqlServer(_) => unreachable!(),
|
||||
}
|
||||
.map_err(db_err)
|
||||
}
|
||||
}
|
||||
.map_err(db_err)
|
||||
}
|
||||
|
||||
/// Closes the connection instead of returning it to the pool (its statement was
|
||||
@@ -509,6 +830,9 @@ impl Held {
|
||||
Held::Mysql(c) => {
|
||||
let _ = c.detach().close().await;
|
||||
}
|
||||
Held::SqlServer(mut c) => {
|
||||
c.0.take();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -530,7 +854,7 @@ impl Held {
|
||||
None => None,
|
||||
};
|
||||
let r = tokio::select! {
|
||||
r = async { fetch!(&mut **$conn, sql, max_rows) } => r,
|
||||
r = async { fetch!(&mut **$conn, sql, max_rows, Cells::Display) } => r,
|
||||
() = cancel.cancelled() => Err(IdeError::cancelled()),
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
@@ -556,6 +880,13 @@ impl Held {
|
||||
run!(c, Some("SELECT pg_backend_pid()"), |b: String| format!("SELECT pg_cancel_backend({b})"))
|
||||
}
|
||||
Held::Mysql(c) => run!(c, Some("SELECT CONNECTION_ID()"), |b: String| format!("KILL QUERY {b}")),
|
||||
Held::SqlServer(c) => {
|
||||
// Tiberius has no attention/cancel API; stop reading and discard the connection.
|
||||
tokio::select! {
|
||||
r = mssql_fetch(c, sql, max_rows) => r?,
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
}
|
||||
}
|
||||
};
|
||||
let (columns, rows, affected, has_more, first) = fetched;
|
||||
let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
@@ -575,6 +906,7 @@ impl Held {
|
||||
pub fn begin_statement(driver: DbDriver) -> &'static str {
|
||||
match driver {
|
||||
DbDriver::Mysql => "START TRANSACTION",
|
||||
DbDriver::SqlServer => "BEGIN TRAN",
|
||||
DbDriver::Sqlite | DbDriver::Postgres => "BEGIN",
|
||||
}
|
||||
}
|
||||
@@ -591,6 +923,95 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::source::{DbOptions, DbProperty};
|
||||
|
||||
#[test]
|
||||
fn discarded_sqlserver_connections_are_broken() {
|
||||
let manager = MssqlConnectionManager(tiberius::Config::new());
|
||||
assert!(manager.has_broken(&mut MssqlConnection(None)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlserver_connect_reports_io_errors() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let mut config = tiberius::Config::new();
|
||||
config.host("127.0.0.1");
|
||||
config.port(listener.local_addr().unwrap().port());
|
||||
drop(listener);
|
||||
let result = MssqlConnectionManager(config).connect().await;
|
||||
assert!(matches!(result, Err(tiberius::error::Error::Io { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlserver_cells_preserve_values_and_nulls() {
|
||||
use std::borrow::Cow;
|
||||
use tiberius::time::{Date, DateTime, DateTime2, DateTimeOffset, SmallDateTime, Time};
|
||||
use tiberius::{ColumnData as C, ColumnType as T, Uuid, numeric::Numeric};
|
||||
let dt = DateTime2::new(Date::new(693_595), Time::new(1234567, 7));
|
||||
let cases = [
|
||||
(C::U8(Some(255)), "255"),
|
||||
(C::I16(Some(-123)), "-123"),
|
||||
(C::I32(Some(-456)), "-456"),
|
||||
(C::I64(Some(i64::MAX)), "9223372036854775807"),
|
||||
(C::F32(Some(1.25)), "1.25"),
|
||||
(C::F64(Some(1.25)), "1.25"),
|
||||
(C::Bit(Some(true)), "true"),
|
||||
(C::String(Some(Cow::Borrowed("hello"))), "hello"),
|
||||
(C::Binary(Some(Cow::Borrowed(&[0, 0xAB, 0xFF]))), "0x00ABFF"),
|
||||
(
|
||||
C::Guid(Some(Uuid::parse_str("ABCDEF01-2345-6789-ABCD-EF0123456789").unwrap())),
|
||||
"abcdef01-2345-6789-abcd-ef0123456789",
|
||||
),
|
||||
(C::Numeric(Some(Numeric::new_with_scale(-123, 5))), "-0.00123"),
|
||||
(C::Numeric(Some(Numeric::new_with_scale(12300, 4))), "1.2300"),
|
||||
(
|
||||
C::Numeric(Some(Numeric::new_with_scale(10i128.pow(38) - 1, 0))),
|
||||
"99999999999999999999999999999999999999",
|
||||
),
|
||||
(C::Xml(Some(Cow::Owned(tiberius::xml::XmlData::new("<a/>")))), "<a/>"),
|
||||
(C::Date(Some(Date::new(0))), "0001-01-01"),
|
||||
(C::Date(Some(Date::new(3_652_058))), "9999-12-31"),
|
||||
(C::Time(Some(Time::new(452961234567, 7))), "12:34:56.1234567"),
|
||||
(C::DateTime(Some(DateTime::new(-1, 1))), "1899-12-31 00:00:00.003"),
|
||||
(C::DateTime(Some(DateTime::new(0, 2))), "1900-01-01 00:00:00.007"),
|
||||
(C::SmallDateTime(Some(SmallDateTime::new(0, 754))), "1900-01-01 12:34:00"),
|
||||
(C::DateTime2(Some(dt)), "1900-01-01 00:00:00.1234567"),
|
||||
(C::DateTimeOffset(Some(DateTimeOffset::new(dt, -60))), "1899-12-31 23:00:00.1234567-01:00"),
|
||||
(C::DateTimeOffset(Some(DateTimeOffset::new(dt, 330))), "1900-01-01 05:30:00.1234567+05:30"),
|
||||
];
|
||||
for (cell, expected) in cases {
|
||||
assert_eq!(tiberius_cell(&cell, T::Null).as_deref(), Some(expected), "{cell:?}");
|
||||
}
|
||||
for cell in [
|
||||
C::U8(None),
|
||||
C::I16(None),
|
||||
C::I32(None),
|
||||
C::I64(None),
|
||||
C::F32(None),
|
||||
C::F64(None),
|
||||
C::Bit(None),
|
||||
C::String(None),
|
||||
C::Guid(None),
|
||||
C::Binary(None),
|
||||
C::Numeric(None),
|
||||
C::Xml(None),
|
||||
C::Date(None),
|
||||
C::Time(None),
|
||||
C::DateTime(None),
|
||||
C::SmallDateTime(None),
|
||||
C::DateTime2(None),
|
||||
C::DateTimeOffset(None),
|
||||
] {
|
||||
assert_eq!(tiberius_cell(&cell, T::Null), None);
|
||||
}
|
||||
for ty in [T::Money, T::Money4] {
|
||||
for (v, expected) in
|
||||
[(0.0, "0.0000"), (1.2, "1.2000"), (-123.4567, "-123.4567"), (214748.3647, "214748.3647")]
|
||||
{
|
||||
assert_eq!(tiberius_cell(&C::F64(Some(v)), ty).as_deref(), Some(expected));
|
||||
}
|
||||
assert_eq!(tiberius_cell(&C::F64(None), ty), None);
|
||||
}
|
||||
}
|
||||
|
||||
fn prop(name: &str, value: &str) -> DbProperty {
|
||||
DbProperty { name: name.into(), value: value.into() }
|
||||
}
|
||||
@@ -649,4 +1070,35 @@ mod tests {
|
||||
let s = DataSource { properties: vec![prop("cache_size", "-2000")], ..Default::default() };
|
||||
assert_eq!(Setup::of(&s).unwrap().params, [("cache_size".to_owned(), "-2000".to_owned())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_bytes_typed_values_are_binary() {
|
||||
// (type name as the driver reports it, the driver reads it as text, binary)
|
||||
let cases = [
|
||||
("VARBINARY", false, true),
|
||||
("BLOB", false, true),
|
||||
("LONGBLOB", false, true),
|
||||
("BINARY", false, true),
|
||||
// MySQL catalog columns (`utf8mb3_bin`) and `utf8mb4_bin` text: flagged BINARY.
|
||||
("VARBINARY", true, false),
|
||||
("BLOB", true, false),
|
||||
("VARCHAR", true, false),
|
||||
("TEXT", true, false),
|
||||
("BYTEA", false, false),
|
||||
("INT", false, false),
|
||||
];
|
||||
for (name, text, binary) in cases {
|
||||
assert_eq!(binary_type(name, text), binary, "{name} text={text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_bytes_are_names_and_grid_bytes_are_hex() {
|
||||
// `oi_数据` as MySQL sends it under `character_set_results = binary`.
|
||||
let name = "oi_数据".as_bytes().to_vec();
|
||||
assert_eq!(bytes_text(name.clone(), Cells::Text), "oi_数据");
|
||||
assert_eq!(bytes_text(name, Cells::Display), "oi_数据");
|
||||
assert_eq!(bytes_text(vec![0xCA, 0xFE], Cells::Display), "0xCAFE");
|
||||
assert_eq!(bytes_text(vec![b'a', 0xFF], Cells::Text), "a\u{FFFD}");
|
||||
}
|
||||
}
|
||||
@@ -549,6 +549,7 @@ impl DbManager {
|
||||
DbDriver::Sqlite => "SELECT 'SQLite ' || sqlite_version()",
|
||||
DbDriver::Postgres => "SELECT version()",
|
||||
DbDriver::Mysql => "SELECT CONCAT(@@version_comment, ' ', VERSION())",
|
||||
DbDriver::SqlServer => "SELECT @@VERSION",
|
||||
};
|
||||
let v = pool.rows(version, 1).await.ok().and_then(|r| r.into_iter().next()?.into_iter().next()?);
|
||||
pool.close().await;
|
||||
@@ -821,6 +822,13 @@ impl DbManager {
|
||||
let ddl = cells(pool.rows(&q, 1).await?, 1).into_iter().next();
|
||||
ddl.map(|d| format!("{d};\n")).ok_or_else(missing)
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
let obj = format!("{}.{}", schema, name).replace('\'', "''");
|
||||
let ddl = cells(pool.rows(&format!("SELECT OBJECT_DEFINITION(OBJECT_ID('{}'))", obj), 1).await?, 0)
|
||||
.into_iter()
|
||||
.next();
|
||||
ddl.map(|d| format!("{d};\n")).ok_or_else(missing)
|
||||
}
|
||||
DbDriver::Postgres => {
|
||||
let rel = pool.rows(&sql::postgres_relation(schema, name), 1).await?.into_iter().next();
|
||||
let (oid, kind) = match rel.as_deref() {
|
||||
|
||||
@@ -36,6 +36,7 @@ pub fn explain_statement(driver: DbDriver, statement: &str) -> String {
|
||||
DbDriver::Sqlite => format!("EXPLAIN QUERY PLAN {s}"),
|
||||
DbDriver::Postgres => format!("EXPLAIN (FORMAT JSON) {s}"),
|
||||
DbDriver::Mysql => format!("EXPLAIN {s}"),
|
||||
DbDriver::SqlServer => format!("SET SHOWPLAN_TEXT ON; {s}"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +60,7 @@ pub fn parse(driver: DbDriver, result: &QueryResult) -> IdeResult<Vec<PlanNode>>
|
||||
let names: Vec<&str> = result.columns.iter().map(|c| c.name.as_str()).collect();
|
||||
Ok(mysql(&names, &result.rows))
|
||||
}
|
||||
DbDriver::SqlServer => Ok(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +199,7 @@ mod tests {
|
||||
assert_eq!(explain_statement(DbDriver::Sqlite, "select 1;"), "EXPLAIN QUERY PLAN select 1");
|
||||
assert_eq!(explain_statement(DbDriver::Postgres, " select 1 "), "EXPLAIN (FORMAT JSON) select 1");
|
||||
assert_eq!(explain_statement(DbDriver::Mysql, "select 1"), "EXPLAIN select 1");
|
||||
assert_eq!(explain_statement(DbDriver::SqlServer, "select 1"), "SET SHOWPLAN_TEXT ON; select 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -16,6 +16,8 @@ pub enum DbDriver {
|
||||
Postgres,
|
||||
/// MySQL and MariaDB.
|
||||
Mysql,
|
||||
/// Microsoft SQL Server.
|
||||
SqlServer,
|
||||
}
|
||||
|
||||
impl DbDriver {
|
||||
@@ -24,6 +26,7 @@ impl DbDriver {
|
||||
DbDriver::Sqlite => None,
|
||||
DbDriver::Postgres => Some(5432),
|
||||
DbDriver::Mysql => Some(3306),
|
||||
DbDriver::SqlServer => Some(1433),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -248,6 +251,7 @@ pub fn scheme_driver(scheme: &str) -> Option<DbDriver> {
|
||||
"postgres" | "postgresql" | "pgsql" | "redshift" | "cockroachdb" | "cockroach" | "yugabytedb"
|
||||
| "timescaledb" | "greenplum" => Some(DbDriver::Postgres),
|
||||
"mysql" | "mariadb" | "tidb" | "singlestore" | "memsql" | "oceanbase" => Some(DbDriver::Mysql),
|
||||
"sqlserver" | "mssql" | "mssqlserver" => Some(DbDriver::SqlServer),
|
||||
"sqlite" | "sqlite3" => Some(DbDriver::Sqlite),
|
||||
_ => None,
|
||||
}
|
||||
@@ -472,6 +476,14 @@ mod tests {
|
||||
assert_eq!(load(tmp.path()).unwrap(), vec![s]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlserver_defaults() {
|
||||
assert_eq!(DbDriver::SqlServer.default_port(), Some(1433));
|
||||
assert_eq!(scheme_driver("sqlserver"), Some(DbDriver::SqlServer));
|
||||
assert_eq!(scheme_driver("mssql"), Some(DbDriver::SqlServer));
|
||||
assert_eq!(scheme_driver("mssqlserver"), Some(DbDriver::SqlServer));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_urls() {
|
||||
let u = parse_url("jdbc:postgresql://ann:s%[email protected]:5433/shop?sslmode=require&search_path=app").unwrap();
|
||||
|
||||
@@ -8,6 +8,7 @@ use specta::Type;
|
||||
pub fn quote_ident(driver: DbDriver, name: &str) -> String {
|
||||
match driver {
|
||||
DbDriver::Mysql => format!("`{}`", name.replace('`', "``")),
|
||||
DbDriver::SqlServer => format!("[{}]", name.replace(']', "]]")),
|
||||
_ => format!("\"{}\"", name.replace('"', "\"\"")),
|
||||
}
|
||||
}
|
||||
@@ -52,6 +53,7 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
|
||||
WHERE schema_name NOT LIKE 'pg\\_toast%' AND schema_name NOT LIKE 'pg\\_temp%' ORDER BY 1"
|
||||
}
|
||||
DbDriver::Mysql if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
|
||||
DbDriver::SqlServer if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
|
||||
DbDriver::Postgres => {
|
||||
"SELECT schema_name FROM information_schema.schemata \
|
||||
WHERE schema_name NOT IN ('pg_catalog', 'information_schema') \
|
||||
@@ -61,6 +63,10 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
|
||||
"SELECT schema_name FROM information_schema.schemata \
|
||||
WHERE schema_name NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys') ORDER BY 1"
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
"SELECT schema_name FROM information_schema.schemata \
|
||||
WHERE schema_name NOT IN ('sys', 'information_schema', 'guest') ORDER BY 1"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,6 +89,11 @@ pub fn tables(driver: DbDriver, schema: &str) -> String {
|
||||
FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::SqlServer => format!(
|
||||
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
|
||||
FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,6 +121,16 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
FROM information_schema.columns WHERE table_schema = {s} AND table_name = {t} \
|
||||
ORDER BY ordinal_position"
|
||||
),
|
||||
DbDriver::SqlServer => format!(
|
||||
"SELECT column_name, data_type, is_nullable, column_default, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM information_schema.table_constraints tc \
|
||||
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
|
||||
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
|
||||
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = {s} \
|
||||
AND tc.table_name = {t} AND k.column_name = c.column_name) THEN 1 ELSE 0 END \
|
||||
FROM information_schema.columns c WHERE c.table_schema = {s} AND c.table_name = {t} \
|
||||
ORDER BY c.ordinal_position"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,6 +155,13 @@ pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
FROM information_schema.statistics WHERE table_schema = {s} AND table_name = {t} \
|
||||
ORDER BY index_name, seq_in_index"
|
||||
),
|
||||
DbDriver::SqlServer => format!(
|
||||
"SELECT i.name, CASE WHEN i.is_unique = 1 THEN 1 ELSE 0 END, c.name \
|
||||
FROM sys.indexes i JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id \
|
||||
JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id \
|
||||
WHERE OBJECT_SCHEMA_NAME(i.object_id) = {s} AND OBJECT_NAME(i.object_id) = {t} AND i.name IS NOT NULL \
|
||||
ORDER BY i.name, ic.key_ordinal"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,6 +199,20 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys') \
|
||||
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.data_type, c.is_nullable, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM information_schema.table_constraints tc \
|
||||
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
|
||||
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
|
||||
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = c.table_schema \
|
||||
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema NOT IN ('sys', 'information_schema') \
|
||||
ORDER BY c.table_schema, c.table_name, c.ordinal_position"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,6 +244,13 @@ pub fn foreign_keys(driver: DbDriver) -> &'static str {
|
||||
AND table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys') \
|
||||
ORDER BY table_schema, table_name, constraint_name, ordinal_position LIMIT 20000"
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
"SELECT table_schema, table_name, constraint_name, column_name, \
|
||||
referenced_table_schema, referenced_table_name, referenced_column_name \
|
||||
FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL \
|
||||
AND table_schema NOT IN ('sys', 'information_schema') \
|
||||
ORDER BY table_schema, table_name, constraint_name, ordinal_position"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,6 +267,9 @@ pub fn table_foreign_keys(driver: DbDriver, schema: &str, table: &str) -> String
|
||||
DbDriver::Mysql => format!(
|
||||
"SELECT table_schema, table_name, constraint_name, column_name, referenced_table_schema, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL AND table_schema = {s} AND table_name = {t} ORDER BY constraint_name, ordinal_position"
|
||||
),
|
||||
DbDriver::SqlServer => format!(
|
||||
"SELECT table_schema, table_name, constraint_name, column_name, referenced_table_schema, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL AND table_schema = {s} AND table_name = {t} ORDER BY constraint_name, ordinal_position"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,6 +279,7 @@ pub fn current_schema(driver: DbDriver) -> Option<&'static str> {
|
||||
DbDriver::Sqlite => None,
|
||||
DbDriver::Postgres => Some("SELECT current_schema()"),
|
||||
DbDriver::Mysql => Some("SELECT DATABASE()"),
|
||||
DbDriver::SqlServer => Some("SELECT DB_NAME()"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -250,8 +303,14 @@ pub fn table_page(
|
||||
) -> String {
|
||||
let mut sql = format!("SELECT * FROM {}", qualified(driver, schema, table));
|
||||
if let Some(f) = filter.map(str::trim).filter(|f| !f.is_empty()) {
|
||||
let f = f.strip_prefix("WHERE ").or_else(|| f.strip_prefix("where ")).unwrap_or(f);
|
||||
sql.push_str(&format!(" WHERE {f}"));
|
||||
let mut f = f.strip_prefix("WHERE ").or_else(|| f.strip_prefix("where ")).unwrap_or(f);
|
||||
if let Some(i) = f.find(';') {
|
||||
f = &f[..i];
|
||||
}
|
||||
f = f.trim();
|
||||
if !f.is_empty() {
|
||||
sql.push_str(&format!(" WHERE {f}"));
|
||||
}
|
||||
}
|
||||
if !sort.is_empty() {
|
||||
let keys: Vec<String> = sort
|
||||
@@ -260,7 +319,14 @@ pub fn table_page(
|
||||
.collect();
|
||||
sql.push_str(&format!(" ORDER BY {}", keys.join(", ")));
|
||||
}
|
||||
sql.push_str(&format!(" LIMIT {} OFFSET {offset}", limit + 1));
|
||||
if driver == DbDriver::SqlServer {
|
||||
if sort.is_empty() {
|
||||
sql.push_str(" ORDER BY (SELECT 1)");
|
||||
}
|
||||
sql.push_str(&format!(" OFFSET {offset} ROWS FETCH NEXT {} ROWS ONLY", limit + 1));
|
||||
} else {
|
||||
sql.push_str(&format!(" LIMIT {} OFFSET {offset}", limit + 1));
|
||||
}
|
||||
sql
|
||||
}
|
||||
|
||||
@@ -400,6 +466,10 @@ pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
"SELECT trigger_name, lower(action_timing), lower(event_manipulation) FROM information_schema.triggers \
|
||||
WHERE event_object_schema = {s} AND event_object_table = {t} ORDER BY 1"
|
||||
),
|
||||
DbDriver::SqlServer => format!(
|
||||
"SELECT t.name, lower(te.type_desc), '' FROM sys.triggers t \
|
||||
WHERE OBJECT_SCHEMA_NAME(t.parent_id) = {s} AND OBJECT_NAME(t.parent_id) = {t} ORDER BY 1"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -438,6 +508,10 @@ pub fn routines(driver: DbDriver, schema: &str) -> Option<String> {
|
||||
AND p.specific_name = r.specific_name AND p.ordinal_position > 0), r.dtd_identifier \
|
||||
FROM information_schema.routines r WHERE r.routine_schema = {s} ORDER BY 1"
|
||||
)),
|
||||
DbDriver::SqlServer => Some(format!(
|
||||
"SELECT r.routine_name, lower(r.routine_type), '', r.data_type \
|
||||
FROM information_schema.routines r WHERE r.routine_schema = {s} ORDER BY 1"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -559,6 +633,10 @@ mod tests {
|
||||
"SELECT * FROM \"public\".\"users\" WHERE age > 3 ORDER BY \"id\" DESC LIMIT 51 OFFSET 100"
|
||||
);
|
||||
assert_eq!(table_page(DbDriver::Mysql, "", "t", Some(" "), &[], 0, 10), "SELECT * FROM `t` LIMIT 11 OFFSET 0");
|
||||
assert_eq!(
|
||||
table_page(DbDriver::SqlServer, "dbo", "users", Some("id = 1;"), &[], 0, 500),
|
||||
"SELECT * FROM [dbo].[users] WHERE id = 1 ORDER BY (SELECT 1) OFFSET 0 ROWS FETCH NEXT 501 ROWS ONLY"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -586,6 +664,30 @@ mod tests {
|
||||
assert!(edit_statement(DbDriver::Postgres, "s", "t", &DbRowEdit::Delete { key: vec![] }).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlserver_quoting_and_schema() {
|
||||
assert_eq!(quote_ident(DbDriver::SqlServer, "a]b"), "[a]]b]");
|
||||
assert_eq!(qualified(DbDriver::SqlServer, "dbo", "t"), "[dbo].[t]");
|
||||
assert_eq!(qualified(DbDriver::SqlServer, "", "t"), "[t]");
|
||||
assert_eq!(current_schema(DbDriver::SqlServer), Some("SELECT DB_NAME()"));
|
||||
assert_eq!(crate::conn::begin_statement(DbDriver::SqlServer), "BEGIN TRAN");
|
||||
assert_eq!(
|
||||
schemas(DbDriver::SqlServer, true),
|
||||
"SELECT schema_name FROM information_schema.schemata ORDER BY 1"
|
||||
);
|
||||
assert!(schemas(DbDriver::SqlServer, false).contains("NOT IN ('sys', 'information_schema', 'guest')"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlserver_introspection_queries() {
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("information_schema.tables"));
|
||||
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("information_schema.columns"));
|
||||
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
|
||||
assert!(foreign_keys(DbDriver::SqlServer).contains("referenced_table_name IS NOT NULL"));
|
||||
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("table_schema = 'dbo'"));
|
||||
assert!(completion_columns(DbDriver::SqlServer).contains("information_schema.columns"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlite_trigger_events() {
|
||||
let ev = sqlite_trigger_event;
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Introspection against a real MySQL / MariaDB server, skipped unless
|
||||
//! `OPENIDEA_TEST_MYSQL=host:port:user:password` names a throwaway server.
|
||||
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{DataSource, DbDriver, DbManager, DbOptions};
|
||||
|
||||
const SCHEMAS: [&str; 2] = ["oi_bin_meta", "oi_数据"];
|
||||
|
||||
fn server() -> Option<(String, u16, String, String)> {
|
||||
let v = std::env::var("OPENIDEA_TEST_MYSQL").ok()?;
|
||||
let mut it = v.splitn(4, ':');
|
||||
Some((it.next()?.into(), it.next()?.parse().ok()?, it.next()?.into(), it.next().unwrap_or("").into()))
|
||||
}
|
||||
|
||||
async fn manager(tmp: &tempfile::TempDir, startup_script: &str) -> Option<DbManager> {
|
||||
let (host, port, user, password) = server()?;
|
||||
let root = tmp.path().to_path_buf();
|
||||
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
db.save_sources(vec![DataSource {
|
||||
id: "m".into(),
|
||||
name: "mysql".into(),
|
||||
driver: DbDriver::Mysql,
|
||||
host,
|
||||
port: Some(port),
|
||||
user,
|
||||
options: DbOptions { startup_script: startup_script.into(), ..Default::default() },
|
||||
..Default::default()
|
||||
}])
|
||||
.await
|
||||
.unwrap();
|
||||
db.set_password("m", Some(password), false).await.unwrap();
|
||||
Some(db)
|
||||
}
|
||||
|
||||
async fn create_schemas(db: &DbManager) {
|
||||
let c = CancellationToken::new();
|
||||
for s in SCHEMAS {
|
||||
for stmt in [
|
||||
format!("DROP DATABASE IF EXISTS `{s}`"),
|
||||
format!("CREATE DATABASE `{s}` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"),
|
||||
format!(
|
||||
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin, raw VARBINARY(4))"
|
||||
),
|
||||
format!("CREATE INDEX `名字` ON `{s}`.`用户` (name)"),
|
||||
format!("INSERT INTO `{s}`.`用户` VALUES (1, 'ann', 0xCAFE)"),
|
||||
] {
|
||||
db.execute("m", &stmt, 10, &c).await.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn assert_metadata_is_text(db: &DbManager) -> IdeResult<()> {
|
||||
let schemas = db.schemas("m").await?;
|
||||
for s in SCHEMAS {
|
||||
assert!(schemas.iter().any(|n| n == s), "{s} missing from {schemas:?}");
|
||||
let tables = db.tables("m", s).await?;
|
||||
assert_eq!(tables.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(), ["用户"], "tables of {s}");
|
||||
let d = db.table_details("m", s, "用户").await?;
|
||||
let cols: Vec<_> = d.columns.iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(cols, ["id", "name", "raw"]);
|
||||
assert!(d.indexes.iter().any(|i| i.name == "名字"), "{:?}", d.indexes);
|
||||
assert!(db.ddl("m", s, "用户").await?.contains("CREATE TABLE `用户`"));
|
||||
}
|
||||
let completion = db.completion("m").await?;
|
||||
let json = serde_json::to_string(&completion).unwrap();
|
||||
assert!(json.contains("oi_数据") && json.contains("用户"), "{json}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// One test: both phases share the schemas they create.
|
||||
#[tokio::test]
|
||||
async fn metadata_names_are_text_whatever_the_column_collation() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
|
||||
create_schemas(&db).await;
|
||||
// MySQL 8 sends `utf8mb3_bin` catalog names flagged BINARY (lower_case_table_names = 0).
|
||||
assert_metadata_is_text(&db).await?;
|
||||
// `_bin` text is text in the grid; true binary stays hex.
|
||||
let r = db.execute("m", "SELECT name, raw FROM `oi_数据`.`用户`", 10, &CancellationToken::new()).await?;
|
||||
assert_eq!(r.rows, vec![vec![Some("ann".to_owned()), Some("0xCAFE".to_owned())]]);
|
||||
|
||||
// Every text column arrives with the `binary` collation.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let raw = manager(&tmp, "SET character_set_results = binary").await.unwrap();
|
||||
assert_metadata_is_text(&raw).await
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
//! Live SQL Server checks, skipped unless OPENIDEA_TEST_SQLSERVER=host:port:user:password
|
||||
//! names a throwaway server.
|
||||
|
||||
use ide_core::CancellationToken;
|
||||
use ide_db::{DataSource, DbDriver, DbSslMode, Held, Pool};
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlserver_values_paging_transactions_and_cancellation() {
|
||||
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
|
||||
let mut parts = server.splitn(4, ':');
|
||||
let source = DataSource {
|
||||
driver: DbDriver::SqlServer,
|
||||
host: parts.next().unwrap().into(),
|
||||
port: Some(parts.next().unwrap().parse().unwrap()),
|
||||
user: parts.next().unwrap().into(),
|
||||
database: "tempdb".into(),
|
||||
ssl: DbSslMode::Disable,
|
||||
..Default::default()
|
||||
};
|
||||
let pool = Pool::connect(&source, parts.next(), None).await.unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let mut held = Held::acquire(&pool).await.unwrap();
|
||||
let table = format!("tempdb.dbo.oi_pr276_values_{}", std::process::id());
|
||||
held.command(&format!("CREATE TABLE {table} (id int PRIMARY KEY, d decimal(38, 7), dt datetime2(7), guid uniqueidentifier, m money, tiny tinyint, x xml)")).await.unwrap();
|
||||
held.command(&format!("INSERT INTO {table} VALUES (1, 12345678901234567890.1234567, '2024-02-29T12:34:56.1234567', 'abcdef01-2345-6789-abcd-ef0123456789', 12.3400, 255, '<a/>'), (2, NULL, NULL, NULL, NULL, NULL, NULL)")).await.unwrap();
|
||||
let r = held.execute(&pool, &format!("SELECT * FROM {table} ORDER BY id"), 1, &cancel).await.unwrap();
|
||||
assert!(r.has_more);
|
||||
assert_eq!(
|
||||
r.rows[0],
|
||||
[
|
||||
"1",
|
||||
"12345678901234567890.1234567",
|
||||
"2024-02-29 12:34:56.1234567",
|
||||
"abcdef01-2345-6789-abcd-ef0123456789",
|
||||
"12.3400",
|
||||
"255",
|
||||
"<a/>"
|
||||
]
|
||||
.map(|s| Some(s.to_owned()))
|
||||
);
|
||||
let r = held.execute(&pool, &format!("SELECT * FROM {table} WHERE id = 2"), 5, &cancel).await.unwrap();
|
||||
assert!(!r.has_more);
|
||||
assert!(r.rows[0][1..].iter().all(Option::is_none));
|
||||
let r = held.execute(&pool, &format!("SELECT * FROM {table} WHERE id = 3"), 5, &cancel).await.unwrap();
|
||||
assert_eq!(r.columns.len(), 7);
|
||||
assert!(r.rows.is_empty());
|
||||
let r = held.execute(&pool,
|
||||
"SELECT CAST('2024-02-29T00:15:00.1234567+05:30' AS datetimeoffset(7)), CAST('2024-02-29' AS date), CAST('12:34:56.1234567' AS time(7)), CAST('2024-02-29T12:34:56.007' AS datetime), CAST('2024-02-29T12:34:00' AS smalldatetime), CAST(-12.3400 AS smallmoney)",
|
||||
1, &cancel).await.unwrap();
|
||||
assert_eq!(
|
||||
r.rows[0],
|
||||
[
|
||||
"2024-02-29 00:15:00.1234567+05:30",
|
||||
"2024-02-29",
|
||||
"12:34:56.1234567",
|
||||
"2024-02-29 12:34:56.007",
|
||||
"2024-02-29 12:34:00",
|
||||
"-12.3400"
|
||||
]
|
||||
.map(|s| Some(s.to_owned()))
|
||||
);
|
||||
held.command(&format!("DROP TABLE {table}")).await.unwrap();
|
||||
drop(held);
|
||||
|
||||
// A unique permanent table lets transaction calls acquire any pooled connection.
|
||||
let table = format!("tempdb.dbo.oi_pr276_{}", std::process::id());
|
||||
pool.execute(&format!("CREATE TABLE {table} (id int PRIMARY KEY, v int)"), 1, &cancel).await.unwrap();
|
||||
pool.transaction(&[(format!("INSERT INTO {table} VALUES (1, 10)"), true)]).await.unwrap();
|
||||
for failing in [format!("INSERT INTO {table} VALUES (1, 20)"), format!("UPDATE {table} SET v = 30 WHERE id = 999")]
|
||||
{
|
||||
assert!(
|
||||
pool.transaction(&[(format!("UPDATE {table} SET v = 99 WHERE id = 1"), true), (failing, true)])
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(pool.rows(&format!("SELECT v FROM {table}"), 1).await.unwrap()[0][0].as_deref(), Some("10"));
|
||||
assert_eq!(pool.rows("SELECT @@TRANCOUNT", 1).await.unwrap()[0][0].as_deref(), Some("0"));
|
||||
}
|
||||
assert_eq!(pool.transaction(&[(format!("UPDATE {table} SET v = 11 WHERE id = 1"), true)]).await.unwrap(), 1);
|
||||
pool.execute(&format!("DROP TABLE {table}"), 1, &cancel).await.unwrap();
|
||||
|
||||
let cancel = CancellationToken::new();
|
||||
let stop = cancel.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
stop.cancel();
|
||||
});
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_secs(2), pool.execute("WAITFOR DELAY '00:00:10'; SELECT 1", 1, &cancel))
|
||||
.await
|
||||
.unwrap()
|
||||
.is_err()
|
||||
);
|
||||
task.await.unwrap();
|
||||
assert_eq!(pool.rows("SELECT 1", 1).await.unwrap()[0][0].as_deref(), Some("1"));
|
||||
}
|
||||
@@ -54,7 +54,7 @@ fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<Str
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
String::from_utf8_lossy(&buf).into_owned()
|
||||
ide_core::output_encoding::decode_tool_output(&buf)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ fn spawn_reader(mut pipe: impl Read + Send + 'static, tx: mpsc::Sender<Event>, s
|
||||
let mut pending: Vec<u8> = Vec::new();
|
||||
let flush = |pending: &mut Vec<u8>| {
|
||||
if !pending.is_empty() {
|
||||
let line = String::from_utf8_lossy(pending).trim_end().to_string();
|
||||
let line = ide_core::output_encoding::decode_tool_output(pending).trim_end().to_string();
|
||||
pending.clear();
|
||||
let _ = tx.send(Event::Line(stream, line));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "ide-fonts"
|
||||
description = "Font families installed on this machine, for the font pickers: CoreText, DirectWrite or fontconfig"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
specta.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFArray", "CFDictionary", "CFNumber", "CFString"] }
|
||||
objc2-core-text = { version = "0.3", default-features = false, features = ["std", "CTFontCollection", "CTFontDescriptor", "CTFontTraits"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite"] }
|
||||
@@ -0,0 +1,306 @@
|
||||
//! The font families installed on this machine, for the font pickers in
|
||||
//! Settings (editor, typography fallback, terminal, UI font).
|
||||
//!
|
||||
//! Each platform asks the font system the WebView itself resolves CSS
|
||||
//! `font-family` names against, so every listed name renders: CoreText on
|
||||
//! macOS, DirectWrite on Windows, fontconfig (`fc-list`) on Linux and the BSDs.
|
||||
//! The list is read on first use and cached until explicitly refreshed; the
|
||||
//! query can take a few hundred milliseconds, so callers run it off the UI and
|
||||
//! command threads.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// One installed family. `monospaced` is the font system's own flag (fixed
|
||||
/// pitch; on Linux also fontconfig's dual-width CJK monospace).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FontFamily {
|
||||
pub name: String,
|
||||
pub monospaced: bool,
|
||||
}
|
||||
|
||||
type Cache = Mutex<Option<Arc<[FontFamily]>>>;
|
||||
|
||||
/// The installed families, sorted case-insensitively, read on first use and
|
||||
/// re-queried when `refresh` is true.
|
||||
pub fn families(refresh: bool) -> Arc<[FontFamily]> {
|
||||
static CACHE: Cache = Mutex::new(None);
|
||||
cached(&CACHE, refresh, imp::list)
|
||||
}
|
||||
|
||||
fn cached(cache: &Cache, refresh: bool, list: impl FnOnce(bool) -> Vec<(String, bool)>) -> Arc<[FontFamily]> {
|
||||
let mut guard = cache.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !refresh && let Some(families) = guard.as_ref() {
|
||||
return Arc::clone(families);
|
||||
}
|
||||
let families: Arc<[FontFamily]> = normalize(list(refresh)).into();
|
||||
*guard = Some(Arc::clone(&families));
|
||||
families
|
||||
}
|
||||
|
||||
/// Merges the per-face records a font system reports into one entry per
|
||||
/// family: trimmed, without empty or hidden (`.`-prefixed system UI) names,
|
||||
/// monospaced when any face is, sorted case-insensitively.
|
||||
pub fn normalize(faces: impl IntoIterator<Item = (String, bool)>) -> Vec<FontFamily> {
|
||||
let mut by_key: BTreeMap<(String, String), bool> = BTreeMap::new();
|
||||
for (name, mono) in faces {
|
||||
let name = name.trim();
|
||||
if name.is_empty() || name.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
*by_key.entry((name.to_lowercase(), name.to_owned())).or_default() |= mono;
|
||||
}
|
||||
let mut out: Vec<FontFamily> = Vec::with_capacity(by_key.len());
|
||||
for ((key, name), monospaced) in by_key {
|
||||
// Same family under two casings (one font file each): keep the first.
|
||||
if let Some(last) = out.last_mut()
|
||||
&& last.name.to_lowercase() == key
|
||||
{
|
||||
last.monospaced |= monospaced;
|
||||
continue;
|
||||
}
|
||||
out.push(FontFamily { name, monospaced });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Parses `fc-list -f '%{family[0]}\t%{spacing}\n'`: one line per face, the
|
||||
/// spacing empty (proportional) or fontconfig's number or name for it.
|
||||
pub fn parse_fc_list(output: &str) -> Vec<(String, bool)> {
|
||||
output
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let (family, spacing) = line.split_once('\t').unwrap_or((line, ""));
|
||||
let family = family.replace("\\-", "-");
|
||||
let mono = match spacing.trim() {
|
||||
"dual" | "mono" | "charcell" => true,
|
||||
s => s.parse::<u32>().is_ok_and(|n| n >= 90),
|
||||
};
|
||||
(!family.trim().is_empty()).then_some((family, mono))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod imp {
|
||||
use objc2_core_foundation::{CFArray, CFDictionary, CFNumber, CFString, CFType};
|
||||
use objc2_core_text::{
|
||||
CTFontCollection, CTFontDescriptor, CTFontSymbolicTraits, kCTFontFamilyNameAttribute, kCTFontSymbolicTrait,
|
||||
kCTFontTraitsAttribute,
|
||||
};
|
||||
|
||||
/// Every face CoreText makes available to this process, as (family, fixed pitch).
|
||||
pub(crate) fn list(_refresh: bool) -> Vec<(String, bool)> {
|
||||
// SAFETY: CoreText's documented types: the matching descriptors array
|
||||
// holds CTFontDescriptors and the traits dictionary maps CFString keys.
|
||||
unsafe {
|
||||
let collection = CTFontCollection::from_available_fonts(None);
|
||||
let Some(descriptors) = collection.matching_font_descriptors() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let descriptors: &CFArray<CTFontDescriptor> = descriptors.cast_unchecked();
|
||||
descriptors
|
||||
.iter()
|
||||
.filter_map(|d| {
|
||||
let name = d.attribute(kCTFontFamilyNameAttribute)?.downcast::<CFString>().ok()?.to_string();
|
||||
let traits = d
|
||||
.attribute(kCTFontTraitsAttribute)
|
||||
.and_then(|t| t.downcast::<CFDictionary>().ok())
|
||||
.and_then(|t| t.cast_unchecked::<CFString, CFType>().get(kCTFontSymbolicTrait))
|
||||
.and_then(|n| n.downcast::<CFNumber>().ok())
|
||||
.and_then(|n| n.as_i64())
|
||||
.unwrap_or(0);
|
||||
Some((name, traits as u32 & CTFontSymbolicTraits::TraitMonoSpace.0 != 0))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use windows::Win32::Graphics::DirectWrite::{
|
||||
DWRITE_FACTORY_TYPE_SHARED, DWRITE_FONT_STRETCH_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_WEIGHT_NORMAL,
|
||||
DWriteCreateFactory, IDWriteFactory, IDWriteFont1, IDWriteLocalizedStrings,
|
||||
};
|
||||
use windows::core::{BOOL, Interface, w};
|
||||
|
||||
/// The system font collection's families, named in English when the
|
||||
/// family has an English name (what CSS matches), else its first name.
|
||||
pub(crate) fn list(refresh: bool) -> Vec<(String, bool)> {
|
||||
// SAFETY: plain DirectWrite COM calls on interfaces we own.
|
||||
unsafe { read(refresh) }.unwrap_or_default()
|
||||
}
|
||||
|
||||
unsafe fn read(refresh: bool) -> windows::core::Result<Vec<(String, bool)>> {
|
||||
let factory: IDWriteFactory = unsafe { DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED) }?;
|
||||
let mut collection = None;
|
||||
unsafe { factory.GetSystemFontCollection(&mut collection, refresh) }?;
|
||||
let Some(collection) = collection else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for i in 0..unsafe { collection.GetFontFamilyCount() } {
|
||||
let Ok(family) = (unsafe { collection.GetFontFamily(i) }) else {
|
||||
continue;
|
||||
};
|
||||
let Some(name) = unsafe { family.GetFamilyNames() }.ok().and_then(|n| unsafe { english(&n) }) else {
|
||||
continue;
|
||||
};
|
||||
let mono = unsafe {
|
||||
family.GetFirstMatchingFont(
|
||||
DWRITE_FONT_WEIGHT_NORMAL,
|
||||
DWRITE_FONT_STRETCH_NORMAL,
|
||||
DWRITE_FONT_STYLE_NORMAL,
|
||||
)
|
||||
}
|
||||
.ok()
|
||||
.and_then(|f| f.cast::<IDWriteFont1>().ok())
|
||||
.is_some_and(|f| unsafe { f.IsMonospacedFont() }.as_bool());
|
||||
out.push((name, mono));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
unsafe fn english(names: &IDWriteLocalizedStrings) -> Option<String> {
|
||||
let mut index = 0u32;
|
||||
let mut exists = BOOL(0);
|
||||
unsafe { names.FindLocaleName(w!("en-us"), &mut index, &mut exists) }.ok()?;
|
||||
if !exists.as_bool() {
|
||||
index = 0;
|
||||
}
|
||||
let len = unsafe { names.GetStringLength(index) }.ok()? as usize;
|
||||
let mut buf = vec![0u16; len + 1];
|
||||
unsafe { names.GetString(index, &mut buf) }.ok()?;
|
||||
Some(String::from_utf16_lossy(&buf[..len]))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod imp {
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// fontconfig's view, which WebKitGTK resolves names with. Empty when
|
||||
/// `fc-list` isn't installed.
|
||||
pub(crate) fn list(_refresh: bool) -> Vec<(String, bool)> {
|
||||
Command::new("fc-list")
|
||||
.args(["-f", "%{family[0]}\t%{spacing}\n"])
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|o| o.status.success())
|
||||
.map(|o| super::parse_fc_list(&String::from_utf8_lossy(&o.stdout)))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
mod imp {
|
||||
pub(crate) fn list(_refresh: bool) -> Vec<(String, bool)> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn fam(name: &str, monospaced: bool) -> FontFamily {
|
||||
FontFamily { name: name.into(), monospaced }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_merges_faces_sorts_and_drops_hidden() {
|
||||
let faces = [
|
||||
("Menlo", true),
|
||||
("Arial", false),
|
||||
("Menlo", true),
|
||||
(".SF NS Mono", true),
|
||||
(" ", false),
|
||||
("arial", false),
|
||||
("PingFang SC", false),
|
||||
("Courier New", false),
|
||||
("Courier New", true),
|
||||
("andale mono", true),
|
||||
]
|
||||
.map(|(n, m)| (n.to_owned(), m));
|
||||
assert_eq!(
|
||||
normalize(faces),
|
||||
vec![
|
||||
fam("andale mono", true),
|
||||
fam("Arial", false),
|
||||
fam("Courier New", true),
|
||||
fam("Menlo", true),
|
||||
fam("PingFang SC", false),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fc_list_spacing_marks_monospace() {
|
||||
let out = "DejaVu Sans Mono\t100\nDejaVu Sans\t\nNoto Sans Mono CJK SC\t90\nTerminus\t110\nCantarell\nFira\\-Code\tmono\n\t100\n";
|
||||
assert_eq!(
|
||||
parse_fc_list(out),
|
||||
[
|
||||
("DejaVu Sans Mono", true),
|
||||
("DejaVu Sans", false),
|
||||
("Noto Sans Mono CJK SC", true),
|
||||
("Terminus", true),
|
||||
("Cantarell", false),
|
||||
("Fira-Code", true),
|
||||
]
|
||||
.map(|(n, m)| (n.to_owned(), m))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caches_until_refresh_requested() {
|
||||
let cache = Mutex::new(None);
|
||||
let calls = AtomicUsize::new(0);
|
||||
let lister = |refresh: bool| {
|
||||
let n = calls.fetch_add(1, Ordering::SeqCst);
|
||||
vec![(format!("Font {n} (refresh={refresh})"), n.is_multiple_of(2))]
|
||||
};
|
||||
|
||||
let first = cached(&cache, false, lister);
|
||||
assert_eq!(&*first, &[fam("Font 0 (refresh=false)", true)]);
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
|
||||
let second = cached(&cache, false, lister);
|
||||
assert!(Arc::ptr_eq(&first, &second));
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
|
||||
let refreshed = cached(&cache, true, lister);
|
||||
assert_eq!(&*refreshed, &[fam("Font 1 (refresh=true)", false)]);
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 2);
|
||||
|
||||
let after_refresh = cached(&cache, false, lister);
|
||||
assert!(Arc::ptr_eq(&refreshed, &after_refresh));
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
/// The real font system: every desktop OS ships some fonts, at least one
|
||||
/// of them monospaced, and the list comes back sorted without duplicates.
|
||||
#[cfg(any(target_os = "macos", windows))]
|
||||
#[test]
|
||||
fn lists_installed_families() {
|
||||
let list = families(false);
|
||||
assert!(list.len() > 20, "only {} families", list.len());
|
||||
assert!(list.iter().any(|f| f.monospaced));
|
||||
assert!(list.iter().any(|f| !f.monospaced));
|
||||
let keys: Vec<String> = list.iter().map(|f| f.name.to_lowercase()).collect();
|
||||
assert!(keys.windows(2).all(|w| w[0] < w[1]));
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let menlo = list.iter().find(|f| f.name == "Menlo").expect("Menlo ships with macOS");
|
||||
assert!(menlo.monospaced);
|
||||
assert!(list.iter().any(|f| f.name == "Helvetica Neue" && !f.monospaced));
|
||||
}
|
||||
assert_eq!(&*families(true), &*list);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ name = "openidea-server"
|
||||
path = "src/bin/server.rs"
|
||||
|
||||
[dependencies]
|
||||
encoding_rs.workspace = true
|
||||
ide-core.workspace = true
|
||||
ide-text.workspace = true
|
||||
ide-vfs.workspace = true
|
||||
@@ -34,17 +35,20 @@ ide-ssh.workspace = true
|
||||
ide-remote.workspace = true
|
||||
ide-jsonrpc.workspace = true
|
||||
ide-agent.workspace = true
|
||||
ide-notebook.workspace = true
|
||||
ide-tools = { path = "../ide-tools" }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
specta-typescript.workspace = true
|
||||
tokio = { workspace = true, features = ["io-std"] }
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
parking_lot.workspace = true
|
||||
dunce.workspace = true
|
||||
dirs.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "io-util"] }
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "io-util", "test-util"] }
|
||||
tempfile.workspace = true
|
||||
@@ -281,7 +281,8 @@ fn run_one(argv: &[String], root: &Path, cancel: &CancellationToken, on_line: &d
|
||||
for pipe in pipes.into_iter().flatten() {
|
||||
let tx = tx.clone();
|
||||
std::thread::spawn(move || {
|
||||
for line in BufReader::new(pipe).lines().map_while(Result::ok) {
|
||||
for line in BufReader::new(pipe).split(b'\n').map_while(Result::ok) {
|
||||
let line = ide_core::output_encoding::decode_tool_output(&line).trim_end_matches('\r').to_owned();
|
||||
if tx.send(line).is_err() {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! runs one on a remote machine and serves it over JSON-RPC ([`rpc`]).
|
||||
|
||||
pub mod environment;
|
||||
pub mod notebook;
|
||||
pub mod ops;
|
||||
mod project;
|
||||
mod proxy;
|
||||
@@ -132,26 +133,75 @@ impl Host {
|
||||
}
|
||||
|
||||
pub fn close_project(&self, window: &str) {
|
||||
if let Some(project) = self.projects.write().remove(window) {
|
||||
let project = self.projects.write().remove(window);
|
||||
if let Some(project) = project {
|
||||
if !project.light {
|
||||
self.environment.project_closed();
|
||||
}
|
||||
project.agents.shutdown();
|
||||
project.notebooks.stop_admission();
|
||||
self.shutdown_notebooks_blocking(vec![project.notebooks.clone()]);
|
||||
let lsp = project.lsp.clone();
|
||||
self.runtime.spawn(async move { lsp.shutdown_all().await });
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops what this host started: language servers, agents, runs and terminals.
|
||||
/// Synchronous project/window destruction must finish owned kernel cleanup,
|
||||
/// not enqueue work which can be lost as the desktop runtime exits.
|
||||
fn shutdown_notebooks_blocking(&self, notebooks: Vec<Arc<notebook::NotebookService>>) {
|
||||
for service in ¬ebooks {
|
||||
service.stop_admission();
|
||||
}
|
||||
let runtime = self.runtime.clone();
|
||||
let wait = move || {
|
||||
let worker = std::thread::spawn(move || {
|
||||
runtime.block_on(async move {
|
||||
for service in notebooks {
|
||||
service.shutdown().await;
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Err(error) = worker.join() {
|
||||
tracing::error!("notebook shutdown thread failed: {error:?}");
|
||||
}
|
||||
};
|
||||
if tokio::runtime::Handle::try_current()
|
||||
.is_ok_and(|handle| handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread)
|
||||
{
|
||||
tokio::task::block_in_place(wait);
|
||||
} else {
|
||||
wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// Called before the desktop runtime exits, including update/restart exits.
|
||||
pub fn shutdown_notebooks_on_exit(&self) {
|
||||
self.shutdown_notebooks_blocking(self.projects().iter().map(|project| project.notebooks.clone()).collect());
|
||||
}
|
||||
|
||||
/// Stops what this host started: notebook kernels, language servers, agents, runs and terminals.
|
||||
/// For a process that exits without dropping the host (the remote server).
|
||||
pub async fn shutdown(&self) {
|
||||
self.environment.shutdown();
|
||||
self.processes.kill_all();
|
||||
self.terminals.kill_all();
|
||||
let projects: Vec<_> = self.projects.write().drain().map(|(_, p)| p).collect();
|
||||
for project in projects {
|
||||
for project in &projects {
|
||||
project.notebooks.stop_admission();
|
||||
project.agents.shutdown();
|
||||
project.lsp.shutdown_all().await;
|
||||
}
|
||||
// Kernel cleanup owns its interrupt/termination/reaping deadlines. An
|
||||
// outer LSP timeout must never abort it before owned children are reaped.
|
||||
for project in &projects {
|
||||
project.notebooks.shutdown().await;
|
||||
}
|
||||
let stop_language_servers = async {
|
||||
for project in &projects {
|
||||
project.lsp.shutdown_all().await;
|
||||
}
|
||||
};
|
||||
if tokio::time::timeout(std::time::Duration::from_secs(10), stop_language_servers).await.is_err() {
|
||||
tracing::warn!("language servers did not shut down in time");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,796 @@
|
||||
//! Project-incarnation notebook ownership and whole-batch execution admission.
|
||||
use crate::ops::Channel;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, SharedSink};
|
||||
use ide_notebook::kernel::{KernelManager, KernelOutput};
|
||||
use ide_notebook::{NotebookDocument, NotebookEdit, NotebookSnapshot};
|
||||
use parking_lot::Mutex;
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{Mutex as AsyncMutex, watch};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NotebookOutputEvent {
|
||||
pub id: String,
|
||||
pub path: String,
|
||||
pub cell: String,
|
||||
pub msg_id: String,
|
||||
pub kind: String,
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
pub content: serde_json::Value,
|
||||
pub version: u32,
|
||||
pub dirty: bool,
|
||||
pub changed_cells: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Registry {
|
||||
stopped: bool,
|
||||
paths: HashMap<PathBuf, String>,
|
||||
documents: HashMap<String, Arc<ManagedDocument>>,
|
||||
}
|
||||
|
||||
struct ManagedDocument {
|
||||
id: String,
|
||||
path: PathBuf,
|
||||
state: Mutex<DocumentState>,
|
||||
control: AsyncMutex<()>,
|
||||
}
|
||||
|
||||
struct DocumentState {
|
||||
document: NotebookDocument,
|
||||
generation: u64,
|
||||
transitioning: bool,
|
||||
closed: bool,
|
||||
active: Option<Arc<Batch>>,
|
||||
kernel_status: Option<(String, Option<String>)>,
|
||||
}
|
||||
|
||||
struct Batch {
|
||||
cancel: CancellationToken,
|
||||
done: watch::Sender<bool>,
|
||||
}
|
||||
|
||||
struct BatchGuard {
|
||||
document: Arc<ManagedDocument>,
|
||||
batch: Arc<Batch>,
|
||||
}
|
||||
|
||||
pub(crate) struct ExecutionAdmission {
|
||||
guard: BatchGuard,
|
||||
generation: u64,
|
||||
plan: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl Drop for BatchGuard {
|
||||
fn drop(&mut self) {
|
||||
let mut state = self.document.state.lock();
|
||||
if state.active.as_ref().is_some_and(|active| Arc::ptr_eq(active, &self.batch)) {
|
||||
if let Err(error) = state.document.set_execution_active(false) {
|
||||
tracing::error!("notebook batch release: {error}");
|
||||
}
|
||||
state.active = None;
|
||||
}
|
||||
self.batch.done.send_replace(true);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NotebookService {
|
||||
registry: Arc<Mutex<Registry>>,
|
||||
kernels: Arc<KernelManager>,
|
||||
sink: SharedSink,
|
||||
}
|
||||
|
||||
impl NotebookService {
|
||||
pub fn new(runtime_dir: PathBuf, sink: SharedSink) -> Arc<Self> {
|
||||
let registry = Arc::new(Mutex::new(Registry::default()));
|
||||
let status_registry = registry.clone();
|
||||
let status_sink = sink.clone();
|
||||
let kernels = KernelManager::new(
|
||||
runtime_dir,
|
||||
Arc::new(move |path, status, message| {
|
||||
let document = {
|
||||
let registry = status_registry.lock();
|
||||
if registry.stopped {
|
||||
return;
|
||||
}
|
||||
registry.paths.get(path).and_then(|id| registry.documents.get(id)).cloned()
|
||||
};
|
||||
if let Some(document) = document {
|
||||
let deliver = {
|
||||
let mut state = document.state.lock();
|
||||
if state.closed {
|
||||
return;
|
||||
}
|
||||
state.kernel_status = Some((status.as_str().to_owned(), message.clone()));
|
||||
!state.transitioning
|
||||
};
|
||||
if deliver {
|
||||
status_sink.emit(IdeEvent::NotebookKernel {
|
||||
id: document.id.clone(),
|
||||
path: path.to_path_buf().into(),
|
||||
state: status.as_str().to_owned(),
|
||||
message,
|
||||
});
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
Arc::new(Self { registry, kernels: Arc::new(kernels), sink })
|
||||
}
|
||||
|
||||
pub fn open(&self, path: &Path) -> IdeResult<NotebookSnapshot> {
|
||||
let path = dunce::canonicalize(path)?;
|
||||
// Serialize first load with path insertion: split views share one incarnation.
|
||||
let mut registry = self.registry.lock();
|
||||
if registry.stopped {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if let Some(id) = registry.paths.get(&path) {
|
||||
return snapshot(®istry.documents[id]);
|
||||
}
|
||||
let document = NotebookDocument::load(&path)?;
|
||||
let initial = document.snapshot();
|
||||
let id = initial.id.clone();
|
||||
registry.paths.insert(path.clone(), id.clone());
|
||||
registry.documents.insert(
|
||||
id.clone(),
|
||||
Arc::new(ManagedDocument {
|
||||
id,
|
||||
path,
|
||||
state: Mutex::new(DocumentState {
|
||||
document,
|
||||
generation: 0,
|
||||
transitioning: false,
|
||||
closed: false,
|
||||
active: None,
|
||||
kernel_status: None,
|
||||
}),
|
||||
control: AsyncMutex::new(()),
|
||||
}),
|
||||
);
|
||||
Ok(initial)
|
||||
}
|
||||
|
||||
fn resolve(&self, id: &str) -> IdeResult<Arc<ManagedDocument>> {
|
||||
let registry = self.registry.lock();
|
||||
if registry.stopped {
|
||||
return Err(IdeError::not_found("notebook project has closed"));
|
||||
}
|
||||
registry.documents.get(id).cloned().ok_or_else(|| IdeError::not_found("notebook incarnation is closed"))
|
||||
}
|
||||
|
||||
pub fn get(&self, id: &str) -> IdeResult<NotebookSnapshot> {
|
||||
snapshot(self.resolve(id)?.as_ref())
|
||||
}
|
||||
|
||||
pub fn edit(&self, id: &str, version: u32, edit: NotebookEdit) -> IdeResult<NotebookSnapshot> {
|
||||
let document = self.resolve(id)?;
|
||||
let mut state = document.state.lock();
|
||||
mutable(&state)?;
|
||||
state.document.edit(version, edit)
|
||||
}
|
||||
|
||||
pub fn save(&self, id: &str) -> IdeResult<NotebookSnapshot> {
|
||||
let document = self.resolve(id)?;
|
||||
let mut state = document.state.lock();
|
||||
mutable(&state)?;
|
||||
state.document.save()
|
||||
}
|
||||
|
||||
pub fn undo(&self, id: &str, redo: bool) -> IdeResult<NotebookSnapshot> {
|
||||
let document = self.resolve(id)?;
|
||||
let mut state = document.state.lock();
|
||||
mutable(&state)?;
|
||||
if state.active.is_some() {
|
||||
return Err(IdeError::unavailable("stop notebook execution before undo or redo"));
|
||||
}
|
||||
if redo { state.document.redo() } else { state.document.undo() }
|
||||
}
|
||||
|
||||
pub async fn interrupt(&self, id: &str) -> IdeResult<()> {
|
||||
let document = self.resolve(id)?;
|
||||
let batch = document.state.lock().active.clone();
|
||||
if let Some(batch) = &batch {
|
||||
batch.cancel.cancel();
|
||||
}
|
||||
// Draining makes prepareClose/save a stable checkpoint, including when
|
||||
// Python catches KeyboardInterrupt or cancel races with kernel startup.
|
||||
let interrupt = self.kernels.interrupt(&document.path).await;
|
||||
self.drain(&document, batch).await?;
|
||||
interrupt
|
||||
}
|
||||
|
||||
async fn drain(&self, document: &ManagedDocument, batch: Option<Arc<Batch>>) -> IdeResult<()> {
|
||||
let Some(batch) = batch else { return Ok(()) };
|
||||
let mut done = batch.done.subscribe();
|
||||
match tokio::time::timeout(Duration::from_secs(5), done.wait_for(|done| *done)).await {
|
||||
Ok(Ok(_)) => return Ok(()),
|
||||
Ok(Err(_)) => return Err(IdeError::internal("notebook execution completion channel closed")),
|
||||
Err(_) => {}
|
||||
}
|
||||
// An uncooperative kernel must not outlive a close/reload authorization.
|
||||
self.kernels.shutdown_kernel(&document.path).await?;
|
||||
tokio::time::timeout(Duration::from_secs(5), done.wait_for(|done| *done))
|
||||
.await
|
||||
.map_err(|_| IdeError::unavailable("notebook execution did not stop after kernel shutdown"))?
|
||||
.map_err(|_| IdeError::internal("notebook execution completion channel closed"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn reload(&self, id: &str, restart: bool) -> IdeResult<NotebookSnapshot> {
|
||||
let document = self.resolve(id)?;
|
||||
let _control = document.control.lock().await;
|
||||
let batch = invalidate(&document)?;
|
||||
let result = async {
|
||||
let _ = self.kernels.interrupt(&document.path).await;
|
||||
self.drain(&document, batch).await?;
|
||||
if document.state.lock().closed {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if restart {
|
||||
self.kernels.restart(&document.path).await?;
|
||||
snapshot(&document)
|
||||
} else {
|
||||
self.kernels.shutdown_kernel(&document.path).await?;
|
||||
document.state.lock().document.reload()
|
||||
}
|
||||
}
|
||||
.await;
|
||||
let status = {
|
||||
let mut state = document.state.lock();
|
||||
state.transitioning = false;
|
||||
if state.closed { None } else { state.kernel_status.clone() }
|
||||
};
|
||||
if let Some((state, message)) = status {
|
||||
self.sink.emit(IdeEvent::NotebookKernel {
|
||||
id: document.id.clone(),
|
||||
path: document.path.clone().into(),
|
||||
state,
|
||||
message,
|
||||
});
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Frontend disposal may arrive after project replacement has already retired this id.
|
||||
pub async fn close(&self, id: &str) -> IdeResult<()> {
|
||||
let document = match self.resolve(id) {
|
||||
Ok(document) => document,
|
||||
Err(error) if error.kind == ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let _control = document.control.lock().await;
|
||||
if document.state.lock().closed {
|
||||
return Ok(());
|
||||
}
|
||||
let batch = invalidate(&document)?;
|
||||
let result = async {
|
||||
let _ = self.kernels.interrupt(&document.path).await;
|
||||
self.drain(&document, batch).await?;
|
||||
self.kernels.shutdown_kernel(&document.path).await
|
||||
}
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
document.state.lock().transitioning = false;
|
||||
return Err(error);
|
||||
}
|
||||
document.state.lock().closed = true;
|
||||
let mut registry = self.registry.lock();
|
||||
registry.documents.remove(id);
|
||||
registry.paths.remove(&document.path);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn admit(
|
||||
&self,
|
||||
id: &str,
|
||||
cells: Vec<String>,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<ExecutionAdmission> {
|
||||
admit(self.resolve(id)?, cells, cancel)
|
||||
}
|
||||
|
||||
pub(crate) async fn execute(
|
||||
self: &Arc<Self>,
|
||||
admission: ExecutionAdmission,
|
||||
python: PathBuf,
|
||||
on_output: Channel<NotebookOutputEvent>,
|
||||
) -> IdeResult<NotebookSnapshot> {
|
||||
let document = admission.guard.document.clone();
|
||||
let service = self.clone();
|
||||
// Keep admission and native execution owned if an IPC receiver disappears.
|
||||
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;
|
||||
drop(guard);
|
||||
match result {
|
||||
Ok(()) => snapshot(&document),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|error| IdeError::internal(error.to_string()))?
|
||||
}
|
||||
|
||||
async fn run_batch(
|
||||
&self,
|
||||
document: Arc<ManagedDocument>,
|
||||
generation: u64,
|
||||
plan: Vec<(String, String)>,
|
||||
python: PathBuf,
|
||||
batch: Arc<Batch>,
|
||||
on_output: Channel<NotebookOutputEvent>,
|
||||
) -> IdeResult<()> {
|
||||
for (cell, source) in plan {
|
||||
{
|
||||
let mut state = document.state.lock();
|
||||
if batch.cancel.is_cancelled() || state.closed || state.generation != generation {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
// A user may delete a queued cell while an earlier one executes.
|
||||
// Never resurrect it from the captured source or a late output.
|
||||
match state.document.begin_execution(&cell) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind == ErrorKind::NotFound => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
let output_error = Arc::new(Mutex::new(None));
|
||||
let callback_document = document.clone();
|
||||
let callback_batch = batch.clone();
|
||||
let callback_error = output_error.clone();
|
||||
let callback_cell = cell.clone();
|
||||
let channel = on_output.clone();
|
||||
let result = self
|
||||
.kernels
|
||||
.execute(
|
||||
&document.path,
|
||||
&python,
|
||||
&source,
|
||||
batch.cancel.clone(),
|
||||
Arc::new(move |output: KernelOutput| {
|
||||
let event = match commit_output(
|
||||
&callback_document,
|
||||
&callback_batch,
|
||||
generation,
|
||||
&callback_cell,
|
||||
output,
|
||||
) {
|
||||
Ok(Some(event)) => event,
|
||||
Ok(None) => return,
|
||||
Err(error) => {
|
||||
*callback_error.lock() = Some(error);
|
||||
callback_batch.cancel.cancel();
|
||||
return;
|
||||
}
|
||||
};
|
||||
let _ = channel.send(event);
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
if let Some(error) = output_error.lock().take() {
|
||||
return Err(error);
|
||||
}
|
||||
let result = result?;
|
||||
if batch.cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if result.status != "ok" {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let state = document.state.lock();
|
||||
if state.closed || state.generation != generation || batch.cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Synchronously revoke admission before handing cleanup to an async runtime.
|
||||
pub fn stop_admission(&self) {
|
||||
let mut registry = self.registry.lock();
|
||||
registry.stopped = true;
|
||||
for document in registry.documents.values() {
|
||||
let mut state = document.state.lock();
|
||||
state.closed = true;
|
||||
state.generation += 1;
|
||||
if let Some(batch) = &state.active {
|
||||
batch.cancel.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn shutdown(&self) {
|
||||
self.stop_admission();
|
||||
self.kernels.shutdown().await;
|
||||
let documents: Vec<_> = self.registry.lock().documents.values().cloned().collect();
|
||||
for document in documents {
|
||||
let batch = document.state.lock().active.clone();
|
||||
if let Err(error) = self.drain(&document, batch).await {
|
||||
tracing::error!("notebook cleanup: {error}");
|
||||
}
|
||||
}
|
||||
let mut registry = self.registry.lock();
|
||||
registry.paths.clear();
|
||||
registry.documents.clear();
|
||||
}
|
||||
}
|
||||
|
||||
fn mutable(state: &DocumentState) -> IdeResult<()> {
|
||||
if state.closed {
|
||||
Err(IdeError::not_found("notebook incarnation is closed"))
|
||||
} else if state.transitioning {
|
||||
Err(IdeError::unavailable("notebook lifecycle operation is in progress"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot(document: &ManagedDocument) -> IdeResult<NotebookSnapshot> {
|
||||
let state = document.state.lock();
|
||||
if state.closed {
|
||||
return Err(IdeError::not_found("notebook incarnation is closed"));
|
||||
}
|
||||
Ok(state.document.snapshot())
|
||||
}
|
||||
|
||||
fn invalidate(document: &ManagedDocument) -> IdeResult<Option<Arc<Batch>>> {
|
||||
let mut state = document.state.lock();
|
||||
mutable(&state)?;
|
||||
state.transitioning = true;
|
||||
state.generation += 1;
|
||||
if let Some(batch) = &state.active {
|
||||
batch.cancel.cancel();
|
||||
}
|
||||
Ok(state.active.clone())
|
||||
}
|
||||
|
||||
fn execution_plan(snapshot: &NotebookSnapshot, cells: Vec<String>) -> IdeResult<Vec<(String, String)>> {
|
||||
let mut selected: HashSet<_> = cells.iter().map(String::as_str).collect();
|
||||
if selected.is_empty() || selected.len() != cells.len() {
|
||||
return Err(IdeError::invalid("select distinct code cells to execute"));
|
||||
}
|
||||
let mut plan = Vec::with_capacity(selected.len());
|
||||
for cell in &snapshot.cells {
|
||||
if selected.remove(cell.id.as_str()) {
|
||||
if cell.cell_type != "code" {
|
||||
return Err(IdeError::invalid("only code cells can execute"));
|
||||
}
|
||||
plan.push((cell.id.clone(), cell.source.clone()));
|
||||
}
|
||||
}
|
||||
if !selected.is_empty() {
|
||||
return Err(IdeError::not_found("an execution cell no longer exists"));
|
||||
}
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
fn admit(
|
||||
document: Arc<ManagedDocument>,
|
||||
cells: Vec<String>,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<ExecutionAdmission> {
|
||||
let (batch, generation, plan) = {
|
||||
let mut state = document.state.lock();
|
||||
mutable(&state)?;
|
||||
if state.active.is_some() {
|
||||
return Err(IdeError::unavailable("notebook execution batch is already running"));
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let plan = execution_plan(&state.document.snapshot(), cells)?;
|
||||
state.document.set_execution_active(true)?;
|
||||
let (done, _) = watch::channel(false);
|
||||
let batch = Arc::new(Batch { cancel, done });
|
||||
state.active = Some(batch.clone());
|
||||
(batch, state.generation, plan)
|
||||
};
|
||||
Ok(ExecutionAdmission { guard: BatchGuard { document, batch }, generation, plan })
|
||||
}
|
||||
|
||||
/// Commit under the short document lock; the caller delivers only after release.
|
||||
fn commit_output(
|
||||
document: &ManagedDocument,
|
||||
batch: &Arc<Batch>,
|
||||
generation: u64,
|
||||
cell: &str,
|
||||
output: KernelOutput,
|
||||
) -> IdeResult<Option<NotebookOutputEvent>> {
|
||||
let mut state = document.state.lock();
|
||||
if state.closed
|
||||
|| state.generation != generation
|
||||
|| !state.active.as_ref().is_some_and(|active| Arc::ptr_eq(active, batch))
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let changed_cells = match state.document.record_output(cell, &output) {
|
||||
Ok(changed) => changed,
|
||||
Err(error) if error.kind == ErrorKind::NotFound => return Ok(None),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
Ok(Some(NotebookOutputEvent {
|
||||
id: document.id.clone(),
|
||||
path: document.path.to_string_lossy().into_owned(),
|
||||
cell: cell.to_owned(),
|
||||
msg_id: output.msg_id,
|
||||
kind: output.kind,
|
||||
content: output.content,
|
||||
version: state.document.version(),
|
||||
dirty: state.document.is_dirty(),
|
||||
changed_cells,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn fixture() -> (tempfile::TempDir, Arc<NotebookService>, NotebookSnapshot) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("session.ipynb");
|
||||
std::fs::write(&path, serde_json::to_vec(&json!({
|
||||
"nbformat": 4, "nbformat_minor": 5, "metadata": {},
|
||||
"cells": [
|
||||
{"id":"first","cell_type":"code","metadata":{},"source":"x = 1","outputs":[],"execution_count":null},
|
||||
{"id":"second","cell_type":"code","metadata":{},"source":"print(x)","outputs":[],"execution_count":null},
|
||||
{"id":"prose","cell_type":"markdown","metadata":{},"source":"notes"}
|
||||
]
|
||||
})).unwrap()).unwrap();
|
||||
let service = NotebookService::new(dir.path().join("kernels"), Arc::new(ide_core::NullSink));
|
||||
let snapshot = service.open(&path).unwrap();
|
||||
(dir, service, snapshot)
|
||||
}
|
||||
|
||||
fn output(kind: &str, content: serde_json::Value) -> KernelOutput {
|
||||
KernelOutput { kind: kind.into(), content, msg_id: "actual-parent-request".into() }
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn canonical_split_opens_share_incarnation_but_reopen_and_projects_do_not() {
|
||||
let (dir, service, initial) = fixture();
|
||||
let alternate = dir.path().join(".").join("session.ipynb");
|
||||
assert_eq!(service.open(&alternate).unwrap().id, initial.id);
|
||||
let other = NotebookService::new(dir.path().join("other-runtime"), Arc::new(ide_core::NullSink));
|
||||
let independent = other.open(&alternate).unwrap();
|
||||
assert_ne!(initial.id, independent.id);
|
||||
assert_eq!(other.get(&initial.id).unwrap_err().kind, ErrorKind::NotFound);
|
||||
service.close(&initial.id).await.unwrap();
|
||||
let reopened = service.open(&alternate).unwrap();
|
||||
assert_ne!(reopened.id, initial.id);
|
||||
assert_eq!(service.get(&initial.id).unwrap_err().kind, ErrorKind::NotFound);
|
||||
// A delayed old-incarnation close cannot dispose a new session at that path.
|
||||
service.close(&initial.id).await.unwrap();
|
||||
assert_eq!(service.get(&reopened.id).unwrap().id, reopened.id);
|
||||
service.shutdown().await;
|
||||
other.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn failed_close_keeps_the_incarnation_recoverable_until_a_retry_succeeds() {
|
||||
let (dir, service, initial) = fixture();
|
||||
// A batch that never drains models a kernel that ignores interrupt and shutdown.
|
||||
let admission =
|
||||
service.admit(&initial.id, vec![initial.cells[0].id.clone()], CancellationToken::new()).unwrap();
|
||||
let error = service.close(&initial.id).await.unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::Unavailable);
|
||||
assert!(admission.guard.batch.cancel.is_cancelled());
|
||||
// The backend still owns the incarnation: a reopen shares it instead of
|
||||
// starting a second kernel, and the failed close left it usable.
|
||||
let reopened = service.open(&dir.path().join("session.ipynb")).unwrap();
|
||||
assert_eq!(reopened.id, initial.id);
|
||||
assert!(matches!(service.admit(&initial.id, vec![initial.cells[0].id.clone()], CancellationToken::new()),
|
||||
Err(error) if error.kind == ErrorKind::Unavailable));
|
||||
drop(admission);
|
||||
service.close(&initial.id).await.unwrap();
|
||||
assert_eq!(service.get(&initial.id).unwrap_err().kind, ErrorKind::NotFound);
|
||||
assert_ne!(service.open(&dir.path().join("session.ipynb")).unwrap().id, initial.id);
|
||||
service.shutdown().await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_admission_captures_document_order_and_retains_busy_until_drained() {
|
||||
let (_dir, service, initial) = fixture();
|
||||
let document = service.resolve(&initial.id).unwrap();
|
||||
let cells = vec![initial.cells[1].id.clone(), initial.cells[0].id.clone()];
|
||||
let admission = admit(document.clone(), cells.clone(), CancellationToken::new()).unwrap();
|
||||
assert_eq!(
|
||||
admission.plan,
|
||||
vec![(initial.cells[0].id.clone(), "x = 1".into()), (initial.cells[1].id.clone(), "print(x)".into()),]
|
||||
);
|
||||
service
|
||||
.edit(
|
||||
&initial.id,
|
||||
initial.version,
|
||||
NotebookEdit::SetSource { cell: initial.cells[1].id.clone(), source: "print('new source')".into() },
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(admission.plan[1].1, "print(x)");
|
||||
assert_eq!(service.undo(&initial.id, false).unwrap_err().kind, ErrorKind::Unavailable);
|
||||
admission.guard.batch.cancel.cancel();
|
||||
assert!(matches!(admit(document.clone(), cells.clone(), CancellationToken::new()), Err(error)
|
||||
if error.kind == ErrorKind::Unavailable));
|
||||
drop(admission);
|
||||
let next = admit(document, cells, CancellationToken::new()).unwrap();
|
||||
assert_eq!(next.plan[1].1, "print('new source')");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_commits_revision_and_cross_cell_display_updates_before_delivery() {
|
||||
let (_dir, service, initial) = fixture();
|
||||
let document = service.resolve(&initial.id).unwrap();
|
||||
let cells: Vec<_> = initial.cells[..2].iter().map(|cell| cell.id.clone()).collect();
|
||||
let admission = admit(document.clone(), cells.clone(), CancellationToken::new()).unwrap();
|
||||
let event = commit_output(
|
||||
&document,
|
||||
&admission.guard.batch,
|
||||
admission.generation,
|
||||
&cells[0],
|
||||
output(
|
||||
"display_data",
|
||||
json!({"data":{"text/plain":"before"},"metadata":{},"transient":{"display_id":"shared"}}),
|
||||
),
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let committed = service.get(&initial.id).unwrap();
|
||||
assert_eq!(event.version, committed.version);
|
||||
assert!(event.version > initial.version);
|
||||
assert!(event.dirty);
|
||||
assert_eq!(event.msg_id, "actual-parent-request");
|
||||
assert_eq!(committed.cells[0].outputs[0]["data"]["text/plain"], "before");
|
||||
let updated = commit_output(
|
||||
&document,
|
||||
&admission.guard.batch,
|
||||
admission.generation,
|
||||
&cells[1],
|
||||
output(
|
||||
"update_display_data",
|
||||
json!({"data":{"text/plain":"after"},"metadata":{},"transient":{"display_id":"shared"}}),
|
||||
),
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(updated.changed_cells.contains(&cells[0]));
|
||||
let committed = service.get(&initial.id).unwrap();
|
||||
assert_eq!(committed.cells[0].outputs[0]["data"]["text/plain"], "after");
|
||||
assert!(committed.cells[0].outputs[0].get("transient").is_none());
|
||||
assert_eq!(updated.version, committed.version);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalidated_or_completed_batches_cannot_commit_and_deleted_cells_stay_deleted() {
|
||||
let (_dir, service, initial) = fixture();
|
||||
let document = service.resolve(&initial.id).unwrap();
|
||||
let cell = initial.cells[0].id.clone();
|
||||
let admission = admit(document.clone(), vec![cell.clone()], CancellationToken::new()).unwrap();
|
||||
let deleted =
|
||||
service.edit(&initial.id, initial.version, NotebookEdit::DeleteCell { cell: cell.clone() }).unwrap();
|
||||
assert!(
|
||||
commit_output(
|
||||
&document,
|
||||
&admission.guard.batch,
|
||||
admission.generation,
|
||||
&cell,
|
||||
output("stream", json!({"name":"stdout","text":"late"}))
|
||||
)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(service.get(&initial.id).unwrap().version, deleted.version);
|
||||
let other = initial.cells[1].id.clone();
|
||||
invalidate(&document).unwrap();
|
||||
assert!(admission.guard.batch.cancel.is_cancelled());
|
||||
assert!(
|
||||
commit_output(
|
||||
&document,
|
||||
&admission.guard.batch,
|
||||
admission.generation,
|
||||
&other,
|
||||
output("stream", json!({"name":"stdout","text":"old generation"}))
|
||||
)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
let batch = admission.guard.batch.clone();
|
||||
let generation = document.state.lock().generation;
|
||||
drop(admission);
|
||||
assert!(
|
||||
commit_output(
|
||||
&document,
|
||||
&batch,
|
||||
generation,
|
||||
&other,
|
||||
output("stream", json!({"name":"stdout","text":"post idle"}))
|
||||
)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(service.get(&initial.id).unwrap().version, deleted.version);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reload_preserves_incarnation_and_project_shutdown_revokes_all_admission() {
|
||||
let (_dir, service, initial) = fixture();
|
||||
let changed = service
|
||||
.edit(
|
||||
&initial.id,
|
||||
initial.version,
|
||||
NotebookEdit::SetSource { cell: initial.cells[0].id.clone(), source: "changed".into() },
|
||||
)
|
||||
.unwrap();
|
||||
let reloaded = service.reload(&initial.id, false).await.unwrap();
|
||||
assert_eq!(reloaded.id, initial.id);
|
||||
assert!(reloaded.version > changed.version);
|
||||
assert_eq!(reloaded.cells[0].source, "x = 1");
|
||||
assert!(!reloaded.dirty);
|
||||
let document = service.resolve(&initial.id).unwrap();
|
||||
let admission = admit(document.clone(), vec![initial.cells[0].id.clone()], CancellationToken::new()).unwrap();
|
||||
service.stop_admission();
|
||||
assert!(admission.guard.batch.cancel.is_cancelled());
|
||||
assert_eq!(service.get(&initial.id).unwrap_err().kind, ErrorKind::NotFound);
|
||||
assert!(matches!(admit(document, vec![initial.cells[0].id.clone()], CancellationToken::new()), Err(error)
|
||||
if error.kind == ErrorKind::NotFound));
|
||||
drop(admission);
|
||||
service.shutdown().await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_batch_selection_does_not_claim_admission() {
|
||||
let (_dir, service, initial) = fixture();
|
||||
let document = service.resolve(&initial.id).unwrap();
|
||||
for cells in [
|
||||
vec![],
|
||||
vec![initial.cells[0].id.clone(), initial.cells[0].id.clone()],
|
||||
vec![initial.cells[2].id.clone()],
|
||||
vec!["deleted".into()],
|
||||
] {
|
||||
assert!(admit(document.clone(), cells, CancellationToken::new()).is_err());
|
||||
}
|
||||
let cancelled = CancellationToken::new();
|
||||
cancelled.cancel();
|
||||
assert!(matches!(admit(document.clone(), vec![initial.cells[0].id.clone()], cancelled), Err(error)
|
||||
if error.kind == ErrorKind::Cancelled));
|
||||
let valid = admit(document, vec![initial.cells[0].id.clone()], CancellationToken::new()).unwrap();
|
||||
assert_eq!(valid.plan[0].1, "x = 1");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn interrupt_cancels_before_drain_and_does_not_release_a_live_batch() {
|
||||
let (_dir, service, initial) = fixture();
|
||||
service
|
||||
.edit(
|
||||
&initial.id,
|
||||
initial.version,
|
||||
NotebookEdit::SetSource { cell: initial.cells[0].id.clone(), source: "changed source".into() },
|
||||
)
|
||||
.unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let admission = service.admit(&initial.id, vec![initial.cells[0].id.clone()], cancel.clone()).unwrap();
|
||||
let interrupt_service = service.clone();
|
||||
let id = initial.id.clone();
|
||||
let interrupt = tokio::spawn(async move { interrupt_service.interrupt(&id).await });
|
||||
tokio::time::timeout(Duration::from_secs(1), cancel.cancelled()).await.unwrap();
|
||||
assert!(!interrupt.is_finished(), "interrupt must wait for owned execution to drain");
|
||||
assert!(matches!(service.admit(&initial.id, vec![initial.cells[0].id.clone()], CancellationToken::new()),
|
||||
Err(error) if error.kind == ErrorKind::Unavailable));
|
||||
let mut done = admission.guard.batch.done.subscribe();
|
||||
drop(admission);
|
||||
assert!(*done.borrow_and_update());
|
||||
tokio::time::timeout(Duration::from_secs(1), interrupt).await.unwrap().unwrap().unwrap();
|
||||
let next = service.admit(&initial.id, vec![initial.cells[0].id.clone()], CancellationToken::new()).unwrap();
|
||||
assert_eq!(next.plan[0].1, "changed source");
|
||||
drop(next);
|
||||
let undone = service.undo(&initial.id, false).unwrap();
|
||||
assert_eq!(undone.cells[0].source, "x = 1");
|
||||
service.close(&initial.id).await.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -140,6 +140,10 @@ pub fn archive(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
host.project(window)?.agents.archive(&task)
|
||||
}
|
||||
|
||||
pub fn unarchive(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
host.project(window)?.agents.unarchive(&task)
|
||||
}
|
||||
|
||||
pub async fn delete(host: &Host, window: &str, task: String, remove_worktree: bool) -> IdeResult<()> {
|
||||
host.project(window)?.agents.delete(&task, remove_worktree).await
|
||||
}
|
||||
@@ -183,6 +187,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("agent_respond", |c| async move {
|
||||
respond(&c.host, &c.window, c.arg("task")?, c.arg("permission")?, c.arg("option")?)
|
||||
});
|
||||
d.add("agent_unarchive", |c| async move { unarchive(&c.host, &c.window, c.arg("task")?) });
|
||||
d.add("agent_archive", |c| async move { archive(&c.host, &c.window, c.arg("task")?) });
|
||||
d.add(
|
||||
"agent_delete",
|
||||
|
||||
@@ -27,7 +27,12 @@ fn java_env(project_jdk: Option<&ide_sdk::java::Jdk>, release: Option<u32>) -> B
|
||||
/// The build model with the launch settings applied: the JDK (`JAVA_HOME`), and
|
||||
/// the Maven home and options from Settings › Maven.
|
||||
pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
|
||||
let mut model = ide_build::load(root, cache, ide_sdk::apply::maven_local_repository(root, settings));
|
||||
let mut model = ide_build::load_linked(
|
||||
root,
|
||||
cache,
|
||||
ide_sdk::apply::maven_local_repository(root, settings),
|
||||
&settings.languages.java.maven,
|
||||
);
|
||||
let jdk = ide_sdk::apply::project_jdk(root, settings);
|
||||
if let Some(m) = &mut model.maven {
|
||||
let mvn = ide_sdk::apply::maven_command(root, settings);
|
||||
@@ -41,7 +46,8 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
|
||||
}
|
||||
}
|
||||
if let Some(g) = &mut model.gradle {
|
||||
g.env = java_env(jdk.as_ref(), g.java_version);
|
||||
g.env = ide_sdk::apply::gradle_env(root, settings, java_env(jdk.as_ref(), g.java_version));
|
||||
g.command = ide_sdk::apply::gradle_command(root, &root.join(&g.dir), settings).to_string_lossy().into_owned();
|
||||
}
|
||||
// A failed sync of a project no installed JDK can build says so first (with a Download JDK action).
|
||||
let missing = |release: Option<u32>| match jdk {
|
||||
@@ -62,7 +68,7 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
|
||||
if let Some(g) = &mut model.gradle
|
||||
&& g.sync_error.is_some()
|
||||
{
|
||||
let hint = missing(g.java_version);
|
||||
let hint = if settings.languages.java.gradle.jvm.trim().is_empty() { missing(g.java_version) } else { None };
|
||||
explain(&mut g.sync_error, hint);
|
||||
}
|
||||
model
|
||||
@@ -107,6 +113,8 @@ pub async fn build_sync(
|
||||
env,
|
||||
maven_command: ide_sdk::apply::maven_command(&root, &settings).map(|p| p.to_string_lossy().into_owned()),
|
||||
maven_options: ide_sdk::apply::maven_options(&root, &settings),
|
||||
maven_settings: settings.languages.java.maven.clone(),
|
||||
gradle_command: current.gradle.as_ref().map(|g| g.command.clone()),
|
||||
};
|
||||
let progress = |p: SyncProgress| {
|
||||
let _ = on_progress.send(p);
|
||||
@@ -261,3 +269,34 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
.await
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod gradle_settings_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn model_for_sync_tasks_and_compile_uses_gradle_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::write(root.join("build.gradle"), "plugins { id 'java' }").unwrap();
|
||||
let wrapper = root.join(if cfg!(windows) { "gradlew.bat" } else { "gradlew" });
|
||||
std::fs::write(&wrapper, "").unwrap();
|
||||
let mut settings = Settings::default();
|
||||
let default = load(root, &root.join("cache"), &settings).gradle.unwrap();
|
||||
assert_eq!(default.command, wrapper.to_string_lossy());
|
||||
settings.languages.java.gradle.jvm = "jdk21".into();
|
||||
settings.languages.java.gradle.user_home = "user-home".into();
|
||||
settings.languages.java.gradle.distribution = ide_core::settings::GradleDistribution::Local;
|
||||
settings.languages.java.gradle.home = "gradle-install".into();
|
||||
let model = load(root, &root.join("cache"), &settings).gradle.unwrap();
|
||||
assert_eq!(
|
||||
model.command,
|
||||
root.join("gradle-install")
|
||||
.join("bin")
|
||||
.join(if cfg!(windows) { "gradle.bat" } else { "gradle" })
|
||||
.to_string_lossy()
|
||||
);
|
||||
assert_eq!(model.env["JAVA_HOME"], root.join("jdk21").to_string_lossy());
|
||||
assert_eq!(model.env["GRADLE_USER_HOME"], root.join("user-home").to_string_lossy());
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,13 @@ use std::path::PathBuf;
|
||||
|
||||
/// Starts a session owned by this window: its events (and those of child sessions) go here only.
|
||||
pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> IdeResult<DebugSessionId> {
|
||||
let mut config = match_java_debug_encoding(config, cfg!(windows));
|
||||
if config.adapter == "debugpy"
|
||||
&& config.request == "launch"
|
||||
&& let Ok(project) = host.project(window)
|
||||
{
|
||||
super::python::prepare_debug(&mut config, &super::python::paths(&project))?;
|
||||
}
|
||||
let label = window;
|
||||
let owner = SessionOwner::new(host.owner_window(label), host.window_sink(label));
|
||||
let settings = match host.project(label) {
|
||||
@@ -20,6 +27,26 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
host.debugger.start_with(config, owner, custom).await
|
||||
}
|
||||
|
||||
/// A JVM launched by java-debug writes what java-debug decodes its output as
|
||||
/// (see [`ide_core::output_encoding::java_debug_vm_args`]).
|
||||
fn match_java_debug_encoding(mut config: LaunchConfig, windows: bool) -> LaunchConfig {
|
||||
if config.adapter != "java-debug" || config.request != "launch" {
|
||||
return config;
|
||||
}
|
||||
let Some(serde_json::Value::Object(mut extra)) =
|
||||
config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok())
|
||||
else {
|
||||
return config;
|
||||
};
|
||||
let vm_args = extra.get("vmArgs").and_then(|v| v.as_str()).unwrap_or_default();
|
||||
let encoding = extra.get("encoding").and_then(|v| v.as_str());
|
||||
if let Some(vm_args) = ide_core::output_encoding::java_debug_vm_args(vm_args, encoding, windows) {
|
||||
extra.insert("vmArgs".into(), vm_args.into());
|
||||
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
pub async fn debug_set_breakpoints(
|
||||
host: &Host,
|
||||
_window: &str,
|
||||
@@ -355,3 +382,46 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
|c| async move { debug_redefine_classes(&c.host, &c.window, c.arg("session")?).await },
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn launch(adapter: &str, request: &str, extra: serde_json::Value) -> LaunchConfig {
|
||||
LaunchConfig {
|
||||
name: "DromaraApplication".into(),
|
||||
adapter: adapter.into(),
|
||||
request: request.into(),
|
||||
program: None,
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: Default::default(),
|
||||
extra_json: Some(extra.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn vm_args(config: &LaunchConfig) -> serde_json::Value {
|
||||
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()["vmArgs"].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_debug_launches_on_windows_write_utf8() {
|
||||
let extra =
|
||||
serde_json::json!({"mainClass": "org.dromara.DromaraApplication", "vmArgs": "-Xmx1g", "debugServer": 1});
|
||||
let fixed = match_java_debug_encoding(launch("java-debug", "launch", extra.clone()), true);
|
||||
assert_eq!(
|
||||
vm_args(&fixed),
|
||||
"-Xmx1g -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(fixed.extra_json.as_deref().unwrap()).unwrap()["mainClass"],
|
||||
"org.dromara.DromaraApplication"
|
||||
);
|
||||
// Attaching, other adapters and other platforms are left alone.
|
||||
for (adapter, request, windows) in
|
||||
[("java-debug", "attach", true), ("debugpy", "launch", true), ("java-debug", "launch", false)]
|
||||
{
|
||||
assert_eq!(vm_args(&match_java_debug_encoding(launch(adapter, request, extra.clone()), windows)), "-Xmx1g");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,13 @@ pub async fn doc_open_virtual(host: &Host, window: &str, uri: String) -> IdeResu
|
||||
blocking(move || project.documents.open_virtual(&vd.uri, vd.language_id, &vd.text)).await
|
||||
}
|
||||
|
||||
/// The CodeMirror mode `path` gets when opened (`DocumentInfo::ui_mode`),
|
||||
/// without opening it: previews of closed files.
|
||||
pub async fn doc_ui_mode(host: &Host, window: &str, path: PathBuf) -> IdeResult<Option<String>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || Ok(project.documents.ui_mode_of(&path))).await
|
||||
}
|
||||
|
||||
/// "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding label.
|
||||
pub fn doc_set_encoding(host: &Host, window: &str, doc: DocId, encoding: String, reload: bool) -> IdeResult<String> {
|
||||
host.project(window)?.documents.set_encoding(doc, &encoding, reload)
|
||||
@@ -108,6 +115,7 @@ pub fn history_content(host: &Host, window: &str, id: String) -> IdeResult<Strin
|
||||
/// Commands of this module the remote server answers.
|
||||
pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("doc_open_virtual", |c| async move { doc_open_virtual(&c.host, &c.window, c.arg("uri")?).await });
|
||||
d.add("doc_ui_mode", |c| async move { doc_ui_mode(&c.host, &c.window, c.arg("path")?).await });
|
||||
d.add("doc_set_encoding", |c| async move {
|
||||
doc_set_encoding(&c.host, &c.window, c.arg("doc")?, c.arg("encoding")?, c.arg("reload")?)
|
||||
});
|
||||
|
||||
@@ -15,7 +15,9 @@ pub mod history;
|
||||
pub mod java;
|
||||
pub mod lsp;
|
||||
pub mod nav;
|
||||
pub mod notebook;
|
||||
pub mod project;
|
||||
mod python;
|
||||
pub mod refactor;
|
||||
pub mod run;
|
||||
pub mod sdk;
|
||||
@@ -59,6 +61,7 @@ impl<T> Clone for Channel<T> {
|
||||
pub fn register_all(d: &mut crate::rpc::Dispatcher) {
|
||||
agent::register(d);
|
||||
lsp::register(d);
|
||||
notebook::register(d);
|
||||
nav::register(d);
|
||||
refactor::register(d);
|
||||
analysis::register(d);
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
//! Native notebook operations shared by desktop IPC and the remote dispatcher.
|
||||
use crate::Host;
|
||||
pub use crate::notebook::NotebookOutputEvent;
|
||||
use crate::ops::Channel;
|
||||
use crate::rpc::Dispatcher;
|
||||
use ide_core::{IdeError, IdeResult, RequestId};
|
||||
use ide_notebook::{NotebookEdit, NotebookSnapshot};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub async fn open(host: &Host, window: &str, path: String) -> IdeResult<NotebookSnapshot> {
|
||||
let project = host.project(window)?;
|
||||
let path = PathBuf::from(path);
|
||||
let path = if path.is_absolute() { path } else { project.root.join(path) };
|
||||
let notebooks = project.notebooks.clone();
|
||||
host.blocking(move || notebooks.open(&path)).await
|
||||
}
|
||||
|
||||
pub fn get(host: &Host, window: &str, id: String) -> IdeResult<NotebookSnapshot> {
|
||||
host.project(window)?.notebooks.get(&id)
|
||||
}
|
||||
|
||||
pub async fn edit(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
version: u32,
|
||||
edit: NotebookEdit,
|
||||
) -> IdeResult<NotebookSnapshot> {
|
||||
let notebooks = host.project(window)?.notebooks.clone();
|
||||
host.blocking(move || notebooks.edit(&id, version, edit)).await
|
||||
}
|
||||
|
||||
pub async fn save(host: &Host, window: &str, id: String) -> IdeResult<NotebookSnapshot> {
|
||||
let notebooks = host.project(window)?.notebooks.clone();
|
||||
host.blocking(move || notebooks.save(&id)).await
|
||||
}
|
||||
|
||||
pub async fn undo(host: &Host, window: &str, id: String) -> IdeResult<NotebookSnapshot> {
|
||||
let notebooks = host.project(window)?.notebooks.clone();
|
||||
host.blocking(move || notebooks.undo(&id, false)).await
|
||||
}
|
||||
|
||||
pub async fn redo(host: &Host, window: &str, id: String) -> IdeResult<NotebookSnapshot> {
|
||||
let notebooks = host.project(window)?.notebooks.clone();
|
||||
host.blocking(move || notebooks.undo(&id, true)).await
|
||||
}
|
||||
|
||||
pub async fn reload(host: &Host, window: &str, id: String) -> IdeResult<NotebookSnapshot> {
|
||||
let notebooks = host.project(window)?.notebooks.clone();
|
||||
// An abandoned IPC future must not leave a lifecycle transition half applied.
|
||||
tokio::spawn(async move { notebooks.reload(&id, false).await })
|
||||
.await
|
||||
.map_err(|error| IdeError::internal(error.to_string()))?
|
||||
}
|
||||
|
||||
pub async fn restart(host: &Host, window: &str, id: String) -> IdeResult<NotebookSnapshot> {
|
||||
let notebooks = host.project(window)?.notebooks.clone();
|
||||
tokio::spawn(async move { notebooks.reload(&id, true).await })
|
||||
.await
|
||||
.map_err(|error| IdeError::internal(error.to_string()))?
|
||||
}
|
||||
|
||||
pub async fn close(host: &Host, window: &str, id: String) -> IdeResult<()> {
|
||||
let notebooks = host.project(window)?.notebooks.clone();
|
||||
tokio::spawn(async move { notebooks.close(&id).await })
|
||||
.await
|
||||
.map_err(|error| IdeError::internal(error.to_string()))?
|
||||
}
|
||||
|
||||
pub async fn interrupt(host: &Host, window: &str, id: String) -> IdeResult<()> {
|
||||
let notebooks = host.project(window)?.notebooks.clone();
|
||||
tokio::spawn(async move { notebooks.interrupt(&id).await })
|
||||
.await
|
||||
.map_err(|error| IdeError::internal(error.to_string()))?
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn execute(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
cells: Vec<String>,
|
||||
python: Option<String>,
|
||||
request: RequestId,
|
||||
on_output: Channel<NotebookOutputEvent>,
|
||||
) -> IdeResult<NotebookSnapshot> {
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
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 selected = match python {
|
||||
Some(path) if path.trim().is_empty() => return Err(IdeError::invalid("select a Python interpreter")),
|
||||
Some(path) => PathBuf::from(path),
|
||||
None => {
|
||||
let root = project.root.clone();
|
||||
let settings = project.settings.effective();
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
result = host.blocking(move || {
|
||||
ide_sdk::apply::python_interpreter(&root, &settings)
|
||||
.or_else(|| ide_sdk::detect(ide_sdk::SdkKind::Python, Some(&root))
|
||||
.into_iter().next().map(|sdk| sdk.path.into_path_buf()))
|
||||
.ok_or_else(|| IdeError::unavailable("select a Python environment with ipykernel installed"))
|
||||
}) => result?,
|
||||
}
|
||||
}
|
||||
};
|
||||
// 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
|
||||
}
|
||||
|
||||
struct RequestGuard<'a> {
|
||||
host: &'a Host,
|
||||
request: RequestId,
|
||||
cancel: ide_core::CancellationToken,
|
||||
}
|
||||
|
||||
impl Drop for RequestGuard<'_> {
|
||||
fn drop(&mut self) {
|
||||
// If the invocation is dropped, the owned batch still receives cancellation.
|
||||
self.cancel.cancel();
|
||||
self.host.end_request(self.request);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("notebook_open", |c| async move { open(&c.host, &c.window, c.arg("path")?).await });
|
||||
d.add("notebook_get", |c| async move { get(&c.host, &c.window, c.arg("id")?) });
|
||||
d.add("notebook_edit", |c| async move {
|
||||
edit(&c.host, &c.window, c.arg("id")?, c.arg("version")?, c.arg("edit")?).await
|
||||
});
|
||||
d.add("notebook_save", |c| async move { save(&c.host, &c.window, c.arg("id")?).await });
|
||||
d.add("notebook_reload", |c| async move { reload(&c.host, &c.window, c.arg("id")?).await });
|
||||
d.add("notebook_undo", |c| async move { undo(&c.host, &c.window, c.arg("id")?).await });
|
||||
d.add("notebook_redo", |c| async move { redo(&c.host, &c.window, c.arg("id")?).await });
|
||||
d.add("notebook_close", |c| async move { close(&c.host, &c.window, c.arg("id")?).await });
|
||||
d.add("notebook_interrupt", |c| async move { interrupt(&c.host, &c.window, c.arg("id")?).await });
|
||||
d.add("notebook_restart", |c| async move { restart(&c.host, &c.window, c.arg("id")?).await });
|
||||
d.add("notebook_execute", |c| async move {
|
||||
execute(
|
||||
&c.host,
|
||||
&c.window,
|
||||
c.arg("id")?,
|
||||
c.arg("cells")?,
|
||||
c.arg("python")?,
|
||||
c.arg("request")?,
|
||||
c.sender("onOutput")?,
|
||||
)
|
||||
.await
|
||||
});
|
||||
}
|
||||
@@ -129,7 +129,9 @@ pub fn set_settings(
|
||||
host.runtime.spawn(async move { lsp.reconfigure().await });
|
||||
}
|
||||
}
|
||||
let roots_changed = key == "projectStructure" || key.starts_with("projectStructure.");
|
||||
let roots_changed = key == "projectStructure"
|
||||
|| key.starts_with("projectStructure.")
|
||||
|| "languages.java.maven.unlinkedProjects".starts_with(key);
|
||||
// Content roots and excludes (files.exclude, ignored names, excluded folders) reach the
|
||||
// index and the watchers without reopening the project (the rescan runs in the background).
|
||||
if roots_changed || key == "files" || key.starts_with("files.") {
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
use crate::project::Project;
|
||||
use ide_core::IdeResult;
|
||||
use ide_dap::LaunchConfig;
|
||||
use ide_workspace::roots::RootKind;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub(super) fn paths(project: &Project) -> Vec<PathBuf> {
|
||||
let mut paths = vec![project.root.clone()];
|
||||
paths.extend(project.content_roots());
|
||||
for root in project.roots().roots {
|
||||
if matches!(root.kind, RootKind::Source | RootKind::Test) {
|
||||
let path = project.root.join(root.path);
|
||||
if !paths.contains(&path) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
pub(super) fn prepare_debug(config: &mut LaunchConfig, paths: &[PathBuf]) -> 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());
|
||||
// A custom adapter may run on another host; local paths are not portable.
|
||||
if extra.as_ref().is_some_and(|e| e.get("debugServer").is_some()) {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(env) = extra.as_mut().and_then(|e| e.get_mut("env")) {
|
||||
if env.is_null() {
|
||||
*env = serde_json::json!({});
|
||||
}
|
||||
if !env.is_object() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut vars = BTreeMap::new();
|
||||
if let Some(value) = env.get("PYTHONPATH").and_then(|v| v.as_str()) {
|
||||
vars.insert("PYTHONPATH".into(), value.to_owned());
|
||||
}
|
||||
ide_run::python_path::extend(&mut vars, paths, env.get("PYTHONPATH").is_none())?;
|
||||
env["PYTHONPATH"] = serde_json::json!(vars["PYTHONPATH"]);
|
||||
config.extra_json = extra.map(|e| e.to_string());
|
||||
} else {
|
||||
ide_run::python_path::extend(&mut config.env, paths, true)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn debug_preserves_remote_paths_and_handles_null_env() {
|
||||
let root = std::env::temp_dir().join("project");
|
||||
let mut config = LaunchConfig {
|
||||
name: "Python".into(),
|
||||
adapter: "debugpy".into(),
|
||||
request: "launch".into(),
|
||||
program: None,
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: BTreeMap::new(),
|
||||
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)).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)).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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_uses_the_effective_environment_field() {
|
||||
for extra in [false, true] {
|
||||
let root = std::env::temp_dir().join("project");
|
||||
let vendor = root.join("vendor");
|
||||
let vars = BTreeMap::from([("PYTHONPATH".into(), vendor.to_string_lossy().into_owned())]);
|
||||
let mut config = LaunchConfig {
|
||||
name: "Python".into(),
|
||||
adapter: "debugpy".into(),
|
||||
request: "launch".into(),
|
||||
program: Some("app/main.py".into()),
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: vars.clone(),
|
||||
extra_json: extra.then(|| serde_json::json!({"env": vars}).to_string()),
|
||||
};
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root)).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()
|
||||
} else {
|
||||
config.env
|
||||
};
|
||||
assert_eq!(std::env::split_paths(&vars["PYTHONPATH"]).collect::<Vec<_>>(), [root, vendor]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,16 +9,29 @@ pub fn configs(host: &Host, window: &str) -> IdeResult<Vec<RunConfig>> {
|
||||
let project = host.project(window)?;
|
||||
let root = project.root.clone();
|
||||
let user = ide_run::load_user_configs(&root)?;
|
||||
let mut all: Vec<RunConfig> =
|
||||
ide_run::detect(&root).into_iter().filter(|d| !user.iter().any(|u| u.id == d.id)).collect();
|
||||
let suppressed = ide_run::load_suppressed_config_ids(&root)?;
|
||||
let settings = project.settings.effective();
|
||||
let excluded_poms = crate::project::unlinked_maven_poms(&root, &settings);
|
||||
let mut all: Vec<RunConfig> = ide_run::detect_excluding(&root, &excluded_poms)
|
||||
.into_iter()
|
||||
.filter(|d| !suppressed.contains(&d.id) && !user.iter().any(|u| u.id == d.id))
|
||||
.collect();
|
||||
all.extend(user);
|
||||
// Project interpreter / package manager / toolchains from Languages & Frameworks.
|
||||
ide_sdk::apply::apply_to_run_configs(&mut all, &root, &project.settings.effective());
|
||||
// Keep Gradle choices unmodified in the editor: derived defaults must not be saved as explicit env.
|
||||
for config in all.iter_mut().filter(|c| c.kind != "gradle") {
|
||||
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(config), &root, &settings);
|
||||
}
|
||||
Ok(all)
|
||||
}
|
||||
|
||||
pub fn save_configs(host: &Host, window: &str, configs: &[RunConfig]) -> IdeResult<()> {
|
||||
ide_run::save_user_configs(&host.project(window)?.root, configs)
|
||||
pub fn save_configs(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
configs: &[RunConfig],
|
||||
removed_detected_ids: &[String],
|
||||
) -> IdeResult<()> {
|
||||
ide_run::save_user_configs_with_removals(&host.project(window)?.root, configs, removed_detected_ids)
|
||||
}
|
||||
|
||||
pub async fn start(host: &Host, window: &str, config: RunConfig, on_output: Emit<OutputChunk>) -> IdeResult<RunInfo> {
|
||||
@@ -38,12 +51,19 @@ pub async fn start(host: &Host, window: &str, config: RunConfig, on_output: Emit
|
||||
let settings = project.settings.effective();
|
||||
// Configurations made in the UI name bare tools (`godot`) that may live outside PATH.
|
||||
let mut config = config;
|
||||
ide_sdk::apply::resolve_run_command(&mut config, &project.root, &settings);
|
||||
if config.kind == "gradle" {
|
||||
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut config), &project.root, &settings);
|
||||
} else {
|
||||
ide_sdk::apply::resolve_run_command(&mut config, &project.root, &settings);
|
||||
}
|
||||
if config.command == ide_sdk::godot::COMMAND {
|
||||
return Err(IdeError::unavailable(ide_sdk::godot::NOT_FOUND));
|
||||
}
|
||||
let encoding = settings.console.encoding;
|
||||
let options = StartOptions { encoding: Some(encoding).filter(|e| !e.trim().is_empty()) };
|
||||
let options = StartOptions {
|
||||
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
|
||||
python_paths: super::python::paths(&project),
|
||||
};
|
||||
host.processes.start(&project.root, &config, &options, project.sink.clone(), Box::new(move |c| on_output(c)))
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,18 @@ pub fn run_system_env(_host: &Host, _window: &str) -> std::collections::BTreeMap
|
||||
ide_run::system_env()
|
||||
}
|
||||
|
||||
/// Writes the Gradle init script that adds `jvm_args` to the JVMs the build forks
|
||||
/// (`bootRun`, `run`, tests) and returns its path, for `--init-script`.
|
||||
pub async fn run_gradle_jvm_args_script(_host: &Host, _window: &str, jvm_args: Vec<String>) -> IdeResult<String> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
ide_run::gradle_jvm::write_init_script(&ide_run::gradle_jvm::default_dir(), &jvm_args)
|
||||
.map(|p| p.to_string_lossy().into_owned())
|
||||
.map_err(|e| IdeError::internal(format!("cannot write the Gradle init script: {e}")))
|
||||
})
|
||||
.await
|
||||
.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).
|
||||
pub async fn run_test_reports(
|
||||
@@ -42,6 +54,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("run_templates", |c| async move { run_templates(&c.host, &c.window) });
|
||||
d.add("run_save_templates", |c| async move { run_save_templates(&c.host, &c.window, c.arg("templates")?) });
|
||||
d.add("run_system_env", |c| async move { Ok(run_system_env(&c.host, &c.window)) });
|
||||
d.add("run_gradle_jvm_args_script", |c| async move {
|
||||
run_gradle_jvm_args_script(&c.host, &c.window, c.arg("jvmArgs")?).await
|
||||
});
|
||||
d.add("run_test_reports", |c| async move {
|
||||
run_test_reports(&c.host, &c.window, c.arg("module")?, c.arg("sinceMs")?).await
|
||||
});
|
||||
|
||||
@@ -187,18 +187,24 @@ pub async fn vcs_branch_info(host: &Host, window: &str, repo: Option<PathBuf>) -
|
||||
pub fn vcs_line_hunks(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<LineHunk>> {
|
||||
let project = host.project(window)?;
|
||||
let text = project.text_of(&path)?;
|
||||
project.with_repo_of(&path, |r| r.line_hunks(&path, &text, false))
|
||||
project.with_repo_of(&path, |r| r.line_hunks(&path, &text, false, project.vcs_encoding(&path, None)?))
|
||||
}
|
||||
|
||||
pub async fn vcs_file_at(host: &Host, window: &str, path: PathBuf, rev: Option<String>) -> IdeResult<Option<String>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_of(&path, |r| r.file_at(&path, rev.as_deref()))).await
|
||||
blocking(move || {
|
||||
project.with_repo_of(&path, |r| r.file_at(&path, rev.as_deref(), project.vcs_encoding(&path, rev.as_deref())?))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn vcs_blame(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<BlameLine>> {
|
||||
let project = host.project(window)?;
|
||||
let text = project.documents.text_of(&path);
|
||||
blocking(move || project.with_repo_of(&path, |r| r.blame(&path, text.as_deref()))).await
|
||||
blocking(move || {
|
||||
project.with_repo_of(&path, |r| r.blame(&path, text.as_deref(), project.vcs_encoding(&path, None)?))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn vcs_log(host: &Host, window: &str, repo: Option<PathBuf>, query: LogQuery) -> IdeResult<Vec<Commit>> {
|
||||
@@ -242,6 +248,33 @@ pub async fn vcs_stage(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeRes
|
||||
blocking(move || per_repo(&project, &paths, None, |r, paths| r.stage(paths))).await
|
||||
}
|
||||
|
||||
/// Project-host operation (also registered with the remote dispatcher).
|
||||
pub async fn vcs_add_to_ignore(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
paths: Vec<PathBuf>,
|
||||
destination: IgnoreDestination,
|
||||
) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
for path in &paths {
|
||||
if path == &project.root || !path.starts_with(&project.root) {
|
||||
return Err(ide_core::IdeError::invalid("Ignore selection is outside the project"));
|
||||
}
|
||||
}
|
||||
apply_git_executable(&project.settings.effective());
|
||||
let result = ide_vcs::add_to_ignore(&paths, destination);
|
||||
// Exclude may live outside a worktree's watched directory. Refresh filters and UI explicitly.
|
||||
project.watcher.reload_ignore_rules();
|
||||
for (_, watcher) in project.content_watchers.lock().iter() {
|
||||
watcher.reload_ignore_rules();
|
||||
}
|
||||
project.sink.emit(ide_core::IdeEvent::VcsChanged { root: project.root.clone().into() });
|
||||
result.map(|_| ())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn vcs_unstage(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || per_repo(&project, &paths, None, |r, paths| r.unstage(paths))).await
|
||||
@@ -249,7 +282,7 @@ pub async fn vcs_unstage(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeR
|
||||
|
||||
pub async fn vcs_stage_patch(host: &Host, window: &str, patch: String) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo(|r| r.stage_patch(&patch))).await
|
||||
blocking(move || project.with_repo(|r| r.stage_patch(&patch, &|path| project.vcs_encoding(path, Some(":0"))))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_discard(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<()> {
|
||||
@@ -266,7 +299,12 @@ pub async fn vcs_commit(
|
||||
) -> IdeResult<String> {
|
||||
// Commit hooks may run for a long time.
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.commit_with(&message, &options))).await
|
||||
blocking(move || {
|
||||
project.with_repo_at(repo.as_deref(), |r| {
|
||||
r.commit_with(&message, &options, &|path| project.vcs_encoding(path, None))
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn vcs_checkout(
|
||||
@@ -437,12 +475,14 @@ pub async fn vcs_remote(
|
||||
/// The user's side is `ours` (sides swapped during a rebase, as in IDEA).
|
||||
pub async fn vcs_conflict_versions(host: &Host, window: &str, path: PathBuf) -> IdeResult<ide_vcs::MergeVersions> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_of(&path, |r| r.merge_versions(&path))).await
|
||||
blocking(move || project.with_repo_of(&path, |r| r.merge_versions(&path, project.vcs_encoding(&path, Some(":2"))?)))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn vcs_diff_text(host: &Host, window: &str, path: PathBuf, staged: bool) -> IdeResult<String> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_of(&path, |r| r.diff_text(&path, staged))).await
|
||||
blocking(move || project.with_repo_of(&path, |r| r.diff_text(&path, staged, project.vcs_encoding(&path, None)?)))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Line hunks between two arbitrary texts (diff viewer, commit dialog).
|
||||
@@ -454,13 +494,11 @@ pub fn vcs_diff_hunks(_host: &Host, _window: &str, old_text: String, new_text: S
|
||||
/// Indices refer to `vcs_diff_hunks(index_text, worktree_text)`.
|
||||
pub fn vcs_stage_hunks(host: &Host, window: &str, path: PathBuf, hunks: Vec<u32>) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
let current = ide_vfs::load_text(&path)?.text;
|
||||
let encoding = project.vcs_encoding(&path, Some(":0"))?;
|
||||
let current = ide_vfs::load_text_as(&path, encoding.name())?.text;
|
||||
project.with_repo_of(&path, |r| {
|
||||
let index_text = r.file_at(&path, Some(":0"))?.unwrap_or_default();
|
||||
let rel = path.strip_prefix(r.root()).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let selected: Vec<usize> = hunks.iter().map(|&h| h as usize).collect();
|
||||
let patch = ide_vcs::build_partial_patch(&rel, &index_text, ¤t, &selected);
|
||||
if patch.is_empty() { Ok(()) } else { r.stage_patch(&patch) }
|
||||
r.stage_hunks(&path, ¤t, &selected, encoding)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -680,13 +718,17 @@ pub async fn vcs_diff_revisions(
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.diff_revisions(&from, &to))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_create_patch(host: &Host, window: &str, source: PatchSource) -> IdeResult<String> {
|
||||
pub async fn vcs_create_patch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
source: PatchSource,
|
||||
) -> IdeResult<String> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.with_repo(|r| match source {
|
||||
project.with_repo_at(repo.as_deref(), |r| match source {
|
||||
PatchSource::Changes { paths, reverse } => {
|
||||
let paths: Vec<PathBuf> = paths.into_iter().map(Into::into).collect();
|
||||
in_primary_repo(&project, &paths)?;
|
||||
r.create_patch(&paths, reverse)
|
||||
}
|
||||
PatchSource::Commits { commits, reverse } => r.create_commits_patch(&commits, reverse),
|
||||
@@ -695,14 +737,24 @@ pub async fn vcs_create_patch(host: &Host, window: &str, source: PatchSource) ->
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn vcs_patch_preview(host: &Host, window: &str, patch: String) -> IdeResult<Vec<PatchFile>> {
|
||||
pub async fn vcs_patch_preview(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
patch: String,
|
||||
) -> IdeResult<Vec<PatchFile>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo(|r| r.patch_preview(&patch))).await
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.patch_preview(&patch))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_apply_patch(host: &Host, window: &str, patch: String) -> IdeResult<ApplyOutcome> {
|
||||
pub async fn vcs_apply_patch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
patch: String,
|
||||
) -> IdeResult<ApplyOutcome> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo(|r| r.apply_patch(&patch))).await
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.apply_patch(&patch))).await
|
||||
}
|
||||
|
||||
/// Shelve Changes: saves the changes of `paths` as a patch on the shelf and reverts them.
|
||||
@@ -786,6 +838,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("vcs_branches", |c| async move { vcs_branches(&c.host, &c.window, c.arg("repo")?).await });
|
||||
d.add("vcs_stashes", |c| async move { vcs_stashes(&c.host, &c.window, c.arg("repo")?).await });
|
||||
d.add("vcs_stage", |c| async move { vcs_stage(&c.host, &c.window, c.arg("paths")?).await });
|
||||
d.add("vcs_add_to_ignore", |c| async move {
|
||||
vcs_add_to_ignore(&c.host, &c.window, c.arg("paths")?, c.arg("destination")?).await
|
||||
});
|
||||
d.add("vcs_unstage", |c| async move { vcs_unstage(&c.host, &c.window, c.arg("paths")?).await });
|
||||
d.add("vcs_stage_patch", |c| async move { vcs_stage_patch(&c.host, &c.window, c.arg("patch")?).await });
|
||||
d.add("vcs_discard", |c| async move { vcs_discard(&c.host, &c.window, c.arg("paths")?).await });
|
||||
@@ -901,9 +956,16 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("vcs_diff_revisions", |c| async move {
|
||||
vcs_diff_revisions(&c.host, &c.window, c.arg("repo")?, c.arg("from")?, c.arg("to")?).await
|
||||
});
|
||||
d.add("vcs_create_patch", |c| async move { vcs_create_patch(&c.host, &c.window, c.arg("source")?).await });
|
||||
d.add("vcs_patch_preview", |c| async move { vcs_patch_preview(&c.host, &c.window, c.arg("patch")?).await });
|
||||
d.add("vcs_apply_patch", |c| async move { vcs_apply_patch(&c.host, &c.window, c.arg("patch")?).await });
|
||||
d.add("vcs_create_patch", |c| async move {
|
||||
vcs_create_patch(&c.host, &c.window, c.arg("repo")?, c.arg("source")?).await
|
||||
});
|
||||
d.add("vcs_patch_preview", |c| async move {
|
||||
vcs_patch_preview(&c.host, &c.window, c.arg("repo")?, c.arg("patch")?).await
|
||||
});
|
||||
d.add(
|
||||
"vcs_apply_patch",
|
||||
|c| async move { vcs_apply_patch(&c.host, &c.window, c.arg("repo")?, c.arg("patch")?).await },
|
||||
);
|
||||
d.add("vcs_shelve", |c| async move { vcs_shelve(&c.host, &c.window, c.arg("name")?, c.arg("paths")?).await });
|
||||
d.add("vcs_shelves", |c| async move { vcs_shelves(&c.host, &c.window) });
|
||||
d.add("vcs_unshelve", |c| async move { vcs_unshelve(&c.host, &c.window, c.arg("id")?, c.arg("remove")?).await });
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! watchers and the per-project services, opened by [`crate::Host::open_project`].
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, SharedSink};
|
||||
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, LanguageId, SharedSink};
|
||||
use ide_index::ProjectIndex;
|
||||
use ide_language::{FileTypes, LanguageRegistry, SyntaxCache};
|
||||
use ide_lsp::LspManager;
|
||||
@@ -46,6 +46,8 @@ pub struct Project {
|
||||
pub http_history: Arc<ide_http::History>,
|
||||
/// Coding agent tasks (Agents tool window).
|
||||
pub agents: Arc<ide_agent::AgentManager>,
|
||||
/// Native notebooks and owned kernels, scoped to this project incarnation.
|
||||
pub notebooks: Arc<crate::notebook::NotebookService>,
|
||||
pub(crate) watcher: Watcher,
|
||||
/// Watchers of the Project Structure content roots outside the project folder.
|
||||
pub(crate) content_watchers: Mutex<Vec<(PathBuf, Watcher)>>,
|
||||
@@ -79,20 +81,14 @@ impl Host {
|
||||
let post_start = self.environment.project_opened(&root, &sink);
|
||||
let settings = SettingsStore::load(&self.config_dir, Some(&root));
|
||||
let detected_roots = Arc::new(RwLock::new(ide_workspace::roots::detect(&root)));
|
||||
let excludes = exclude_globs(&settings.effective(), &detected_roots.read());
|
||||
let excludes = exclude_globs(&root, &settings.effective(), &detected_roots.read());
|
||||
let extra_roots = content_roots(&settings.effective(), &root);
|
||||
mark("roots");
|
||||
|
||||
// The project's own registry: File Types associations may be project-scoped.
|
||||
let languages = Arc::new(self.languages.fork());
|
||||
languages.set_file_types(FileTypes::from_settings(&settings.effective().files, Some(&root)));
|
||||
let documents = {
|
||||
let languages = languages.clone();
|
||||
Arc::new(Documents::new(
|
||||
sink.clone(),
|
||||
Box::new(move |p: &Path, first: Option<&str>| languages.detect(p, first)),
|
||||
))
|
||||
};
|
||||
let documents = documents(&sink, &languages, Some(&root));
|
||||
documents.set_file_defaults(ide_workspace::FileDefaults::from_settings(&settings.effective(), Some(&root)));
|
||||
let history = Arc::new(LocalHistory::open(&self.data_dir.join("history"), &root)?);
|
||||
{
|
||||
@@ -158,6 +154,8 @@ impl Host {
|
||||
ide_sdk::jdtls::launch_directly(cfg);
|
||||
}
|
||||
ide_sdk::apply::server_protocol_overrides(cfg, &effective);
|
||||
let excluded_poms = unlinked_maven_poms(&root, &effective);
|
||||
ide_sdk::apply::configure_maven_import(cfg, &root, &excluded_poms);
|
||||
}));
|
||||
}
|
||||
{
|
||||
@@ -188,6 +186,7 @@ impl Host {
|
||||
let settings = settings.clone();
|
||||
let index = index.clone();
|
||||
let documents = documents.clone();
|
||||
let languages = languages.clone();
|
||||
let sink = sink.clone();
|
||||
let root = root.clone();
|
||||
let detected_roots = detected_roots.clone();
|
||||
@@ -203,6 +202,12 @@ impl Host {
|
||||
index.update(&changed, &batch.removed);
|
||||
// Atomic saves by external tools surface as `created`.
|
||||
documents.on_disk_changed(&changed);
|
||||
// A framework's root marker (`angular.json`) created or deleted: its
|
||||
// templates gain or lose their mode. Markers in `node_modules` only
|
||||
// count here when the folder isn't excluded (it is by default).
|
||||
if batch.created.iter().chain(&batch.removed).any(|p| languages.is_framework_marker(p)) {
|
||||
documents.redetect_languages();
|
||||
}
|
||||
record_external_changes(&history, &changed, &batch.removed);
|
||||
if !batch.removed.is_empty() {
|
||||
delete_deployed(
|
||||
@@ -221,7 +226,7 @@ impl Host {
|
||||
if *detected_roots.read() != fresh {
|
||||
// Detected excluded folders (`target`, `build`) leave the index too.
|
||||
let effective = settings.effective();
|
||||
index.set_scope(content_roots(&effective, &root), exclude_globs(&effective, &fresh));
|
||||
index.set_scope(content_roots(&effective, &root), exclude_globs(&root, &effective, &fresh));
|
||||
*detected_roots.write() = fresh;
|
||||
sink.emit(IdeEvent::ProjectRootsChanged { root: root.clone().into() });
|
||||
}
|
||||
@@ -229,7 +234,7 @@ impl Host {
|
||||
// A repository was cloned / initialised / removed below the project: its
|
||||
// `.git/HEAD` (the watcher reports nothing else of `.git`) appeared or went.
|
||||
let known = repos.read().roots();
|
||||
let git_dirs = changed.iter().chain(&batch.removed).any(|p| {
|
||||
let git_dirs = changed.iter().chain(&batch.removed).chain(&batch.vcs).any(|p| {
|
||||
let Some(dir) = p.ends_with(".git/HEAD").then(|| p.parent().and_then(Path::parent)).flatten()
|
||||
else {
|
||||
return false;
|
||||
@@ -239,7 +244,10 @@ impl Host {
|
||||
if git_dirs {
|
||||
scan_repositories(&root, &repos, &settings, &sink);
|
||||
}
|
||||
sink.emit(IdeEvent::VcsChanged { root: root.clone().into() });
|
||||
let vcs_moved = batch.vcs.iter().any(|p| vcs_path_changed(p));
|
||||
if git_dirs || vcs_moved {
|
||||
sink.emit(IdeEvent::VcsChanged { root: root.clone().into() });
|
||||
}
|
||||
}),
|
||||
)?
|
||||
};
|
||||
@@ -282,6 +290,10 @@ impl Host {
|
||||
tracing::info!("opened {} in window {window} in {} ms {laps:?}", root.display(), started.elapsed().as_millis());
|
||||
|
||||
let (db, http_history, agents) = self.project_services(&root, &project_key);
|
||||
let notebooks = crate::notebook::NotebookService::new(
|
||||
self.data_dir.join("notebook-runtime").join(uuid::Uuid::new_v4().to_string()),
|
||||
sink.clone(),
|
||||
);
|
||||
ide_agent::registry::maintain(crate::ops::agent::registry_paths(self));
|
||||
let project = Arc::new(Project {
|
||||
root,
|
||||
@@ -301,6 +313,7 @@ impl Host {
|
||||
db,
|
||||
http_history,
|
||||
agents,
|
||||
notebooks,
|
||||
watcher,
|
||||
content_watchers: Mutex::new(content_watchers),
|
||||
_scratch_watcher: scratch_watcher,
|
||||
@@ -375,13 +388,7 @@ impl Host {
|
||||
let effective = settings.effective();
|
||||
let languages = Arc::new(self.languages.fork());
|
||||
languages.set_file_types(FileTypes::from_settings(&effective.files, None));
|
||||
let documents = {
|
||||
let languages = languages.clone();
|
||||
Arc::new(Documents::new(
|
||||
sink.clone(),
|
||||
Box::new(move |p: &Path, first: Option<&str>| languages.detect(p, first)),
|
||||
))
|
||||
};
|
||||
let documents = documents(&sink, &languages, None);
|
||||
documents.set_file_defaults(ide_workspace::FileDefaults::from_settings(&effective, None));
|
||||
let history = Arc::new(LocalHistory::open(&self.data_dir.join("history"), &dir)?);
|
||||
let index = ProjectIndex::unindexed(&dir, languages.clone(), self.syntax(), sink.clone())?;
|
||||
@@ -393,6 +400,10 @@ impl Host {
|
||||
let watcher = light_watcher(&dir, &sink, &documents, &history)?;
|
||||
let project_key = project_key(&dir);
|
||||
let (db, http_history, agents) = self.project_services(&dir, &project_key);
|
||||
let notebooks = crate::notebook::NotebookService::new(
|
||||
self.data_dir.join("notebook-runtime").join(uuid::Uuid::new_v4().to_string()),
|
||||
sink.clone(),
|
||||
);
|
||||
let project = Arc::new(Project {
|
||||
sink,
|
||||
languages,
|
||||
@@ -410,6 +421,7 @@ impl Host {
|
||||
db,
|
||||
http_history,
|
||||
agents,
|
||||
notebooks,
|
||||
watcher,
|
||||
content_watchers: Mutex::new(Vec::new()),
|
||||
_scratch_watcher: None,
|
||||
@@ -440,6 +452,18 @@ impl Project {
|
||||
}
|
||||
}
|
||||
|
||||
/// The documents of a project whose languages and UI modes `languages` detects,
|
||||
/// looking for frameworks' root markers up to `root` (anywhere for loose files).
|
||||
fn documents(sink: &SharedSink, languages: &Arc<LanguageRegistry>, root: Option<&Path>) -> Arc<Documents> {
|
||||
let (detect, modes, root) = (languages.clone(), languages.clone(), root.map(Path::to_path_buf));
|
||||
Arc::new(
|
||||
Documents::new(sink.clone(), Box::new(move |p: &Path, first: Option<&str>| detect.detect(p, first)))
|
||||
.with_ui_mode_detection(Box::new(move |p: &Path, lang: &LanguageId| {
|
||||
modes.framework_ui_mode(lang, p, root.as_deref())
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
fn light_watcher(
|
||||
dir: &Path,
|
||||
sink: &SharedSink,
|
||||
@@ -567,7 +591,7 @@ impl Project {
|
||||
|
||||
/// Effective source / test / resource / excluded roots (detected + Project Structure marks).
|
||||
pub fn roots(&self) -> ProjectRoots {
|
||||
ProjectRoots::compute(self.detected_roots.read().clone(), &self.settings.effective().project_structure)
|
||||
linked_roots(&self.root, &self.settings.effective(), &self.detected_roots.read())
|
||||
}
|
||||
|
||||
/// Where the Maven / Gradle tool windows cache what the build tools reported.
|
||||
@@ -623,7 +647,7 @@ impl Project {
|
||||
|
||||
/// `files.exclude`, the ignored names and the effective excluded roots (user-marked and detected).
|
||||
pub fn exclude_globs(&self) -> Vec<String> {
|
||||
exclude_globs(&self.settings.effective(), &self.detected_roots.read())
|
||||
exclude_globs(&self.root, &self.settings.effective(), &self.detected_roots.read())
|
||||
}
|
||||
|
||||
/// Project Structure content roots besides the project folder (existing directories).
|
||||
@@ -668,11 +692,29 @@ impl Project {
|
||||
}
|
||||
}
|
||||
|
||||
/// Use the open document's selected encoding, or the same detection/settings as opening it.
|
||||
pub fn vcs_encoding(&self, path: &Path, rev: Option<&str>) -> IdeResult<&'static encoding_rs::Encoding> {
|
||||
if let Some(id) = self.documents.by_path(path) {
|
||||
let info = self.documents.snapshot(id)?;
|
||||
return encoding_rs::Encoding::for_label(info.encoding.as_bytes())
|
||||
.ok_or_else(|| ide_core::IdeError::invalid("unknown document encoding"));
|
||||
}
|
||||
let defaults = self.documents.file_defaults();
|
||||
let fallback = defaults.fallback_for(path);
|
||||
if path.exists() {
|
||||
let loaded = ide_vfs::load_text_with_fallback(path, fallback)?;
|
||||
return encoding_rs::Encoding::for_label(loaded.encoding.as_bytes())
|
||||
.ok_or_else(|| ide_core::IdeError::invalid("unknown file encoding"));
|
||||
}
|
||||
let bytes = self.with_repo_of(path, |r| r.file_bytes_at(path, rev))?.unwrap_or_default();
|
||||
Ok(ide_vfs::detect_encoding(&bytes, fallback))
|
||||
}
|
||||
|
||||
/// Current text of `path`: the open buffer when available, else the file on disk.
|
||||
pub fn text_of(&self, path: &Path) -> IdeResult<String> {
|
||||
match self.documents.text_of(path) {
|
||||
Some(text) => Ok(text),
|
||||
None => Ok(ide_vfs::load_text(path)?.text),
|
||||
None => Ok(ide_vfs::load_text_with_fallback(path, self.documents.file_defaults().fallback_for(path))?.text),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -773,9 +815,23 @@ fn content_root_watcher(
|
||||
.ok()
|
||||
}
|
||||
|
||||
fn exclude_globs(settings: &ide_core::settings::Settings, detected: &[SourceFolder]) -> Vec<String> {
|
||||
pub(crate) fn unlinked_maven_poms(root: &Path, settings: &ide_core::settings::Settings) -> Vec<PathBuf> {
|
||||
ide_build::maven::UnlinkedProjects::load(root, &settings.languages.java.maven).poms().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
fn linked_roots(root: &Path, settings: &ide_core::settings::Settings, detected: &[SourceFolder]) -> ProjectRoots {
|
||||
let unlinked = ide_build::maven::UnlinkedProjects::load(root, &settings.languages.java.maven);
|
||||
let detected = detected
|
||||
.iter()
|
||||
.filter(|folder| !folder.detected_from.as_ref().is_some_and(|pom| unlinked.contains(pom)))
|
||||
.cloned()
|
||||
.collect();
|
||||
ProjectRoots::compute(detected, &settings.project_structure)
|
||||
}
|
||||
|
||||
fn exclude_globs(root: &Path, settings: &ide_core::settings::Settings, detected: &[SourceFolder]) -> Vec<String> {
|
||||
let mut globs = settings.file_excludes();
|
||||
globs.extend(ProjectRoots::compute(detected.to_vec(), &settings.project_structure).excluded_globs());
|
||||
globs.extend(linked_roots(root, settings, detected).excluded_globs());
|
||||
globs
|
||||
}
|
||||
|
||||
@@ -906,3 +962,98 @@ pub fn apply_git_executable(settings: &ide_core::settings::Settings) {
|
||||
let exe = settings.vcs.git.executable.trim();
|
||||
ide_vcs::set_git_executable((!exe.is_empty()).then(|| Path::new(exe)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod maven_linkage_tests {
|
||||
#[test]
|
||||
fn unlinked_roots_remain_plain_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
for name in ["a", "b"] {
|
||||
std::fs::create_dir_all(tmp.path().join(name).join("src/main/java")).unwrap();
|
||||
std::fs::write(tmp.path().join(name).join("pom.xml"), "<project/>").unwrap();
|
||||
}
|
||||
std::fs::create_dir_all(tmp.path().join("a/child/src/main/java")).unwrap();
|
||||
std::fs::write(tmp.path().join("a/pom.xml"), "<project><modules><module>child</module></modules></project>")
|
||||
.unwrap();
|
||||
std::fs::write(tmp.path().join("a/child/pom.xml"), "<project/>").unwrap();
|
||||
let detected = ide_workspace::roots::detect(tmp.path());
|
||||
let mut settings = ide_core::settings::Settings::default();
|
||||
settings.languages.java.maven.unlinked_projects.push("a/pom.xml".into());
|
||||
let excluded_poms = super::unlinked_maven_poms(tmp.path(), &settings);
|
||||
assert_eq!(excluded_poms, vec![std::path::PathBuf::from("a/child/pom.xml"), "a/pom.xml".into()]);
|
||||
let configs = ide_run::detect_excluding(tmp.path(), &excluded_poms);
|
||||
assert!(configs.iter().any(|c| c.kind == "maven"));
|
||||
assert!(
|
||||
configs
|
||||
.iter()
|
||||
.filter(|c| c.kind == "maven")
|
||||
.all(|c| { c.cwd.as_ref().is_some_and(|dir| dir.as_ref() == std::path::Path::new("b")) })
|
||||
);
|
||||
let mut server = serde_json::from_value::<ide_language::LanguageServerConfig>(
|
||||
serde_json::json!({"name": "jdtls", "command": "jdtls"}),
|
||||
)
|
||||
.unwrap();
|
||||
ide_sdk::apply::configure_maven_import(&mut server, tmp.path(), &excluded_poms);
|
||||
let options = serde_json::to_value(server.initialization_options).unwrap();
|
||||
let exclusions = options.pointer("/settings/java/import/exclusions").unwrap().as_array().unwrap();
|
||||
assert!(exclusions.contains(&serde_json::json!(tmp.path().join("a").to_string_lossy().replace('\\', "/"))));
|
||||
assert!(
|
||||
exclusions.contains(&serde_json::json!(tmp.path().join("a/child").to_string_lossy().replace('\\', "/")))
|
||||
);
|
||||
let roots = super::linked_roots(tmp.path(), &settings, &detected);
|
||||
assert!(roots.roots.iter().any(|r| r.path == "b/src/main/java"));
|
||||
assert!(!roots.roots.iter().any(|r| r.path.starts_with("a/")));
|
||||
assert!(tmp.path().join("a/pom.xml").is_file());
|
||||
let model = crate::ops::build::load(tmp.path(), &tmp.path().join("cache"), &settings);
|
||||
assert_eq!(model.maven.unwrap().projects.len(), 1);
|
||||
settings.languages.java.maven.unlinked_projects.push("b/pom.xml".into());
|
||||
let model = crate::ops::build::load(tmp.path(), &tmp.path().join("cache"), &settings);
|
||||
assert!(model.maven.unwrap().projects.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
fn vcs_path_changed(path: &Path) -> bool {
|
||||
!path.ends_with(".git/index") || !ide_vcs::is_own_index_write(path)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod index_event_tests {
|
||||
use super::vcs_path_changed;
|
||||
|
||||
#[test]
|
||||
fn status_write_is_suppressed_but_external_index_and_refs_refresh() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let git = |args: &[&str]| {
|
||||
let output = std::process::Command::new("git").current_dir(dir).args(args).output().unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
};
|
||||
git(&["init", "-q"]);
|
||||
let file = dir.join("file.txt");
|
||||
std::fs::write(&file, "original\n").unwrap();
|
||||
git(&["add", "file.txt"]);
|
||||
// Same contents, different stat data: status must refresh the index.
|
||||
std::fs::File::options()
|
||||
.write(true)
|
||||
.open(&file)
|
||||
.unwrap()
|
||||
.set_modified(std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1))
|
||||
.unwrap();
|
||||
let index = dir.join(".git/index");
|
||||
let before = std::fs::read(&index).unwrap();
|
||||
let repo = ide_vcs::Repo::discover(dir).unwrap().unwrap();
|
||||
repo.status().unwrap();
|
||||
assert_ne!(before, std::fs::read(&index).unwrap(), "status must actually write the index");
|
||||
assert!(!vcs_path_changed(&index));
|
||||
assert!(!vcs_path_changed(&index), "duplicate notifications for the same identity");
|
||||
for path in [".git/HEAD", ".git/refs/heads/main", ".git/packed-refs"] {
|
||||
assert!(vcs_path_changed(&dir.join(path)));
|
||||
}
|
||||
std::fs::write(&file, "external staged change\n").unwrap();
|
||||
git(&["add", "file.txt"]);
|
||||
assert!(vcs_path_changed(&index));
|
||||
assert!(vcs_path_changed(&index));
|
||||
std::fs::remove_file(&index).unwrap();
|
||||
assert!(vcs_path_changed(&index));
|
||||
}
|
||||
}
|
||||
@@ -200,7 +200,12 @@ impl Dispatcher {
|
||||
.add("term_available_shells", |_| async move { Ok(ide_terminal::available_shells()) })
|
||||
.add("run_configs", |c| async move { ops::run::configs(&c.host, &c.window) })
|
||||
.add("run_save_configs", |c| async move {
|
||||
ops::run::save_configs(&c.host, &c.window, &c.arg::<Vec<ide_run::RunConfig>>("configs")?)
|
||||
ops::run::save_configs(
|
||||
&c.host,
|
||||
&c.window,
|
||||
&c.arg::<Vec<ide_run::RunConfig>>("configs")?,
|
||||
&c.arg::<Option<Vec<String>>>("removedDetectedIds")?.unwrap_or_default(),
|
||||
)
|
||||
})
|
||||
.add("run_system_env", |_| async move { Ok(ide_run::system_env()) })
|
||||
.add("run_start", |c| async move {
|
||||
|
||||
@@ -109,7 +109,13 @@ fn server_environment_from_login_shell_and_devcontainer() {
|
||||
let started = project.join("started.txt");
|
||||
wait_for("postStartCommand", || std::fs::read_to_string(&started).is_ok_and(|s| s.ends_with('\n')));
|
||||
assert_eq!(std::fs::read_to_string(&started).unwrap(), "two-demo\n");
|
||||
wait_for("the task to end", || events.0.lock().iter().any(|e| matches!(e, IdeEvent::Task { done: true, .. })));
|
||||
wait_for("postStartCommand to end", || {
|
||||
events
|
||||
.0
|
||||
.lock()
|
||||
.iter()
|
||||
.any(|e| matches!(e, IdeEvent::Task { title, done: true, .. } if title == "postStartCommand"))
|
||||
});
|
||||
assert!(events.0.lock().iter().any(
|
||||
|e| matches!(e, IdeEvent::Task { message: Some(m), title, .. } if m == "post-start-output" && title == "postStartCommand")
|
||||
));
|
||||
|
||||
@@ -108,6 +108,26 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
invoke(&peer, "vcs_init", json!({ "dir": project })).await.unwrap();
|
||||
until("git repository", || project.join(".git").is_dir()).await;
|
||||
|
||||
// Real project-host ignore writes travel through the remote command dispatcher.
|
||||
assert!(Dispatcher::standard().commands().contains(&"vcs_add_to_ignore"));
|
||||
let ignore_root = dunce::canonicalize(&project).unwrap();
|
||||
for (name, destination) in [("shared.tmp", "gitignore"), ("private.tmp", "localExclude")] {
|
||||
let path = ignore_root.join(name);
|
||||
std::fs::write(&path, "temporary").unwrap();
|
||||
invoke(&peer, "vcs_add_to_ignore", json!({ "paths": [path], "destination": destination })).await.unwrap();
|
||||
let entries = invoke(&peer, "fs_read_dir", json!({ "path": ignore_root })).await.unwrap();
|
||||
let entry = entries.as_array().unwrap().iter().find(|e| e["name"] == name).unwrap();
|
||||
assert_eq!(entry["ignored"], true);
|
||||
assert_eq!(entry["excluded"], false);
|
||||
}
|
||||
assert!(std::fs::read_to_string(project.join(".gitignore")).unwrap().contains("/shared.tmp"));
|
||||
assert!(std::fs::read_to_string(project.join(".git/info/exclude")).unwrap().contains("/private.tmp"));
|
||||
let outside = tmp.path().join("outside.tmp");
|
||||
std::fs::write(&outside, "keep").unwrap();
|
||||
assert!(
|
||||
invoke(&peer, "vcs_add_to_ignore", json!({ "paths": [outside], "destination": "gitignore" })).await.is_err()
|
||||
);
|
||||
|
||||
// Unknown commands and bad arguments come back as IdeErrors.
|
||||
let e = invoke(&peer, "window_minimize", json!({})).await.unwrap_err();
|
||||
assert!(e.message.contains("not available remotely"), "{e:?}");
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
use ide_core::NullSink;
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn host(base: &std::path::Path) -> Arc<Host> {
|
||||
Arc::new(Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
}))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn removed_detections_stay_removed_and_overrides_restore() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::write(root.join("package.json"), r#"{"scripts":{"dev":"node app.js","test":"node test.js"}}"#).unwrap();
|
||||
let host = host(&root.join("app"));
|
||||
host.open_project("main", &root).unwrap();
|
||||
let detected = ops::run::configs(&host, "main").unwrap();
|
||||
assert!(detected.len() >= 2);
|
||||
assert!(detected.iter().all(|c| c.detected));
|
||||
let id = detected[0].id.clone();
|
||||
ops::run::save_configs(&host, "main", &[], std::slice::from_ref(&id)).unwrap();
|
||||
let remaining = ops::run::configs(&host, "main").unwrap();
|
||||
assert!(!remaining.iter().any(|c| c.id == id));
|
||||
assert_eq!(remaining.len(), detected.len() - 1);
|
||||
// Reopening a project reads suppression from disk.
|
||||
host.open_project("again", &root).unwrap();
|
||||
assert!(!ops::run::configs(&host, "again").unwrap().iter().any(|c| c.id == id));
|
||||
let mut saved = detected[0].clone();
|
||||
saved.detected = false;
|
||||
ops::run::save_configs(&host, "main", &[saved], &[]).unwrap();
|
||||
assert!(ide_run::load_suppressed_config_ids(&root).unwrap().is_empty());
|
||||
assert!(!ops::run::configs(&host, "main").unwrap().iter().find(|c| c.id == id).unwrap().detected);
|
||||
ops::run::save_configs(&host, "main", &[], &[]).unwrap();
|
||||
assert!(ops::run::configs(&host, "main").unwrap().iter().find(|c| c.id == id).unwrap().detected);
|
||||
// An override may coexist with suppression (e.g. a shared file added elsewhere).
|
||||
ops::run::save_configs(&host, "main", &[], std::slice::from_ref(&id)).unwrap();
|
||||
std::fs::write(
|
||||
ide_run::user_configs_path(&root),
|
||||
format!("[[configurations]]\nid = {id:?}\nname = \"Override\"\ncommand = \"node\"\n"),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(ops::run::configs(&host, "main").unwrap().iter().any(|c| c.id == id && !c.detected));
|
||||
ops::run::save_configs(&host, "main", &[], &[]).unwrap();
|
||||
assert!(!ops::run::configs(&host, "main").unwrap().iter().any(|c| c.id == id));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn gradle_defaults_are_not_saved_as_explicit_run_choices() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::write(root.join("build.gradle"), "plugins { id 'java' }").unwrap();
|
||||
let host = host(&root.join("app"));
|
||||
host.open_project("main", &root).unwrap();
|
||||
ops::project::set_settings(
|
||||
&host,
|
||||
"main",
|
||||
ide_workspace::settings::SettingsScope::Project,
|
||||
"languages.java.gradle.jvm",
|
||||
"\"/configured-jdk\"",
|
||||
)
|
||||
.unwrap();
|
||||
let configs = ops::run::configs(&host, "main").unwrap();
|
||||
let mut gradle = configs.into_iter().find(|c| c.kind == "gradle").unwrap();
|
||||
assert!(!gradle.env.contains_key("JAVA_HOME"));
|
||||
gradle.detected = false;
|
||||
gradle.env.insert("JAVA_HOME".into(), "/explicit-jdk".into());
|
||||
ops::run::save_configs(&host, "main", &[gradle.clone()], &[]).unwrap();
|
||||
let saved = ops::run::configs(&host, "main").unwrap().into_iter().find(|c| c.id == gradle.id).unwrap();
|
||||
assert_eq!(saved.env["JAVA_HOME"], "/explicit-jdk");
|
||||
assert_eq!(saved.command, gradle.command);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
use ide_core::{ChangeSet, NullSink, TextChange};
|
||||
use ide_host::{Host, HostConfig, ops::vcs};
|
||||
use std::{path::Path, process::Command, sync::Arc, time::Duration};
|
||||
|
||||
fn git(root: &Path, args: &[&str]) {
|
||||
let out = Command::new("git").current_dir(root).args(args).output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
git(&root, &["init", "-b", "main"]);
|
||||
git(&root, &["config", "user.name", "Test"]);
|
||||
git(&root, &["config", "user.email", "[email protected]"]);
|
||||
git(&root, &["config", "commit.gpgsign", "false"]);
|
||||
git(&root, &["config", "core.autocrlf", "false"]);
|
||||
let path = root.join("Example.java");
|
||||
let old = "// 中文注释\nclass Example {\n // 保持不变\n int value = 1;\n}\n";
|
||||
let original = ide_vfs::encode(old, "gbk", false).unwrap();
|
||||
std::fs::write(&path, &original).unwrap();
|
||||
std::fs::write(root.join("Utf8.java"), old).unwrap();
|
||||
git(&root, &["add", "."]);
|
||||
git(&root, &["commit", "-m", "GBK Java"]);
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
for _ in 0..500 {
|
||||
if !project.repos().is_empty() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
let mut defaults = project.documents.file_defaults();
|
||||
defaults.project_fallback = "gbk".into();
|
||||
project.documents.set_file_defaults(defaults);
|
||||
assert_eq!(project.text_of(&path).unwrap(), old);
|
||||
assert_eq!(vcs::vcs_file_at(&host, "main", path.clone(), None).await.unwrap().as_deref(), Some(old));
|
||||
let doc = project.documents.open(&path).unwrap();
|
||||
assert_eq!(doc.encoding, "gbk");
|
||||
// A live document's explicit selection wins over later project defaults.
|
||||
let mut defaults = project.documents.file_defaults();
|
||||
defaults.project_fallback = "windows-1252".into();
|
||||
project.documents.set_file_defaults(defaults);
|
||||
assert!(vcs::vcs_line_hunks(&host, "main", path.clone()).unwrap().is_empty());
|
||||
let from = old.find("value = 1").unwrap() + "value = ".len();
|
||||
let offset = old[..from].encode_utf16().count() as u32;
|
||||
project
|
||||
.documents
|
||||
.edit(
|
||||
doc.id,
|
||||
doc.version,
|
||||
ChangeSet { changes: vec![TextChange { from: offset, to: offset + 1, insert: "2".into() }] },
|
||||
)
|
||||
.unwrap();
|
||||
let hunks = vcs::vcs_line_hunks(&host, "main", path.clone()).unwrap();
|
||||
assert_eq!(hunks.len(), 1);
|
||||
assert_eq!((hunks[0].start, hunks[0].lines), (3, 1));
|
||||
assert_eq!(hunks[0].old_text, " int value = 1;\n");
|
||||
project.documents.save(doc.id).unwrap();
|
||||
vcs::vcs_stage_hunks(&host, "main", path.clone(), vec![0]).unwrap();
|
||||
let repo = ide_vcs::Repo::discover(&root).unwrap().unwrap();
|
||||
assert_eq!(
|
||||
repo.file_bytes_at(&path, Some(":0")).unwrap().unwrap(),
|
||||
ide_vfs::encode(&old.replace("value = 1", "value = 2"), "gbk", false).unwrap()
|
||||
);
|
||||
repo.unstage(std::slice::from_ref(&path)).unwrap();
|
||||
let snapshot = project.documents.snapshot(doc.id).unwrap();
|
||||
let line_start =
|
||||
snapshot.text.split_inclusive('\n').take(3).map(|s| s.encode_utf16().count()).sum::<usize>() as u32;
|
||||
project
|
||||
.documents
|
||||
.edit(
|
||||
doc.id,
|
||||
snapshot.version,
|
||||
ChangeSet {
|
||||
changes: vec![TextChange {
|
||||
from: line_start,
|
||||
to: line_start + " int value = 2;\n".encode_utf16().count() as u32,
|
||||
insert: hunks[0].old_text.clone(),
|
||||
}],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
project.documents.save(doc.id).unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), original);
|
||||
assert!(vcs::vcs_line_hunks(&host, "main", path.clone()).unwrap().is_empty());
|
||||
assert!(vcs::vcs_blame(&host, "main", path.clone()).await.unwrap().iter().all(|l| l.author == "Test"));
|
||||
// Missing working files still use configured encoding for historical content.
|
||||
project.documents.close(doc.id);
|
||||
let mut defaults = project.documents.file_defaults();
|
||||
defaults.project_fallback = "gbk".into();
|
||||
project.documents.set_file_defaults(defaults);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert_eq!(vcs::vcs_file_at(&host, "main", path, None).await.unwrap().as_deref(), Some(old));
|
||||
let utf8 = root.join("Utf8.java");
|
||||
std::fs::remove_file(&utf8).unwrap();
|
||||
assert_eq!(vcs::vcs_file_at(&host, "main", utf8, None).await.unwrap().as_deref(), Some(old));
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//! Repository-scoped patch operations must never fall back to the primary root.
|
||||
use ide_core::NullSink;
|
||||
use ide_host::{Host, HostConfig, ops::vcs};
|
||||
use std::{path::Path, process::Command, sync::Arc, time::Duration};
|
||||
|
||||
fn git(root: &Path, args: &[&str]) -> String {
|
||||
let output = Command::new("git").current_dir(root).args(args).output().unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
String::from_utf8(output.stdout).unwrap().trim().to_owned()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn patches_read_and_write_the_requested_repository() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let project_root = base.join("project");
|
||||
let roots = [project_root.join("front"), project_root.join("back")];
|
||||
let mut revisions = Vec::new();
|
||||
for (i, root) in roots.iter().enumerate() {
|
||||
std::fs::create_dir_all(root).unwrap();
|
||||
git(root, &["init", "-b", "main"]);
|
||||
git(root, &["config", "user.name", "Test"]);
|
||||
git(root, &["config", "user.email", "[email protected]"]);
|
||||
std::fs::write(root.join("same.txt"), format!("root {i}\n")).unwrap();
|
||||
git(root, &["add", "."]);
|
||||
git(root, &["commit", "-m", "initial"]);
|
||||
std::fs::write(root.join("same.txt"), format!("changed {i}\n")).unwrap();
|
||||
git(root, &["commit", "-am", "change"]);
|
||||
revisions.push(git(root, &["rev-parse", "HEAD"]));
|
||||
}
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
let project = host.open_project("main", &project_root).unwrap();
|
||||
for _ in 0..500 {
|
||||
if project.repos().all().len() == 2 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(project.repos().all().len(), 2);
|
||||
for (i, root) in roots.iter().enumerate() {
|
||||
let patch = vcs::vcs_create_patch(
|
||||
&host,
|
||||
"main",
|
||||
Some(root.clone()),
|
||||
vcs::PatchSource::Commits { commits: vec![revisions[i].clone()], reverse: true },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(patch.contains(&format!("-changed {i}")));
|
||||
assert_eq!(vcs::vcs_patch_preview(&host, "main", Some(root.clone()), patch.clone()).await.unwrap().len(), 1);
|
||||
vcs::vcs_apply_patch(&host, "main", Some(root.clone()), patch).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(root.join("same.txt")).unwrap(), format!("root {i}\n"));
|
||||
}
|
||||
assert!(vcs::vcs_apply_patch(&host, "main", Some(base.join("outside")), String::new()).await.is_err());
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -332,6 +332,25 @@ impl Drop for KillOnDrop {
|
||||
}
|
||||
}
|
||||
|
||||
/// The program [`Peer::spawn_framed`] runs: a bare name resolved against the
|
||||
/// child's `PATH` (a caller's `env` PATH, else the login shell's, else ours), so
|
||||
/// that on Windows `PATHEXT` names (`codex` → `codex.cmd`) start; anything else
|
||||
/// is kept as given.
|
||||
fn resolve_spawn_program(command: &str, env: &[(String, String)]) -> std::path::PathBuf {
|
||||
let path = std::path::Path::new(command);
|
||||
if path.components().count() > 1 || path.is_absolute() {
|
||||
return path.to_path_buf();
|
||||
}
|
||||
let search = env
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
.map(|(_, v)| std::ffi::OsString::from(v))
|
||||
.or_else(|| ide_core::process::shell_env().find(|(k, _)| k == "PATH").map(|(_, v)| v))
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"))
|
||||
.unwrap_or_default();
|
||||
ide_core::process::find_executable(command, &search).unwrap_or_else(|| path.to_path_buf())
|
||||
}
|
||||
|
||||
impl Peer {
|
||||
/// Spawns `command` and speaks JSON-RPC over its stdio. Stderr lines, and
|
||||
/// stdout lines that are not part of a message (a launcher's own output), are
|
||||
@@ -360,7 +379,10 @@ impl Peer {
|
||||
framing: Framing,
|
||||
) -> std::io::Result<Self> {
|
||||
use std::process::Stdio;
|
||||
let mut cmd = tokio::process::Command::new(command);
|
||||
// Windows resolves a bare name only as `.exe`; find the file a child
|
||||
// would (`PATH` × `PATHEXT`, e.g. `codex` → `codex.cmd`) first.
|
||||
let resolved = resolve_spawn_program(command, env);
|
||||
let mut cmd = tokio::process::Command::new(&resolved);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
cmd.args(args)
|
||||
.current_dir(cwd)
|
||||
|
||||
@@ -58,6 +58,7 @@ tree-sitter-gdscript = "6.1.0"
|
||||
|
||||
[dev-dependencies]
|
||||
criterion = { version = "0.5", default-features = false }
|
||||
tempfile.workspace = true
|
||||
|
||||
[[bench]]
|
||||
name = "syntax"
|
||||
|
||||
@@ -9,8 +9,10 @@ use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
mod markers;
|
||||
mod registry;
|
||||
mod syntax;
|
||||
pub use markers::marked_root;
|
||||
pub use registry::{FileTypes, LanguageRegistry};
|
||||
pub use syntax::{
|
||||
CSS_CLASS, CSS_ID, CSS_VARIABLE, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES,
|
||||
@@ -41,6 +43,10 @@ pub struct LanguageConfig {
|
||||
/// Name of the CodeMirror/Lezer language the UI should load for instant highlighting.
|
||||
#[serde(default)]
|
||||
pub ui_mode: Option<String>,
|
||||
/// Modes replacing `ui_mode` in a framework's projects (Angular templates);
|
||||
/// the first one whose root marker is found applies.
|
||||
#[serde(default)]
|
||||
pub framework_ui_modes: Vec<FrameworkUiMode>,
|
||||
#[serde(default)]
|
||||
pub tree_sitter: Option<String>,
|
||||
#[serde(default)]
|
||||
@@ -49,6 +55,17 @@ pub struct LanguageConfig {
|
||||
pub debugger: Option<DebuggerConfig>,
|
||||
}
|
||||
|
||||
/// A CodeMirror mode for the files of a framework's projects.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub struct FrameworkUiMode {
|
||||
pub ui_mode: String,
|
||||
/// Files whose presence in a directory above a file, up to the project
|
||||
/// folder, marks the framework's project, e.g. `angular.json`; matched like
|
||||
/// language servers' `root-markers`.
|
||||
pub root_markers: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all(serialize = "camelCase", deserialize = "kebab-case"))]
|
||||
pub struct IndentConfig {
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
//! Root markers: files whose presence in a directory marks a tool's or a
|
||||
//! framework's project there (`Cargo.toml`, `angular.json`). Language server
|
||||
//! roots (`root-markers`) and framework modes (`framework-ui-modes`) share them.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The outermost ancestor of `file` containing a root marker, within
|
||||
/// `project_root` (any ancestor without one: loose files).
|
||||
pub fn marked_root(project_root: Option<&Path>, file: &Path, markers: &[String]) -> Option<PathBuf> {
|
||||
let mut best = None;
|
||||
for dir in file.ancestors().skip(1) {
|
||||
if project_root.is_some_and(|root| !dir.starts_with(root)) {
|
||||
break;
|
||||
}
|
||||
if markers.iter().any(|m| has_marker(dir, m)) {
|
||||
best = Some(dir.to_path_buf());
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// `dir` contains `marker`: a relative path, or a file name pattern with one
|
||||
/// `*` (`*.csproj`).
|
||||
fn has_marker(dir: &Path, marker: &str) -> bool {
|
||||
let Some((prefix, suffix)) = marker.split_once('*') else {
|
||||
return dir.join(marker).exists();
|
||||
};
|
||||
std::fs::read_dir(dir).is_ok_and(|entries| {
|
||||
entries.flatten().any(|e| matches_pattern(&e.file_name().to_string_lossy(), prefix, suffix))
|
||||
})
|
||||
}
|
||||
|
||||
/// `path` is (or, after its creation or removal, was) a root marker of the
|
||||
/// directory above it.
|
||||
pub(crate) fn is_marker_path(path: &Path, marker: &str) -> bool {
|
||||
match marker.split_once('*') {
|
||||
None => path.ends_with(marker),
|
||||
Some((prefix, suffix)) => {
|
||||
path.file_name().is_some_and(|name| matches_pattern(&name.to_string_lossy(), prefix, suffix))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn matches_pattern(name: &str, prefix: &str, suffix: &str) -> bool {
|
||||
name.len() >= prefix.len() + suffix.len() && name.starts_with(prefix) && name.ends_with(suffix)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn marked_root_needs_a_marker() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let file = root.join("apps/web/src/app.ts");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
let markers = vec!["angular.json".to_string(), "node_modules/@angular/core".to_string()];
|
||||
assert_eq!(marked_root(Some(root), &file, &markers), None);
|
||||
std::fs::create_dir_all(root.join("apps/web/node_modules/@angular/core")).unwrap();
|
||||
assert_eq!(marked_root(Some(root), &file, &markers), Some(root.join("apps/web")));
|
||||
assert_eq!(marked_root(Some(root), &root.join("apps/api/main.ts"), &markers), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markers_above_the_project_root_only_count_without_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (home, project) = (tmp.path(), tmp.path().join("work/site"));
|
||||
let file = project.join("src/index.html");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::create_dir_all(home.join("node_modules/@angular/core")).unwrap();
|
||||
let markers = vec!["node_modules/@angular/core".to_string()];
|
||||
assert_eq!(marked_root(Some(&project), &file, &markers), None);
|
||||
assert_eq!(marked_root(None, &file, &markers), Some(home.to_path_buf()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patterns_match_file_names() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
std::fs::write(dir.join("App.csproj"), "").unwrap();
|
||||
assert!(has_marker(dir, "*.csproj") && has_marker(dir, "App.*") && !has_marker(dir, "*.fsproj"));
|
||||
assert!(is_marker_path(&dir.join("App.csproj"), "*.csproj"));
|
||||
assert!(is_marker_path(Path::new("/p/web/node_modules/@angular/core"), "node_modules/@angular/core"));
|
||||
assert!(is_marker_path(Path::new("/p/web/angular.json"), "angular.json"));
|
||||
assert!(!is_marker_path(Path::new("/p/web/angular.json.bak"), "angular.json"));
|
||||
assert!(!is_marker_path(Path::new("/p/core"), "node_modules/@angular/core"));
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use std::sync::Arc;
|
||||
|
||||
/// Built-in definitions, embedded at compile time. Add new languages here.
|
||||
const BUILTIN: &[(&str, &str)] = &[
|
||||
("bat", include_str!("../../../languages/bat.toml")),
|
||||
("c", include_str!("../../../languages/c.toml")),
|
||||
("clojure", include_str!("../../../languages/clojure.toml")),
|
||||
("cmake", include_str!("../../../languages/cmake.toml")),
|
||||
@@ -276,6 +277,27 @@ impl LanguageRegistry {
|
||||
self.languages.iter().find(|l| &l.id == id).cloned()
|
||||
}
|
||||
|
||||
/// The `framework-ui-modes` mode of a `language` file at `path`: the first
|
||||
/// whose root marker is in a directory above it, up to `project_root` (any
|
||||
/// directory without one: loose files). `None` keeps the language's own
|
||||
/// `ui-mode`.
|
||||
pub fn framework_ui_mode(&self, language: &LanguageId, path: &Path, project_root: Option<&Path>) -> Option<String> {
|
||||
let cfg = self.languages.iter().find(|l| &l.id == language)?;
|
||||
cfg.framework_ui_modes
|
||||
.iter()
|
||||
.find(|f| crate::marked_root(project_root, path, &f.root_markers).is_some())
|
||||
.map(|f| f.ui_mode.clone())
|
||||
}
|
||||
|
||||
/// Creating or removing `path` can change a file's `framework_ui_mode`:
|
||||
/// it is a framework's root marker.
|
||||
pub fn is_framework_marker(&self, path: &Path) -> bool {
|
||||
self.languages
|
||||
.iter()
|
||||
.flat_map(|l| &l.framework_ui_modes)
|
||||
.any(|f| f.root_markers.iter().any(|m| crate::markers::is_marker_path(path, m)))
|
||||
}
|
||||
|
||||
/// Detects by Override File Type, exact file name, then file-name pattern
|
||||
/// (`Dockerfile.*`), then extension (longest compound first, e.g. `d.ts`),
|
||||
/// then hashbang / first line; falls back to plaintext. The user's patterns
|
||||
@@ -348,8 +370,10 @@ mod tests {
|
||||
use super::*;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// `name`s exported by `@codemirror/language-data` (the UI resolves `ui-mode` against these).
|
||||
/// `name`s exported by `@codemirror/language-data` or built into `src/editor/core/cm/languages.ts`
|
||||
/// (the UI resolves `ui-mode` against these).
|
||||
const UI_MODES: &[&str] = &[
|
||||
"Batch",
|
||||
"C",
|
||||
"C++",
|
||||
"CQL",
|
||||
@@ -511,6 +535,7 @@ mod tests {
|
||||
assert_eq!(reg.detect(Path::new("script"), Some("#!/usr/bin/env python3")).as_str(), "python");
|
||||
assert_eq!(detect(®, "README"), "plaintext");
|
||||
assert_eq!(detect(®, "unknown.zzz"), "plaintext");
|
||||
assert_eq!(reg.get(&LanguageId::new("bat")).unwrap().line_comment.as_deref(), Some("@REM"));
|
||||
let rust = reg.get(&LanguageId::new("rust")).unwrap();
|
||||
assert_eq!(rust.language_servers[0].name, "rust-analyzer");
|
||||
}
|
||||
@@ -552,6 +577,37 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn html_of_angular_projects_is_an_angular_template() {
|
||||
let reg = reg();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let mode = |lang: &str, file: &str| reg.framework_ui_mode(&LanguageId::new(lang), &root.join(file), Some(root));
|
||||
std::fs::create_dir_all(root.join("apps/web/node_modules/@angular/core")).unwrap();
|
||||
std::fs::create_dir_all(root.join("apps/admin")).unwrap();
|
||||
std::fs::write(root.join("apps/admin/angular.json"), "{}").unwrap();
|
||||
assert_eq!(mode("html", "apps/web/src/app/app.html").as_deref(), Some("Angular Template"));
|
||||
assert_eq!(mode("html", "apps/admin/src/index.html").as_deref(), Some("Angular Template"));
|
||||
assert_eq!(mode("html", "docs/index.html"), None);
|
||||
assert_eq!(mode("typescript", "apps/web/src/app/app.ts"), None);
|
||||
assert!(reg.is_framework_marker(&root.join("apps/admin/angular.json")));
|
||||
assert!(!reg.is_framework_marker(&root.join("apps/admin/package.json")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markers_outside_the_project_do_not_make_angular_templates() {
|
||||
let reg = reg();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// A stray `~/node_modules/@angular/core` above an unrelated project.
|
||||
std::fs::create_dir_all(tmp.path().join("node_modules/@angular/core")).unwrap();
|
||||
let project = tmp.path().join("work/site");
|
||||
let page = project.join("index.html");
|
||||
assert_eq!(reg.framework_ui_mode(&LanguageId::new("html"), &page, Some(&project)), None);
|
||||
// Loose files (LightEdit) have no project to stop at.
|
||||
let loose = reg.framework_ui_mode(&LanguageId::new("html"), &page, None);
|
||||
assert_eq!(loose.as_deref(), Some("Angular Template"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_builtin_file_is_registered_and_parses() {
|
||||
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../languages");
|
||||
@@ -621,7 +677,8 @@ mod tests {
|
||||
fn ui_modes_exist_in_codemirror_language_data() {
|
||||
for (name, src) in BUILTIN {
|
||||
let cfg = parse(src).unwrap();
|
||||
if let Some(mode) = &cfg.ui_mode {
|
||||
let framework_modes = cfg.framework_ui_modes.iter().map(|f| &f.ui_mode);
|
||||
for mode in cfg.ui_mode.iter().chain(framework_modes) {
|
||||
assert!(UI_MODES.contains(&mode.as_str()), "{name}: ui-mode {mode:?} is not a language-data name");
|
||||
}
|
||||
}
|
||||
@@ -679,6 +736,8 @@ mod tests {
|
||||
("deploy.sh", "shellscript"),
|
||||
(".zshrc", "shellscript"),
|
||||
("Build.ps1", "powershell"),
|
||||
("build.bat", "bat"),
|
||||
("run.cmd", "bat"),
|
||||
("schema.sql", "sql"),
|
||||
("api.http", "http"),
|
||||
("api.rest", "http"),
|
||||
|
||||
@@ -21,7 +21,6 @@ futures.workspace = true
|
||||
globset.workspace = true
|
||||
toml.workspace = true
|
||||
percent-encoding = "2"
|
||||
which = "8"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
@@ -1176,6 +1176,40 @@ mod tests {
|
||||
assert!(matches!(back.text_edit, Some(lsp::CompletionTextEdit::InsertAndReplace(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdtls_completion_defaults_preserve_prefix_range_and_edit_text() {
|
||||
// JDT.LS 1.63: request after `System.out.` or `System.out.Print`.
|
||||
for end in [19, 24] {
|
||||
let (_, items) = parse_completion_response(json!({
|
||||
"isIncomplete": false,
|
||||
"itemDefaults": {
|
||||
"editRange": {
|
||||
"insert": {"start": {"line":2,"character":19}, "end": {"line":2,"character":end}},
|
||||
"replace": {"start": {"line":2,"character":19}, "end": {"line":2,"character":end}}
|
||||
},
|
||||
"insertTextFormat": 2,
|
||||
"data": {"completionKinds": [2, 6]}
|
||||
},
|
||||
"items": [{
|
||||
"label": "print",
|
||||
"labelDetails": {"detail": "(Object obj)", "description": "void"},
|
||||
"kind": 2,
|
||||
"detail": "PrintStream.print(Object obj) : void",
|
||||
"filterText": "print(Object obj) : void",
|
||||
"insertText": "print",
|
||||
"textEditText": "print(${0});",
|
||||
"data": {"pid": "0", "rid": "0"}
|
||||
}]
|
||||
}));
|
||||
let item = completion_item(&Conv::utf16(), Path::new("/Main.java"), items[0].clone(), ServerId(1));
|
||||
assert_eq!(item.replace_range, Some(Range::new(p(2, 19), p(2, end))));
|
||||
assert_eq!(item.replace_range_tab, None);
|
||||
assert_eq!(item.filter_text.as_deref(), Some("print(Object obj) : void"));
|
||||
assert_eq!(item.insert_text, "print(${0});");
|
||||
assert!(item.is_snippet);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hover_normalisation() {
|
||||
let conv = Conv::utf16();
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! Starting server processes: binary resolution and the [`Launcher`] seam.
|
||||
|
||||
use ide_core::CancellationToken;
|
||||
use ide_core::tool_path::search_path;
|
||||
use ide_jsonrpc::{Handler, Peer};
|
||||
use ide_language::LanguageServerConfig;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum LaunchError {
|
||||
@@ -72,8 +73,7 @@ impl Launcher for ProcessLauncher {
|
||||
cancel: &CancellationToken,
|
||||
) -> Result<Peer, LaunchError> {
|
||||
let search = server_search_path(config);
|
||||
let binary = which::which_in(&config.command, Some(&search), root)
|
||||
.ok()
|
||||
let binary = ide_core::tool_path::find_command(&config.command, &search, root)
|
||||
.and_then(|b| resolve_rustup_proxy(&config.command, b));
|
||||
let mut env: Vec<(String, String)> = vec![("PATH".into(), search.to_string_lossy().into_owned())];
|
||||
env.extend(config.env.iter().filter(|(k, _)| *k != "PATH").map(|(k, v)| (k.clone(), v.clone())));
|
||||
@@ -95,7 +95,7 @@ impl Launcher for ProcessLauncher {
|
||||
}
|
||||
|
||||
fn available(&self, config: &LanguageServerConfig, root: &Path) -> bool {
|
||||
which::which_in(&config.command, Some(server_search_path(config)), root).is_ok()
|
||||
ide_core::tool_path::find_command(&config.command, &server_search_path(config), root).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,9 +104,6 @@ fn server_search_path(config: &LanguageServerConfig) -> OsString {
|
||||
config.env.get("PATH").map(OsString::from).unwrap_or_else(search_path)
|
||||
}
|
||||
|
||||
/// `PATH` plus the login shell's `PATH` and common tool directories, so
|
||||
/// servers resolve even when the app is launched from a GUI shell with a
|
||||
/// minimal environment.
|
||||
/// `~/.cargo/bin/<tool>` is usually a rustup proxy that fails when the active
|
||||
/// toolchain lacks the component (common for rust-analyzer). In that case use
|
||||
/// the newest installed toolchain that ships the binary; with none, the tool is
|
||||
@@ -153,74 +150,6 @@ fn resolve_rustup_proxy(command: &str, binary: PathBuf) -> Option<PathBuf> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn search_path() -> OsString {
|
||||
static PATH: OnceLock<OsString> = OnceLock::new();
|
||||
PATH.get_or_init(|| {
|
||||
let mut dirs: Vec<PathBuf> =
|
||||
std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
|
||||
if let Some(shell_path) = login_shell_path() {
|
||||
dirs.extend(std::env::split_paths(&shell_path));
|
||||
}
|
||||
if let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from) {
|
||||
for rel in [".cargo/bin", ".local/bin", "go/bin", ".bun/bin", ".deno/bin", ".npm-global/bin", ".volta/bin"]
|
||||
{
|
||||
dirs.push(home.join(rel));
|
||||
}
|
||||
// nvm: newest installed node's bin.
|
||||
if let Ok(entries) = std::fs::read_dir(home.join(".nvm/versions/node")) {
|
||||
let mut versions: Vec<PathBuf> = entries.flatten().map(|e| e.path().join("bin")).collect();
|
||||
versions.sort();
|
||||
dirs.extend(versions.into_iter().rev());
|
||||
}
|
||||
}
|
||||
for d in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"] {
|
||||
dirs.push(PathBuf::from(d));
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
dirs.retain(|d| !d.as_os_str().is_empty() && seen.insert(d.clone()));
|
||||
std::env::join_paths(dirs).unwrap_or_default()
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn login_shell_path() -> Option<OsString> {
|
||||
use std::io::Read;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
let shell = std::env::var_os("SHELL")?;
|
||||
const MARK: &str = "__OPENIDEA_PATH__";
|
||||
let mut child = ide_core::process::prepare(&mut Command::new(shell))
|
||||
.args(["-l", "-c", &format!("printf '{MARK}%s{MARK}' \"$PATH\"")])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.ok()?;
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(_)) => break,
|
||||
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(10)),
|
||||
_ => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
child.stdout.take()?.read_to_string(&mut out).ok()?;
|
||||
let start = out.find(MARK)? + MARK.len();
|
||||
let end = start + out[start..].find(MARK)?;
|
||||
Some(OsString::from(&out[start..end]))
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn login_shell_path() -> Option<OsString> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Workspace root for `file`: the outermost ancestor within `project_root`
|
||||
/// containing a root marker (so a Cargo/npm workspace gets one server, not one
|
||||
/// per member), else `project_root`. `None` when `file` is outside the project.
|
||||
@@ -231,32 +160,10 @@ pub fn find_root(project_root: &Path, file: &Path, markers: &[String]) -> Option
|
||||
Some(marked_root(project_root, file, markers).unwrap_or_else(|| project_root.to_path_buf()))
|
||||
}
|
||||
|
||||
/// The outermost ancestor of `file` within `project_root` containing a root marker.
|
||||
/// The outermost ancestor of `file` within `project_root` containing a root
|
||||
/// marker (the same lookup as `framework-ui-modes`).
|
||||
pub fn marked_root(project_root: &Path, file: &Path, markers: &[String]) -> Option<PathBuf> {
|
||||
let mut best = None;
|
||||
for dir in file.ancestors().skip(1) {
|
||||
if !dir.starts_with(project_root) {
|
||||
break;
|
||||
}
|
||||
if markers.iter().any(|m| has_marker(dir, m)) {
|
||||
best = Some(dir.to_path_buf());
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
fn has_marker(dir: &Path, marker: &str) -> bool {
|
||||
if !marker.contains('*') {
|
||||
return dir.join(marker).exists();
|
||||
}
|
||||
let (prefix, suffix) = marker.split_once('*').unwrap_or((marker, ""));
|
||||
std::fs::read_dir(dir).is_ok_and(|entries| {
|
||||
entries.flatten().any(|e| {
|
||||
let name = e.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
name.len() >= prefix.len() + suffix.len() && name.starts_with(prefix) && name.ends_with(suffix)
|
||||
})
|
||||
})
|
||||
ide_language::marked_root(Some(project_root), file, markers)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -24,7 +24,7 @@ mod uri;
|
||||
mod virtual_doc;
|
||||
|
||||
pub use inspect::{FileInspection, InspectHost, InspectOptions};
|
||||
pub use launch::{LaunchError, Launcher, ProcessLauncher, search_path};
|
||||
pub use launch::{LaunchError, Launcher, ProcessLauncher};
|
||||
pub use scope::{CandidateFiles, CandidateFn, CandidateQuery, MAX_CANDIDATES};
|
||||
pub use uri::{is_virtual_uri, path_to_uri_string, uri_target, uri_to_path};
|
||||
|
||||
@@ -218,8 +218,17 @@ fn user_did_open(server: &Server, run: &Running, path: &Path, uri: &lsp::Uri, pa
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported(feature: &str) -> IdeError {
|
||||
IdeError::unavailable(format!("no running language server supports {feature}"))
|
||||
/// No target for `feature`: names the running servers that lack it, so the UI can
|
||||
/// tell "the server can't do this" from "no server is running" (the UI's
|
||||
/// `unavailableText` matches the "… doesn't support …" wording).
|
||||
fn unsupported(servers: &[Arc<Server>], feature: &str) -> IdeError {
|
||||
let running: Vec<&str> = servers.iter().filter(|s| s.running().is_some()).map(|s| s.name.as_str()).collect();
|
||||
if running.is_empty() {
|
||||
IdeError::unavailable(format!("no running language server supports {feature}"))
|
||||
} else {
|
||||
let servers = running.join(", ");
|
||||
IdeError::unavailable(format!("{servers} doesn't support {feature}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds per-server results: any success wins over errors; errors surface only
|
||||
@@ -830,7 +839,7 @@ impl LspManager {
|
||||
let snap = self.snapshot(doc)?;
|
||||
let targets = self.ready_targets(&snap.servers, pred).await;
|
||||
if targets.is_empty() {
|
||||
return Err(unsupported(feature));
|
||||
return Err(unsupported(&snap.servers, feature));
|
||||
}
|
||||
Ok((snap, targets))
|
||||
}
|
||||
@@ -1183,7 +1192,7 @@ impl LspManager {
|
||||
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
|
||||
let targets = self.ready_targets(&servers, |c| c.has("workspaceSymbolProvider")).await;
|
||||
if targets.is_empty() {
|
||||
return Err(unsupported("workspace symbols"));
|
||||
return Err(unsupported(&servers, "workspace symbols"));
|
||||
}
|
||||
let requests = targets.iter().map(|t| {
|
||||
let cancel = &cancel;
|
||||
@@ -1912,9 +1921,22 @@ impl LspManager {
|
||||
/// Servers no longer enabled stop; newly enabled ones attach to open documents.
|
||||
pub async fn reconfigure(&self) {
|
||||
self.stop_unlisted().await;
|
||||
let Some(me) = self.me.upgrade() else { return };
|
||||
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
|
||||
for s in servers {
|
||||
let next = self.configured(&s);
|
||||
// The settings hook may run tools (`npm root -g`), as when the server starts.
|
||||
let next = match tokio::task::spawn_blocking({
|
||||
let (me, s) = (me.clone(), s.clone());
|
||||
move || me.configured(&s)
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(next) => next,
|
||||
Err(e) => {
|
||||
tracing::warn!("{}: settings hook failed: {e}", s.name);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let current = s.effective_config();
|
||||
if next == current {
|
||||
continue;
|
||||
|
||||
@@ -245,6 +245,7 @@ fn harness_configured(
|
||||
block_comment: None,
|
||||
indent: None,
|
||||
ui_mode: None,
|
||||
framework_ui_modes: Vec::new(),
|
||||
tree_sitter: None,
|
||||
language_servers: servers
|
||||
.iter()
|
||||
@@ -520,6 +521,20 @@ async fn inline_completion_only_from_servers_that_advertise_it() {
|
||||
assert!(plain.requested("textDocument/inlineCompletion").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn unsupported_feature_names_the_running_servers_that_lack_it() {
|
||||
let h = harness(&[("plain", incremental_caps()), ("other", json!({ "textDocumentSync": 2 }))]);
|
||||
let (doc, _) = h.open("a.mk", "let x = fo");
|
||||
for name in ["plain", "other"] {
|
||||
h.wait_status(name, ServerStatus::Ready).await;
|
||||
}
|
||||
let e = h.mgr.inline_completion(doc, Pos::new(0, 10), false, Default::default()).await.unwrap_err();
|
||||
assert_eq!(e.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert_eq!(e.message, "plain, other doesn't support inline completion");
|
||||
let e = h.mgr.type_hierarchy(doc, Pos::new(0, 4), HierarchyDirection::Incoming).await.unwrap_err();
|
||||
assert_eq!(e.message, "plain, other doesn't support type hierarchy");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn diagnostics_become_events_and_feed_code_actions() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
|
||||
@@ -54,6 +54,7 @@ fn lang(id: &str, ext: &str, server: LanguageServerConfig) -> LanguageConfig {
|
||||
block_comment: None,
|
||||
indent: None,
|
||||
ui_mode: None,
|
||||
framework_ui_modes: Vec::new(),
|
||||
tree_sitter: None,
|
||||
language_servers: vec![server],
|
||||
debugger: None,
|
||||
@@ -296,7 +297,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
|
||||
|
||||
/// Vue Language Server 3 in hybrid mode: its `tsserver/request`s go through the
|
||||
/// client to vtsls with `@vue/typescript-plugin` (issue #25). Set
|
||||
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vue/language-server typescript@"<7" @vtsls/language-server`.
|
||||
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vue/language-server typescript@6 @vtsls/language-server`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires @vue/language-server and @vtsls/language-server (OPENIDEA_TEST_NPM_TOOLS)"]
|
||||
async fn vue_hybrid_mode_end_to_end() {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "ide-notebook"
|
||||
description = "Lossless native notebook documents and owned Jupyter kernels"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
ide-core.workspace = true
|
||||
ide-vfs.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
specta-typescript.workspace = true
|
||||
uuid.workspace = true
|
||||
tokio.workspace = true
|
||||
futures.workspace = true
|
||||
parking_lot.workspace = true
|
||||
tracing.workspace = true
|
||||
jupyter-zmq-client.workspace = true
|
||||
jupyter-protocol.workspace = true
|
||||
zeromq.workspace = true
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Threading", "Win32_System_JobObjects", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Memory"] }
|
||||
|
||||
@@ -0,0 +1,988 @@
|
||||
//! Lossless nbformat 4 documents. Runtime identities and execution bookkeeping
|
||||
//! never leak into existing notebook JSON. Only explicit mutations alter bytes.
|
||||
mod raw;
|
||||
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use ide_core::{IdeError, IdeResult, error::ErrorKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use specta::Type;
|
||||
use uuid::Uuid;
|
||||
|
||||
use self::raw::{Layout, Member, Node};
|
||||
use crate::kernel::KernelOutput;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NotebookSnapshot {
|
||||
pub id: String,
|
||||
pub path: String,
|
||||
pub version: u32,
|
||||
pub dirty: bool,
|
||||
pub can_undo: bool,
|
||||
pub can_redo: bool,
|
||||
pub nbformat: u32,
|
||||
pub nbformat_minor: u32,
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
pub metadata: Value,
|
||||
pub cells: Vec<NotebookCell>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NotebookCell {
|
||||
pub id: String,
|
||||
pub cell_type: String,
|
||||
pub source: String,
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
pub metadata: Value,
|
||||
#[specta(type = Vec<specta_typescript::Unknown>)]
|
||||
pub outputs: Vec<Value>,
|
||||
pub execution_count: Option<u32>,
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
pub attachments: Value,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum NotebookEdit {
|
||||
SetSource {
|
||||
cell: String,
|
||||
source: String,
|
||||
},
|
||||
InsertCell {
|
||||
after: Option<String>,
|
||||
cell_type: String,
|
||||
},
|
||||
DeleteCell {
|
||||
cell: String,
|
||||
},
|
||||
MoveCell {
|
||||
cell: String,
|
||||
before: Option<String>,
|
||||
},
|
||||
SetCellType {
|
||||
cell: String,
|
||||
cell_type: String,
|
||||
},
|
||||
SetOutputs {
|
||||
cell: String,
|
||||
#[specta(type = Vec<specta_typescript::Unknown>)]
|
||||
outputs: Vec<Value>,
|
||||
execution_count: Option<u32>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CellState {
|
||||
id: String,
|
||||
display_ids: Vec<Option<String>>,
|
||||
pending_clear: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Fields {
|
||||
values: Vec<(String, Option<Member>)>,
|
||||
order: Vec<String>,
|
||||
layout: Layout,
|
||||
}
|
||||
|
||||
impl Fields {
|
||||
fn capture(node: &Node, keys: &[&str]) -> Self {
|
||||
let members = node.members().expect("validated cell object");
|
||||
Self {
|
||||
values: keys.iter().map(|key| ((*key).into(), members.iter().find(|m| m.key == *key).cloned())).collect(),
|
||||
order: members.iter().map(|m| m.key.clone()).collect(),
|
||||
layout: node.layout(),
|
||||
}
|
||||
}
|
||||
|
||||
fn restore(&self, node: &mut Node) {
|
||||
node.restore_fields(&self.values, &self.order, &self.layout);
|
||||
}
|
||||
}
|
||||
|
||||
enum Change {
|
||||
Fields { cell: String, before: Fields, after: Fields },
|
||||
Insert { index: usize, node: Node, state: CellState, before: Layout, after: Layout },
|
||||
Delete { index: usize, node: Node, state: CellState, before: Layout, after: Layout },
|
||||
Move { from: usize, to: usize, before: Layout, after: Layout },
|
||||
}
|
||||
|
||||
struct History {
|
||||
change: Change,
|
||||
typing_cell: Option<String>,
|
||||
time: Instant,
|
||||
}
|
||||
|
||||
/// The caller serializes short document operations, not kernel awaits. Batch
|
||||
/// admission belongs to the host; set_execution_active protects backend history.
|
||||
pub struct NotebookDocument {
|
||||
id: String,
|
||||
path: PathBuf,
|
||||
root: Node,
|
||||
prefix: String,
|
||||
suffix: String,
|
||||
baseline: Node,
|
||||
baseline_text: Arc<str>,
|
||||
cells: Vec<CellState>,
|
||||
version: u32,
|
||||
last_user_revision: u32,
|
||||
undo: Vec<History>,
|
||||
redo: Vec<History>,
|
||||
execution_active: bool,
|
||||
}
|
||||
|
||||
impl NotebookDocument {
|
||||
pub fn load(path: &Path) -> IdeResult<Self> {
|
||||
let text = std::fs::read_to_string(path)?;
|
||||
Self::from_text(path.to_path_buf(), text)
|
||||
}
|
||||
|
||||
pub fn from_text(path: PathBuf, text: String) -> IdeResult<Self> {
|
||||
let text: Arc<str> = text.into();
|
||||
let (root, prefix, suffix) = Node::parse(text.clone())?;
|
||||
validate_notebook(&root)?;
|
||||
let nodes = root.get("cells").and_then(Node::array).expect("validated cells");
|
||||
let mut persisted = HashMap::<String, usize>::new();
|
||||
for node in nodes {
|
||||
if let Some(id) = string_field(node, "id").filter(|id| valid_id(id)) {
|
||||
*persisted.entry(id.to_owned()).or_default() += 1;
|
||||
}
|
||||
}
|
||||
let mut used: HashSet<String> = persisted.keys().cloned().collect();
|
||||
let cells = nodes
|
||||
.iter()
|
||||
.map(|node| {
|
||||
let id = string_field(node, "id")
|
||||
.filter(|id| valid_id(id) && persisted.get(*id) == Some(&1))
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| unique_id(&mut used));
|
||||
let outputs = node.get("outputs").and_then(Node::array).map_or(0, <[Node]>::len);
|
||||
CellState { id, display_ids: vec![None; outputs], pending_clear: false }
|
||||
})
|
||||
.collect();
|
||||
Ok(Self {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
path,
|
||||
baseline: root.clone(),
|
||||
root,
|
||||
prefix,
|
||||
suffix,
|
||||
baseline_text: text,
|
||||
cells,
|
||||
version: 1,
|
||||
last_user_revision: 1,
|
||||
undo: Vec::new(),
|
||||
redo: Vec::new(),
|
||||
execution_active: false,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> NotebookSnapshot {
|
||||
NotebookSnapshot {
|
||||
id: self.id.clone(),
|
||||
path: self.path.to_string_lossy().into_owned(),
|
||||
version: self.version,
|
||||
dirty: self.is_dirty(),
|
||||
can_undo: !self.execution_active && !self.undo.is_empty(),
|
||||
can_redo: !self.execution_active && !self.redo.is_empty(),
|
||||
nbformat: uint_field(&self.root, "nbformat").expect("validated format"),
|
||||
nbformat_minor: uint_field(&self.root, "nbformat_minor").expect("validated minor"),
|
||||
metadata: self.root.get("metadata").expect("validated metadata").value(),
|
||||
cells: self
|
||||
.nodes()
|
||||
.iter()
|
||||
.zip(&self.cells)
|
||||
.map(|(node, state)| NotebookCell {
|
||||
id: state.id.clone(),
|
||||
cell_type: string_field(node, "cell_type").expect("validated type").into(),
|
||||
source: source(node).expect("validated source"),
|
||||
metadata: node.get("metadata").map_or_else(|| json!({}), Node::value),
|
||||
outputs: node
|
||||
.get("outputs")
|
||||
.and_then(Node::array)
|
||||
.map_or_else(Vec::new, |items| items.iter().map(Node::value).collect()),
|
||||
execution_count: uint_field(node, "execution_count"),
|
||||
attachments: node.get("attachments").map_or_else(|| json!({}), Node::value),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Byte equality, not a sticky flag. Unchanged raw siblings short-circuit
|
||||
/// without serializing the notebook on each source edit or output chunk.
|
||||
pub fn is_dirty(&self) -> bool {
|
||||
!self.root.same_bytes(&self.baseline)
|
||||
}
|
||||
|
||||
/// The host uses these cheap fields for high-volume output events.
|
||||
pub fn version(&self) -> u32 {
|
||||
self.version
|
||||
}
|
||||
pub fn id(&self) -> &str {
|
||||
&self.id
|
||||
}
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
||||
/// Intended for save/export and behavioral tests, not per-chunk IPC.
|
||||
pub fn to_text(&self) -> String {
|
||||
let mut text = String::with_capacity(self.baseline_text.len());
|
||||
text.push_str(&self.prefix);
|
||||
self.root.write(&mut text);
|
||||
text.push_str(&self.suffix);
|
||||
text
|
||||
}
|
||||
|
||||
pub fn save(&mut self) -> IdeResult<NotebookSnapshot> {
|
||||
let disk = std::fs::read(&self.path).map_err(|error| {
|
||||
if error.kind() == std::io::ErrorKind::NotFound {
|
||||
out_of_sync("Notebook file was removed; reload or save a separate copy before overwriting")
|
||||
} else {
|
||||
error.into()
|
||||
}
|
||||
})?;
|
||||
if disk != self.baseline_text.as_bytes() {
|
||||
return Err(out_of_sync("Notebook changed on disk; reload or save a separate copy before overwriting"));
|
||||
}
|
||||
if self.is_dirty() {
|
||||
let text = self.to_text();
|
||||
ide_vfs::write_atomic_strict(&self.path, text.as_bytes())?;
|
||||
self.baseline_text = text.into();
|
||||
self.baseline = self.root.clone();
|
||||
}
|
||||
// A save is a typing-group boundary; undo after it must become dirty.
|
||||
self.break_typing_group();
|
||||
Ok(self.snapshot())
|
||||
}
|
||||
|
||||
pub fn reload(&mut self) -> IdeResult<NotebookSnapshot> {
|
||||
self.require_inactive()?;
|
||||
self.ensure_revision()?;
|
||||
let mut replacement = Self::load(&self.path)?;
|
||||
replacement.id.clone_from(&self.id);
|
||||
replacement.version = self.version + 1;
|
||||
replacement.last_user_revision = replacement.version;
|
||||
*self = replacement;
|
||||
Ok(self.snapshot())
|
||||
}
|
||||
|
||||
pub fn set_execution_active(&mut self, active: bool) -> IdeResult<()> {
|
||||
if active && self.execution_active {
|
||||
return Err(IdeError::invalid("Notebook already has an active execution batch"));
|
||||
}
|
||||
self.execution_active = active;
|
||||
self.break_typing_group();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn nodes(&self) -> &[Node] {
|
||||
self.root.get("cells").and_then(Node::array).expect("validated cells")
|
||||
}
|
||||
fn array_mut(&mut self) -> &mut Node {
|
||||
self.root.get_mut("cells").expect("validated cells")
|
||||
}
|
||||
fn cell_mut(&mut self, index: usize) -> &mut Node {
|
||||
self.array_mut().item_mut(index)
|
||||
}
|
||||
fn index(&self, id: &str) -> IdeResult<usize> {
|
||||
self.cells
|
||||
.iter()
|
||||
.position(|cell| cell.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("Notebook cell {id} no longer exists")))
|
||||
}
|
||||
fn ensure_revision(&self) -> IdeResult<()> {
|
||||
if self.version == u32::MAX {
|
||||
Err(IdeError::unavailable("Notebook revision limit reached; save and reopen the document"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn require_inactive(&self) -> IdeResult<()> {
|
||||
if self.execution_active {
|
||||
Err(IdeError::invalid("Stop and drain notebook execution before undo, redo, or reload"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn break_typing_group(&mut self) {
|
||||
if let Some(last) = self.undo.last_mut() {
|
||||
last.typing_cell = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn out_of_sync(message: &str) -> IdeError {
|
||||
IdeError::new(ErrorKind::OutOfSync, message)
|
||||
}
|
||||
fn string_field<'a>(node: &'a Node, key: &str) -> Option<&'a str> {
|
||||
node.get(key)?.string()
|
||||
}
|
||||
fn uint_field(node: &Node, key: &str) -> Option<u32> {
|
||||
node.get(key)?.uint()
|
||||
}
|
||||
fn valid_id(id: &str) -> bool {
|
||||
!id.is_empty() && id.len() <= 64 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||
}
|
||||
fn unique_id(used: &mut HashSet<String>) -> String {
|
||||
loop {
|
||||
let id = Uuid::new_v4().to_string();
|
||||
if used.insert(id.clone()) {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn text_value(value: &Value) -> IdeResult<String> {
|
||||
match value {
|
||||
Value::String(text) => Ok(text.clone()),
|
||||
Value::Array(parts) => {
|
||||
let mut text = String::new();
|
||||
for part in parts {
|
||||
text.push_str(
|
||||
part.as_str().ok_or_else(|| IdeError::invalid("Notebook text arrays must contain only strings"))?,
|
||||
);
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
_ => Err(IdeError::invalid("Notebook source/text must be a string or string array")),
|
||||
}
|
||||
}
|
||||
|
||||
fn source(node: &Node) -> IdeResult<String> {
|
||||
match node.get("source") {
|
||||
Some(value) => node_text(value),
|
||||
None if !matches!(string_field(node, "cell_type"), Some("code" | "markdown" | "raw")) => Ok(String::new()),
|
||||
None => Err(IdeError::invalid("Notebook cell source is missing")),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_notebook(root: &Node) -> IdeResult<()> {
|
||||
if root.members().is_none()
|
||||
|| uint_field(root, "nbformat") != Some(4)
|
||||
|| uint_field(root, "nbformat_minor").is_none()
|
||||
{
|
||||
return Err(IdeError::invalid(
|
||||
"Only nbformat 4 notebooks with a nonnegative integer minor version are supported; the file has not been modified",
|
||||
));
|
||||
}
|
||||
if root.get("metadata").is_none_or(|n| n.members().is_none()) {
|
||||
return Err(IdeError::invalid("Notebook metadata must be an object"));
|
||||
}
|
||||
let cells =
|
||||
root.get("cells").and_then(Node::array).ok_or_else(|| IdeError::invalid("Notebook cells must be an array"))?;
|
||||
for node in cells {
|
||||
if node.members().is_none() || string_field(node, "cell_type").is_none() {
|
||||
return Err(IdeError::invalid("Notebook cells must be objects with a string cell_type"));
|
||||
}
|
||||
let known = matches!(string_field(node, "cell_type"), Some("code" | "markdown" | "raw"));
|
||||
match node.get("source") {
|
||||
Some(value) => validate_text_node(value)?,
|
||||
None if known => return Err(IdeError::invalid("Notebook cell source is missing")),
|
||||
None => {}
|
||||
}
|
||||
if known && node.get("metadata").is_none() {
|
||||
return Err(IdeError::invalid("Notebook cell metadata is missing"));
|
||||
}
|
||||
if let Some(metadata) = node.get("metadata")
|
||||
&& metadata.members().is_none()
|
||||
{
|
||||
return Err(IdeError::invalid("Cell metadata must be an object"));
|
||||
}
|
||||
if let Some(attachments) = node.get("attachments")
|
||||
&& attachments.members().is_none()
|
||||
{
|
||||
return Err(IdeError::invalid("Cell attachments must be an object"));
|
||||
}
|
||||
if let Some(outputs) = node.get("outputs") {
|
||||
let outputs = outputs.array().ok_or_else(|| IdeError::invalid("Cell outputs must be an array"))?;
|
||||
for output in outputs {
|
||||
validate_output_node(output)?;
|
||||
}
|
||||
}
|
||||
if let Some(count) = node.get("execution_count")
|
||||
&& !count.is_null()
|
||||
&& uint_field(node, "execution_count").is_none()
|
||||
{
|
||||
return Err(IdeError::invalid("Cell execution_count must be null or a nonnegative 32-bit integer"));
|
||||
}
|
||||
if string_field(node, "cell_type") == Some("code")
|
||||
&& (node.get("outputs").is_none() || node.get("execution_count").is_none())
|
||||
{
|
||||
return Err(IdeError::invalid("Code cells require outputs and execution_count"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl NotebookDocument {
|
||||
pub fn edit(&mut self, base_version: u32, edit: NotebookEdit) -> IdeResult<NotebookSnapshot> {
|
||||
if base_version < self.last_user_revision || base_version > self.version {
|
||||
return Err(out_of_sync("Notebook was edited elsewhere; refresh and rebase pending edits"));
|
||||
}
|
||||
self.ensure_revision()?;
|
||||
if let NotebookEdit::SetOutputs { cell, outputs, execution_count } = edit {
|
||||
let index = self.code_index(&cell)?;
|
||||
let outputs = outputs.into_iter().map(persisted_output).collect::<IdeResult<Vec<_>>>()?;
|
||||
let node = Node::new(Value::Array(outputs));
|
||||
for output in node.array().expect("outputs array") {
|
||||
validate_output_node(output)?;
|
||||
}
|
||||
let count = Node::new(json!(execution_count));
|
||||
let changed = !self.nodes()[index].get("outputs").expect("code outputs").same_bytes(&node)
|
||||
|| !self.nodes()[index].get("execution_count").expect("code count").same_bytes(&count);
|
||||
if changed {
|
||||
let len = node.array().expect("outputs array").len();
|
||||
self.cell_mut(index).set("outputs", Some(node));
|
||||
self.cell_mut(index).set("execution_count", Some(count));
|
||||
self.cells[index].display_ids = vec![None; len];
|
||||
self.cells[index].pending_clear = false;
|
||||
self.version += 1;
|
||||
}
|
||||
return Ok(self.snapshot());
|
||||
}
|
||||
let typing_cell = match &edit {
|
||||
NotebookEdit::SetSource { cell, .. } => Some(cell.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let change = match edit {
|
||||
NotebookEdit::SetSource { cell, source: text } => {
|
||||
let index = self.index(&cell)?;
|
||||
if self.nodes()[index].get("source").is_some_and(|old| text_matches(old, &text)) {
|
||||
return Ok(self.snapshot());
|
||||
}
|
||||
let before = Fields::capture(&self.nodes()[index], &["source"]);
|
||||
let value = rewritten_source(self.nodes()[index].get("source"), text);
|
||||
self.cell_mut(index).set("source", Some(value));
|
||||
let after = Fields::capture(&self.nodes()[index], &["source"]);
|
||||
Change::Fields { cell, before, after }
|
||||
}
|
||||
NotebookEdit::InsertCell { after, cell_type } => {
|
||||
validate_cell_type(&cell_type)?;
|
||||
let index = after.map_or(Ok(0), |id| self.index(&id).map(|index| index + 1))?;
|
||||
let id = unique_id(&mut self.cells.iter().map(|state| state.id.clone()).collect());
|
||||
let mut value = json!({ "cell_type": cell_type, "metadata": {}, "source": [] });
|
||||
if uint_field(&self.root, "nbformat_minor").expect("minor") >= 5 {
|
||||
value["id"] = json!(id);
|
||||
}
|
||||
if value["cell_type"] == "code" {
|
||||
value["outputs"] = json!([]);
|
||||
value["execution_count"] = Value::Null;
|
||||
}
|
||||
let node = Node::new(value);
|
||||
let state = CellState { id, display_ids: Vec::new(), pending_clear: false };
|
||||
let before = self.root.get("cells").expect("cells").layout();
|
||||
self.array_mut().insert(index, node.clone());
|
||||
self.cells.insert(index, state.clone());
|
||||
let after = self.root.get("cells").expect("cells").layout();
|
||||
Change::Insert { index, node, state, before, after }
|
||||
}
|
||||
NotebookEdit::DeleteCell { cell } => {
|
||||
let index = self.index(&cell)?;
|
||||
let before = self.root.get("cells").expect("cells").layout();
|
||||
let node = self.array_mut().remove(index);
|
||||
let state = self.cells.remove(index);
|
||||
let after = self.root.get("cells").expect("cells").layout();
|
||||
Change::Delete { index, node, state, before, after }
|
||||
}
|
||||
NotebookEdit::MoveCell { cell, before: target } => {
|
||||
let from = self.index(&cell)?;
|
||||
let target = target.map_or(Ok(self.cells.len()), |id| self.index(&id))?;
|
||||
let to = if target > from { target - 1 } else { target };
|
||||
if from == to {
|
||||
return Ok(self.snapshot());
|
||||
}
|
||||
let before = self.root.get("cells").expect("cells").layout();
|
||||
self.move_cell(from, to);
|
||||
let after = self.root.get("cells").expect("cells").layout();
|
||||
Change::Move { from, to, before, after }
|
||||
}
|
||||
NotebookEdit::SetCellType { cell, cell_type } => {
|
||||
validate_cell_type(&cell_type)?;
|
||||
let index = self.index(&cell)?;
|
||||
if string_field(&self.nodes()[index], "cell_type") == Some(cell_type.as_str()) {
|
||||
return Ok(self.snapshot());
|
||||
}
|
||||
let keys = ["cell_type", "outputs", "execution_count"];
|
||||
let before = Fields::capture(&self.nodes()[index], &keys);
|
||||
let node = self.cell_mut(index);
|
||||
node.set("cell_type", Some(Node::new(json!(cell_type))));
|
||||
if cell_type == "code" {
|
||||
node.set("outputs", Some(Node::new(json!([]))));
|
||||
node.set("execution_count", Some(Node::new(Value::Null)));
|
||||
} else {
|
||||
node.set("outputs", None);
|
||||
node.set("execution_count", None);
|
||||
}
|
||||
self.cells[index].display_ids.clear();
|
||||
self.cells[index].pending_clear = false;
|
||||
let after = Fields::capture(&self.nodes()[index], &keys);
|
||||
Change::Fields { cell, before, after }
|
||||
}
|
||||
NotebookEdit::SetOutputs { .. } => unreachable!("output edits handled above"),
|
||||
};
|
||||
self.version += 1;
|
||||
self.last_user_revision = self.version;
|
||||
self.redo.clear();
|
||||
let now = Instant::now();
|
||||
let grouped = typing_cell.as_ref().is_some_and(|cell| {
|
||||
self.undo.last().is_some_and(|last| {
|
||||
last.typing_cell.as_ref() == Some(cell) && now.duration_since(last.time) < Duration::from_millis(750)
|
||||
})
|
||||
});
|
||||
if grouped {
|
||||
if let (
|
||||
Some(History { change: Change::Fields { after: previous, .. }, time, .. }),
|
||||
Change::Fields { after, .. },
|
||||
) = (self.undo.last_mut(), change)
|
||||
{
|
||||
*previous = after;
|
||||
*time = now;
|
||||
}
|
||||
} else {
|
||||
self.undo.push(History { change, typing_cell, time: now });
|
||||
// Bounded operation count; streaming outputs never enter history.
|
||||
if self.undo.len() > 200 {
|
||||
self.undo.remove(0);
|
||||
}
|
||||
}
|
||||
Ok(self.snapshot())
|
||||
}
|
||||
|
||||
pub fn undo(&mut self) -> IdeResult<NotebookSnapshot> {
|
||||
self.require_inactive()?;
|
||||
self.ensure_revision()?;
|
||||
if let Some(mut history) = self.undo.pop() {
|
||||
if let Err(error) = self.apply_history(&mut history.change, false) {
|
||||
self.undo.push(history);
|
||||
return Err(error);
|
||||
}
|
||||
history.typing_cell = None;
|
||||
self.redo.push(history);
|
||||
self.version += 1;
|
||||
self.last_user_revision = self.version;
|
||||
}
|
||||
self.break_typing_group();
|
||||
Ok(self.snapshot())
|
||||
}
|
||||
|
||||
pub fn redo(&mut self) -> IdeResult<NotebookSnapshot> {
|
||||
self.require_inactive()?;
|
||||
self.ensure_revision()?;
|
||||
if let Some(mut history) = self.redo.pop() {
|
||||
if let Err(error) = self.apply_history(&mut history.change, true) {
|
||||
self.redo.push(history);
|
||||
return Err(error);
|
||||
}
|
||||
history.typing_cell = None;
|
||||
self.undo.push(history);
|
||||
self.version += 1;
|
||||
self.last_user_revision = self.version;
|
||||
}
|
||||
Ok(self.snapshot())
|
||||
}
|
||||
|
||||
fn apply_history(&mut self, change: &mut Change, forward: bool) -> IdeResult<()> {
|
||||
let insertion_change = matches!(change, Change::Insert { .. });
|
||||
match change {
|
||||
Change::Fields { cell, before, after } => {
|
||||
let index = self.index(cell)?;
|
||||
let keys: Vec<&str> = before.values.iter().map(|(key, _)| key.as_str()).collect();
|
||||
let current = Fields::capture(&self.nodes()[index], &keys);
|
||||
if forward {
|
||||
*before = current;
|
||||
} else {
|
||||
*after = current;
|
||||
}
|
||||
let fields = if forward { after } else { before };
|
||||
fields.restore(self.cell_mut(index));
|
||||
if fields.values.iter().any(|(key, _)| key == "outputs") {
|
||||
let len = self.nodes()[index].get("outputs").and_then(Node::array).map_or(0, <[Node]>::len);
|
||||
self.cells[index].display_ids = vec![None; len];
|
||||
self.cells[index].pending_clear = false;
|
||||
}
|
||||
}
|
||||
Change::Insert { index, node, state, before, after }
|
||||
| Change::Delete { index, node, state, before, after } => {
|
||||
let insert = insertion_change == forward;
|
||||
if insert {
|
||||
self.array_mut().insert(*index, node.clone());
|
||||
self.cells.insert(*index, state.clone());
|
||||
} else {
|
||||
*node = self.array_mut().remove(*index);
|
||||
*state = self.cells.remove(*index);
|
||||
}
|
||||
self.array_mut().restore_layout(if forward { after } else { before }.clone());
|
||||
}
|
||||
Change::Move { from, to, before, after } => {
|
||||
if forward {
|
||||
self.move_cell(*from, *to);
|
||||
} else {
|
||||
self.move_cell(*to, *from);
|
||||
}
|
||||
self.array_mut().restore_layout(if forward { after } else { before }.clone());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn move_cell(&mut self, from: usize, to: usize) {
|
||||
let node = self.array_mut().remove(from);
|
||||
self.array_mut().insert(to, node);
|
||||
let state = self.cells.remove(from);
|
||||
self.cells.insert(to, state);
|
||||
}
|
||||
|
||||
fn code_index(&self, cell: &str) -> IdeResult<usize> {
|
||||
let index = self.index(cell)?;
|
||||
if string_field(&self.nodes()[index], "cell_type") != Some("code") {
|
||||
return Err(IdeError::invalid("Only code cells accept execution output"));
|
||||
}
|
||||
Ok(index)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_cell_type(cell_type: &str) -> IdeResult<()> {
|
||||
if matches!(cell_type, "code" | "markdown" | "raw") {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(IdeError::invalid("New/converted cell type must be code, markdown, or raw"))
|
||||
}
|
||||
}
|
||||
|
||||
fn persisted_output(mut value: Value) -> IdeResult<Value> {
|
||||
let object = value.as_object_mut().ok_or_else(|| IdeError::invalid("Notebook outputs must be objects"))?;
|
||||
if !object.get("output_type").is_some_and(Value::is_string) {
|
||||
return Err(IdeError::invalid("Notebook outputs require a string output_type"));
|
||||
}
|
||||
object.remove("transient");
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
impl NotebookDocument {
|
||||
pub fn begin_execution(&mut self, cell: &str) -> IdeResult<()> {
|
||||
let index = self.code_index(cell)?;
|
||||
self.ensure_revision()?;
|
||||
let changed = self.clear_outputs(index);
|
||||
let count_changed = !self.nodes()[index].get("execution_count").expect("code count").is_null();
|
||||
if count_changed {
|
||||
self.cell_mut(index).set("execution_count", Some(Node::new(Value::Null)));
|
||||
}
|
||||
if changed || count_changed {
|
||||
self.version += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Commits one IOPub event and returns all cells whose persisted bytes
|
||||
/// changed. Display identifiers and deferred clears exist only in memory.
|
||||
pub fn record_output(&mut self, cell: &str, event: &KernelOutput) -> IdeResult<Vec<String>> {
|
||||
let index = self.code_index(cell)?;
|
||||
self.ensure_revision()?;
|
||||
let content = &event.content;
|
||||
let mut changed = Vec::new();
|
||||
match event.kind.as_str() {
|
||||
"execute_input" => {
|
||||
let count = content
|
||||
.get("execution_count")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.ok_or_else(|| IdeError::invalid("Kernel execute_input lacks a valid execution_count"))?;
|
||||
if uint_field(&self.nodes()[index], "execution_count") != Some(count) {
|
||||
self.cell_mut(index).set("execution_count", Some(Node::new(json!(count))));
|
||||
changed.push(cell.to_owned());
|
||||
}
|
||||
}
|
||||
"clear_output" => {
|
||||
if content.get("wait").and_then(Value::as_bool).unwrap_or(false) {
|
||||
self.cells[index].pending_clear = true;
|
||||
} else if self.clear_outputs(index) {
|
||||
changed.push(cell.to_owned());
|
||||
}
|
||||
}
|
||||
"stream" => {
|
||||
let name = content
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| IdeError::invalid("Kernel stream lacks a name"))?;
|
||||
let text =
|
||||
text_value(content.get("text").ok_or_else(|| IdeError::invalid("Kernel stream lacks text"))?)?;
|
||||
if self.clear_pending(index) {
|
||||
changed.push(cell.to_owned());
|
||||
}
|
||||
let outputs = self.nodes()[index].get("outputs").and_then(Node::array).expect("code outputs");
|
||||
let last = outputs.len().checked_sub(1).filter(|last| {
|
||||
string_field(&outputs[*last], "output_type") == Some("stream")
|
||||
&& string_field(&outputs[*last], "name") == Some(name)
|
||||
});
|
||||
if let Some(last) = last {
|
||||
if !text.is_empty() {
|
||||
let old = outputs[last]
|
||||
.get("text")
|
||||
.ok_or_else(|| IdeError::invalid("Stored stream output lacks text"))?;
|
||||
let combined = if old.string().is_some() { None } else { Some(node_text(old)?) };
|
||||
let stream = self.cell_mut(index).get_mut("outputs").expect("outputs").item_mut(last);
|
||||
if let Some(mut combined) = combined {
|
||||
combined.push_str(&text);
|
||||
stream.set("text", Some(Node::new(Value::String(combined))));
|
||||
} else {
|
||||
stream.get_mut("text").expect("stream text").append_string(&text);
|
||||
}
|
||||
changed.push(cell.to_owned());
|
||||
}
|
||||
} else {
|
||||
let mut value = content
|
||||
.as_object()
|
||||
.cloned()
|
||||
.ok_or_else(|| IdeError::invalid("Kernel stream content must be an object"))?;
|
||||
value.insert("output_type".into(), json!("stream"));
|
||||
value.insert("text".into(), Value::String(text));
|
||||
value.remove("transient");
|
||||
self.append_output(index, Node::new(Value::Object(value)), None);
|
||||
changed.push(cell.to_owned());
|
||||
}
|
||||
}
|
||||
"display_data" | "execute_result" | "error" => {
|
||||
// Validate before applying a pending clear: malformed messages
|
||||
// must not erase existing output as a side effect of failure.
|
||||
let mut value = content
|
||||
.as_object()
|
||||
.cloned()
|
||||
.ok_or_else(|| IdeError::invalid("Kernel output content must be an object"))?;
|
||||
if event.kind == "error" {
|
||||
if !value.get("ename").is_some_and(Value::is_string)
|
||||
|| !value.get("evalue").is_some_and(Value::is_string)
|
||||
|| !value
|
||||
.get("traceback")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|lines| lines.iter().all(Value::is_string))
|
||||
{
|
||||
return Err(IdeError::invalid("Kernel error output is malformed"));
|
||||
}
|
||||
} else if !value.get("data").is_some_and(Value::is_object)
|
||||
|| !value.get("metadata").is_some_and(Value::is_object)
|
||||
{
|
||||
return Err(IdeError::invalid("Kernel display output lacks a MIME bundle or metadata"));
|
||||
}
|
||||
if event.kind == "execute_result"
|
||||
&& value.get("execution_count").and_then(Value::as_u64).is_none_or(|n| u32::try_from(n).is_err())
|
||||
{
|
||||
return Err(IdeError::invalid("Kernel execute_result lacks a valid execution_count"));
|
||||
}
|
||||
let display_id = display_id(content);
|
||||
value.remove("transient");
|
||||
value.insert("output_type".into(), json!(event.kind));
|
||||
if self.clear_pending(index) {
|
||||
changed.push(cell.to_owned());
|
||||
}
|
||||
self.append_output(index, Node::new(Value::Object(value)), display_id);
|
||||
changed.push(cell.to_owned());
|
||||
}
|
||||
"update_display_data" => {
|
||||
let Some(id) = display_id(content) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let data = content
|
||||
.get("data")
|
||||
.filter(|v| v.is_object())
|
||||
.ok_or_else(|| IdeError::invalid("Display update lacks a MIME bundle"))?;
|
||||
let metadata = content
|
||||
.get("metadata")
|
||||
.filter(|v| v.is_object())
|
||||
.ok_or_else(|| IdeError::invalid("Display update lacks metadata"))?;
|
||||
if self.clear_pending(index) {
|
||||
changed.push(cell.to_owned());
|
||||
}
|
||||
for current in 0..self.cells.len() {
|
||||
let matches: Vec<usize> = self.cells[current]
|
||||
.display_ids
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(output, display)| (display.as_deref() == Some(id.as_str())).then_some(output))
|
||||
.collect();
|
||||
let mut cell_changed = false;
|
||||
for output in matches {
|
||||
let Some(old) = self.nodes()[current]
|
||||
.get("outputs")
|
||||
.and_then(Node::array)
|
||||
.and_then(|outputs| outputs.get(output))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let data_node = Node::new(data.clone());
|
||||
let metadata_node = Node::new(metadata.clone());
|
||||
let replace_data = old.get("data").is_none_or(|old| !old.same_bytes(&data_node));
|
||||
let replace_metadata = old.get("metadata").is_none_or(|old| !old.same_bytes(&metadata_node));
|
||||
if replace_data || replace_metadata {
|
||||
let output =
|
||||
self.cell_mut(current).get_mut("outputs").expect("mapped outputs").item_mut(output);
|
||||
if replace_data {
|
||||
output.set("data", Some(data_node));
|
||||
}
|
||||
if replace_metadata {
|
||||
output.set("metadata", Some(metadata_node));
|
||||
}
|
||||
cell_changed = true;
|
||||
}
|
||||
}
|
||||
if cell_changed {
|
||||
changed.push(self.cells[current].id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
changed.retain(|id| seen.insert(id.clone()));
|
||||
if !changed.is_empty() {
|
||||
self.version += 1;
|
||||
}
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
fn append_output(&mut self, index: usize, node: Node, display_id: Option<String>) {
|
||||
let len = self.nodes()[index].get("outputs").and_then(Node::array).expect("code outputs").len();
|
||||
self.cell_mut(index).get_mut("outputs").expect("outputs").insert(len, node);
|
||||
self.cells[index].display_ids.push(display_id);
|
||||
}
|
||||
|
||||
fn clear_pending(&mut self, index: usize) -> bool {
|
||||
if self.cells[index].pending_clear { self.clear_outputs(index) } else { false }
|
||||
}
|
||||
|
||||
fn clear_outputs(&mut self, index: usize) -> bool {
|
||||
self.cells[index].pending_clear = false;
|
||||
self.cells[index].display_ids.clear();
|
||||
let changed = !self.nodes()[index].get("outputs").and_then(Node::array).expect("code outputs").is_empty();
|
||||
if changed {
|
||||
self.cell_mut(index).set("outputs", Some(Node::new(json!([]))));
|
||||
}
|
||||
changed
|
||||
}
|
||||
}
|
||||
|
||||
fn display_id(content: &Value) -> Option<String> {
|
||||
content.get("transient")?.get("display_id")?.as_str().map(str::to_owned)
|
||||
}
|
||||
|
||||
fn node_text(node: &Node) -> IdeResult<String> {
|
||||
if let Some(text) = node.string() {
|
||||
return Ok(text.into());
|
||||
}
|
||||
if let Some(parts) = node.array() {
|
||||
let mut text = String::new();
|
||||
for part in parts {
|
||||
text.push_str(
|
||||
part.string().ok_or_else(|| IdeError::invalid("Notebook text arrays must contain only strings"))?,
|
||||
);
|
||||
}
|
||||
return Ok(text);
|
||||
}
|
||||
Err(IdeError::invalid("Notebook source/text must be a string or string array"))
|
||||
}
|
||||
|
||||
fn rewritten_source(old: Option<&Node>, text: String) -> Node {
|
||||
let Some(old) = old.filter(|node| node.array().is_some()) else {
|
||||
return Node::new(Value::String(text));
|
||||
};
|
||||
let parts = old.array().expect("source list");
|
||||
let mut first = 0;
|
||||
let mut start = 0;
|
||||
while first < parts.len() {
|
||||
let part = parts[first].string().expect("validated source text");
|
||||
if !text[start..].starts_with(part) {
|
||||
break;
|
||||
}
|
||||
start += part.len();
|
||||
first += 1;
|
||||
}
|
||||
let mut last = parts.len();
|
||||
let mut end = text.len();
|
||||
while last > first {
|
||||
let part = parts[last - 1].string().expect("validated source text");
|
||||
if end - start < part.len() || !text[start..end].ends_with(part) {
|
||||
break;
|
||||
}
|
||||
end -= part.len();
|
||||
last -= 1;
|
||||
}
|
||||
let mut updated = old.clone();
|
||||
for index in (first..last).rev() {
|
||||
updated.remove(index);
|
||||
}
|
||||
for (offset, part) in text[start..end].split_inclusive('\n').enumerate() {
|
||||
updated.insert(first + offset, Node::new(Value::String(part.into())));
|
||||
}
|
||||
updated
|
||||
}
|
||||
|
||||
fn validate_text_node(node: &Node) -> IdeResult<()> {
|
||||
if node.string().is_some() || node.array().is_some_and(|items| items.iter().all(|part| part.string().is_some())) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(IdeError::invalid("Notebook source/text must be a string or string array"))
|
||||
}
|
||||
}
|
||||
|
||||
fn text_matches(node: &Node, text: &str) -> bool {
|
||||
if let Some(old) = node.string() {
|
||||
return old == text;
|
||||
}
|
||||
let Some(parts) = node.array() else {
|
||||
return false;
|
||||
};
|
||||
let mut remaining = text;
|
||||
for part in parts {
|
||||
let Some(part) = part.string() else {
|
||||
return false;
|
||||
};
|
||||
let Some(rest) = remaining.strip_prefix(part) else {
|
||||
return false;
|
||||
};
|
||||
remaining = rest;
|
||||
}
|
||||
remaining.is_empty()
|
||||
}
|
||||
|
||||
fn validate_output_node(node: &Node) -> IdeResult<()> {
|
||||
let kind = string_field(node, "output_type")
|
||||
.ok_or_else(|| IdeError::invalid("Notebook outputs must be objects with a string output_type"))?;
|
||||
match kind {
|
||||
"stream" => {
|
||||
if string_field(node, "name").is_none() {
|
||||
return Err(IdeError::invalid("Stored stream output lacks a name"));
|
||||
}
|
||||
validate_text_node(node.get("text").ok_or_else(|| IdeError::invalid("Stored stream output lacks text"))?)?;
|
||||
}
|
||||
"display_data" | "execute_result" => {
|
||||
if node.get("data").is_none_or(|n| n.members().is_none())
|
||||
|| node.get("metadata").is_none_or(|n| n.members().is_none())
|
||||
{
|
||||
return Err(IdeError::invalid("Stored display output requires data and metadata objects"));
|
||||
}
|
||||
if kind == "execute_result" && uint_field(node, "execution_count").is_none() {
|
||||
return Err(IdeError::invalid("Stored execute_result lacks a valid execution_count"));
|
||||
}
|
||||
}
|
||||
"error"
|
||||
if (string_field(node, "ename").is_none()
|
||||
|| string_field(node, "evalue").is_none()
|
||||
|| !node
|
||||
.get("traceback")
|
||||
.and_then(Node::array)
|
||||
.is_some_and(|lines| lines.iter().all(|line| line.string().is_some()))) =>
|
||||
{
|
||||
return Err(IdeError::invalid("Stored error output is malformed"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
//! JSON syntax retained as shared original spans. Mutating one value never
|
||||
//! normalizes its siblings, property spelling, whitespace, or container order.
|
||||
use std::{ops::Range, sync::Arc};
|
||||
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Raw {
|
||||
text: Arc<str>,
|
||||
span: Range<usize>,
|
||||
}
|
||||
|
||||
impl Raw {
|
||||
fn text(&self) -> &str {
|
||||
&self.text[self.span.clone()]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Node {
|
||||
raw: Option<Raw>,
|
||||
kind: Kind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Kind {
|
||||
Scalar(Arc<Value>),
|
||||
Object(Vec<Member>, Layout),
|
||||
Array(Vec<Node>, Layout),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Member {
|
||||
pub key: String,
|
||||
head: String,
|
||||
pub value: Node,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Layout {
|
||||
prefix: String,
|
||||
separators: Vec<String>,
|
||||
suffix: String,
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
fn compact() -> Self {
|
||||
Self { prefix: String::new(), separators: Vec::new(), suffix: String::new() }
|
||||
}
|
||||
|
||||
fn separator(&self, index: usize) -> &str {
|
||||
self.separators.get(index).map(String::as_str).unwrap_or(",")
|
||||
}
|
||||
|
||||
fn remove(&mut self, index: usize) {
|
||||
if !self.separators.is_empty() {
|
||||
self.separators.remove(index.saturating_sub(1).min(self.separators.len() - 1));
|
||||
}
|
||||
}
|
||||
|
||||
fn insert(&mut self, index: usize, previous_len: usize) {
|
||||
if previous_len > 0 {
|
||||
let separator = self.separators.first().cloned().unwrap_or_else(|| ",".into());
|
||||
self.separators.insert(index.saturating_sub(1).min(self.separators.len()), separator);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Node {
|
||||
pub fn parse(text: Arc<str>) -> IdeResult<(Self, String, String)> {
|
||||
// serde supplies strict JSON/UTF-8 string and numeric validation. The
|
||||
// scanner below only locates the already validated syntax spans.
|
||||
let start = usize::from(text.starts_with('\u{feff}')) * 3;
|
||||
serde_json::from_str::<serde::de::IgnoredAny>(&text[start..])
|
||||
.map_err(|e| IdeError::invalid(format!("Invalid notebook JSON: {e}")))?;
|
||||
let mut parser = Parser { text: text.clone(), pos: start };
|
||||
parser.space();
|
||||
let begin = parser.pos;
|
||||
let root = parser.node()?;
|
||||
Ok((root, text[..begin].into(), text[parser.pos..].into()))
|
||||
}
|
||||
|
||||
pub fn new(value: Value) -> Self {
|
||||
match value {
|
||||
Value::Object(map) => Self {
|
||||
raw: None,
|
||||
kind: Kind::Object(
|
||||
map.into_iter()
|
||||
.map(|(key, value)| Member {
|
||||
head: format!("{}:", serde_json::to_string(&key).expect("JSON key")),
|
||||
key,
|
||||
value: Self::new(value),
|
||||
})
|
||||
.collect(),
|
||||
Layout::compact(),
|
||||
),
|
||||
},
|
||||
Value::Array(values) => {
|
||||
Self { raw: None, kind: Kind::Array(values.into_iter().map(Self::new).collect(), Layout::compact()) }
|
||||
}
|
||||
value => Self { raw: None, kind: Kind::Scalar(Arc::new(value)) },
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value(&self) -> Value {
|
||||
match &self.kind {
|
||||
Kind::Scalar(value) => value.as_ref().clone(),
|
||||
Kind::Array(items, _) => Value::Array(items.iter().map(Self::value).collect()),
|
||||
Kind::Object(items, _) => Value::Object(items.iter().map(|m| (m.key.clone(), m.value.value())).collect()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(&self, key: &str) -> Option<&Self> {
|
||||
match &self.kind {
|
||||
Kind::Object(items, _) => items.iter().find(|m| m.key == key).map(|m| &m.value),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn string(&self) -> Option<&str> {
|
||||
match &self.kind {
|
||||
Kind::Scalar(value) => value.as_str(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn uint(&self) -> Option<u32> {
|
||||
match &self.kind {
|
||||
Kind::Scalar(value) => value.as_u64().and_then(|n| u32::try_from(n).ok()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_null(&self) -> bool {
|
||||
matches!(&self.kind, Kind::Scalar(value) if value.is_null())
|
||||
}
|
||||
|
||||
pub fn append_string(&mut self, text: &str) {
|
||||
self.raw = None;
|
||||
let Kind::Scalar(value) = &mut self.kind else { unreachable!("validated string") };
|
||||
let Value::String(current) = Arc::make_mut(value) else { unreachable!("validated string") };
|
||||
current.push_str(text);
|
||||
}
|
||||
|
||||
pub fn get_mut(&mut self, key: &str) -> Option<&mut Self> {
|
||||
self.raw = None;
|
||||
match &mut self.kind {
|
||||
Kind::Object(items, _) => items.iter_mut().find(|m| m.key == key).map(|m| &mut m.value),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn members(&self) -> Option<&[Member]> {
|
||||
match &self.kind {
|
||||
Kind::Object(items, _) => Some(items),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn array(&self) -> Option<&[Self]> {
|
||||
match &self.kind {
|
||||
Kind::Array(items, _) => Some(items),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn item_mut(&mut self, index: usize) -> &mut Self {
|
||||
self.raw = None;
|
||||
match &mut self.kind {
|
||||
Kind::Array(items, _) => &mut items[index],
|
||||
_ => unreachable!("validated array"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn layout(&self) -> Layout {
|
||||
match &self.kind {
|
||||
Kind::Array(_, layout) | Kind::Object(_, layout) => layout.clone(),
|
||||
_ => unreachable!("container layout"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn restore_layout(&mut self, layout: Layout) {
|
||||
self.raw = None;
|
||||
match &mut self.kind {
|
||||
Kind::Array(_, old) | Kind::Object(_, old) => *old = layout,
|
||||
_ => unreachable!("container layout"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set(&mut self, key: &str, value: Option<Self>) {
|
||||
self.raw = None;
|
||||
let Kind::Object(items, layout) = &mut self.kind else { unreachable!("validated object") };
|
||||
match (items.iter().position(|m| m.key == key), value) {
|
||||
(Some(index), Some(value)) => items[index].value = value,
|
||||
(Some(index), None) => {
|
||||
items.remove(index);
|
||||
layout.remove(index);
|
||||
}
|
||||
(None, Some(value)) => {
|
||||
layout.insert(items.len(), items.len());
|
||||
items.push(Member {
|
||||
key: key.into(),
|
||||
head: format!("{}:", serde_json::to_string(key).expect("JSON key")),
|
||||
value,
|
||||
});
|
||||
}
|
||||
(None, None) => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn restore_fields(&mut self, fields: &[(String, Option<Member>)], order: &[String], layout: &Layout) {
|
||||
for (key, field) in fields {
|
||||
self.set(key, field.as_ref().map(|m| m.value.clone()));
|
||||
}
|
||||
let Kind::Object(items, old_layout) = &mut self.kind else { unreachable!("validated object") };
|
||||
for (key, field) in fields {
|
||||
if let (Some(saved), Some(current)) = (field, items.iter_mut().find(|m| &m.key == key)) {
|
||||
current.head.clone_from(&saved.head);
|
||||
}
|
||||
}
|
||||
items.sort_by_key(|m| order.iter().position(|key| key == &m.key).unwrap_or(usize::MAX));
|
||||
if items.len() == order.len() {
|
||||
*old_layout = layout.clone();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, index: usize, node: Self) {
|
||||
self.raw = None;
|
||||
let Kind::Array(items, layout) = &mut self.kind else { unreachable!("validated array") };
|
||||
layout.insert(index, items.len());
|
||||
items.insert(index, node);
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, index: usize) -> Self {
|
||||
self.raw = None;
|
||||
let Kind::Array(items, layout) = &mut self.kind else { unreachable!("validated array") };
|
||||
layout.remove(index);
|
||||
items.remove(index)
|
||||
}
|
||||
|
||||
pub fn same_bytes(&self, other: &Self) -> bool {
|
||||
if let (Some(a), Some(b)) = (&self.raw, &other.raw) {
|
||||
return (Arc::ptr_eq(&a.text, &b.text) && a.span == b.span) || a.text() == b.text();
|
||||
}
|
||||
match (&self.kind, &other.kind) {
|
||||
(Kind::Scalar(a), Kind::Scalar(b)) => {
|
||||
if a != b {
|
||||
return false;
|
||||
}
|
||||
match (&self.raw, &other.raw) {
|
||||
(Some(raw), None) | (None, Some(raw)) => {
|
||||
raw.text() == serde_json::to_string(a.as_ref()).expect("JSON value")
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
(Kind::Object(a, al), Kind::Object(b, bl)) => {
|
||||
a.len() == b.len()
|
||||
&& same_layout(al, bl, a.len())
|
||||
&& a.iter().zip(b).all(|(a, b)| a.key == b.key && a.head == b.head && a.value.same_bytes(&b.value))
|
||||
}
|
||||
(Kind::Array(a, al), Kind::Array(b, bl)) => {
|
||||
a.len() == b.len() && same_layout(al, bl, a.len()) && a.iter().zip(b).all(|(a, b)| a.same_bytes(b))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write(&self, output: &mut String) {
|
||||
if let Some(raw) = &self.raw {
|
||||
output.push_str(raw.text());
|
||||
return;
|
||||
}
|
||||
match &self.kind {
|
||||
Kind::Scalar(value) => output.push_str(&serde_json::to_string(value.as_ref()).expect("JSON value")),
|
||||
Kind::Object(items, layout) => {
|
||||
output.push('{');
|
||||
output.push_str(&layout.prefix);
|
||||
for (index, member) in items.iter().enumerate() {
|
||||
if index > 0 {
|
||||
output.push_str(layout.separator(index - 1));
|
||||
}
|
||||
output.push_str(&member.head);
|
||||
member.value.write(output);
|
||||
}
|
||||
output.push_str(&layout.suffix);
|
||||
output.push('}');
|
||||
}
|
||||
Kind::Array(items, layout) => {
|
||||
output.push('[');
|
||||
output.push_str(&layout.prefix);
|
||||
for (index, item) in items.iter().enumerate() {
|
||||
if index > 0 {
|
||||
output.push_str(layout.separator(index - 1));
|
||||
}
|
||||
item.write(output);
|
||||
}
|
||||
output.push_str(&layout.suffix);
|
||||
output.push(']');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn same_layout(a: &Layout, b: &Layout, count: usize) -> bool {
|
||||
a.prefix == b.prefix
|
||||
&& a.suffix == b.suffix
|
||||
&& (0..count.saturating_sub(1)).all(|index| a.separator(index) == b.separator(index))
|
||||
}
|
||||
|
||||
struct Parser {
|
||||
text: Arc<str>,
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
fn space(&mut self) {
|
||||
while self.text.as_bytes().get(self.pos).is_some_and(u8::is_ascii_whitespace) {
|
||||
self.pos += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn string_end(&mut self) {
|
||||
self.pos += 1;
|
||||
loop {
|
||||
match self.text.as_bytes()[self.pos] {
|
||||
b'\\' => self.pos += 2,
|
||||
b'"' => {
|
||||
self.pos += 1;
|
||||
break;
|
||||
}
|
||||
_ => self.pos += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn node(&mut self) -> IdeResult<Node> {
|
||||
let start = self.pos;
|
||||
let kind = match self.text.as_bytes()[self.pos] {
|
||||
b'{' | b'[' => {
|
||||
let object = self.text.as_bytes()[self.pos] == b'{';
|
||||
let close = if object { b'}' } else { b']' };
|
||||
self.pos += 1;
|
||||
let gap = self.pos;
|
||||
self.space();
|
||||
let mut layout =
|
||||
Layout { prefix: self.text[gap..self.pos].into(), separators: Vec::new(), suffix: String::new() };
|
||||
let mut members = Vec::new();
|
||||
let mut values = Vec::new();
|
||||
if self.text.as_bytes()[self.pos] != close {
|
||||
loop {
|
||||
if object {
|
||||
let key_start = self.pos;
|
||||
self.string_end();
|
||||
let key: String = serde_json::from_str(&self.text[key_start..self.pos])
|
||||
.map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
if members.iter().any(|m: &Member| m.key == key) {
|
||||
return Err(IdeError::invalid(
|
||||
"Duplicate JSON object keys are ambiguous; notebook was not opened",
|
||||
));
|
||||
}
|
||||
self.space();
|
||||
self.pos += 1;
|
||||
self.space();
|
||||
let head = self.text[key_start..self.pos].into();
|
||||
let value = self.node()?;
|
||||
members.push(Member { key, head, value });
|
||||
} else {
|
||||
values.push(self.node()?);
|
||||
}
|
||||
let end = self.pos;
|
||||
self.space();
|
||||
if self.text.as_bytes()[self.pos] == close {
|
||||
layout.suffix = self.text[end..self.pos].into();
|
||||
break;
|
||||
}
|
||||
self.pos += 1;
|
||||
self.space();
|
||||
layout.separators.push(self.text[end..self.pos].into());
|
||||
}
|
||||
}
|
||||
self.pos += 1;
|
||||
if object { Kind::Object(members, layout) } else { Kind::Array(values, layout) }
|
||||
}
|
||||
b'"' => {
|
||||
self.string_end();
|
||||
Kind::Scalar(Arc::new(
|
||||
serde_json::from_str(&self.text[start..self.pos]).map_err(|e| IdeError::invalid(e.to_string()))?,
|
||||
))
|
||||
}
|
||||
_ => {
|
||||
while self
|
||||
.text
|
||||
.as_bytes()
|
||||
.get(self.pos)
|
||||
.is_some_and(|b| !b.is_ascii_whitespace() && !b",]}".contains(b))
|
||||
{
|
||||
self.pos += 1;
|
||||
}
|
||||
Kind::Scalar(Arc::new(
|
||||
serde_json::from_str(&self.text[start..self.pos]).map_err(|e| IdeError::invalid(e.to_string()))?,
|
||||
))
|
||||
}
|
||||
};
|
||||
Ok(Node { raw: Some(Raw { text: self.text.clone(), span: start..self.pos }), kind })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
//! Native, app-owned Jupyter kernels. One supervised process per notebook path.
|
||||
//!
|
||||
//! 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.
|
||||
|
||||
mod process;
|
||||
mod transport;
|
||||
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use tokio::sync::Mutex as AsyncMutex;
|
||||
|
||||
pub(super) type StatusCallback = Arc<dyn Fn(&Path, KernelState, Option<String>) + Send + Sync>;
|
||||
pub(super) type OutputCallback = Arc<dyn Fn(KernelOutput) + Send + Sync>;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct KernelOutput {
|
||||
pub kind: String,
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
pub content: Value,
|
||||
/// Actual Jupyter parent request ID, not a UI request ID.
|
||||
pub msg_id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum KernelState {
|
||||
Starting,
|
||||
Idle,
|
||||
Busy,
|
||||
Dead,
|
||||
}
|
||||
|
||||
impl KernelState {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Starting => "starting",
|
||||
Self::Idle => "idle",
|
||||
Self::Busy => "busy",
|
||||
Self::Dead => "dead",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExecutionResult {
|
||||
pub status: String,
|
||||
pub execution_count: Option<u32>,
|
||||
}
|
||||
|
||||
struct Slot {
|
||||
operation: AsyncMutex<Option<transport::Running>>,
|
||||
interrupt: Mutex<Option<CancellationToken>>,
|
||||
stop: Mutex<Option<CancellationToken>>,
|
||||
closed: AtomicBool,
|
||||
}
|
||||
|
||||
impl Slot {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
operation: AsyncMutex::new(None),
|
||||
interrupt: Mutex::new(None),
|
||||
stop: Mutex::new(None),
|
||||
closed: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel(&self) {
|
||||
if let Some(token) = self.interrupt.lock().as_ref() {
|
||||
token.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
fn stop(&self) {
|
||||
self.cancel();
|
||||
if let Some(token) = self.stop.lock().as_ref() {
|
||||
token.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ActiveExecution<'a>(&'a Slot);
|
||||
impl Drop for ActiveExecution<'_> {
|
||||
fn drop(&mut self) {
|
||||
if let Some(token) = self.0.interrupt.lock().take() {
|
||||
token.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct KernelManager {
|
||||
runtime_dir: PathBuf,
|
||||
on_status: StatusCallback,
|
||||
slots: Mutex<HashMap<PathBuf, Arc<Slot>>>,
|
||||
closed: AtomicBool,
|
||||
}
|
||||
|
||||
impl KernelManager {
|
||||
pub fn new(runtime_dir: PathBuf, on_status: StatusCallback) -> Self {
|
||||
Self { runtime_dir, on_status, slots: Mutex::new(HashMap::new()), closed: AtomicBool::new(false) }
|
||||
}
|
||||
|
||||
pub async fn execute(
|
||||
&self,
|
||||
notebook: &Path,
|
||||
python: &Path,
|
||||
code: &str,
|
||||
cancel: CancellationToken,
|
||||
on_output: OutputCallback,
|
||||
) -> IdeResult<ExecutionResult> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let slot = {
|
||||
let mut slots = self.slots.lock();
|
||||
if self.closed.load(Ordering::Acquire) {
|
||||
return Err(IdeError::unavailable("notebook kernel manager is shut down"));
|
||||
}
|
||||
slots.entry(notebook.to_path_buf()).or_insert_with(|| Arc::new(Slot::new())).clone()
|
||||
};
|
||||
// Register cancellation before taking the operation lock: interrupt can
|
||||
// otherwise race the tiny lock-to-token gap and miss a newly admitted run.
|
||||
let interrupt = CancellationToken::new();
|
||||
{
|
||||
let mut active = slot.interrupt.lock();
|
||||
if active.is_some() {
|
||||
return Err(IdeError::unavailable("notebook kernel is busy"));
|
||||
}
|
||||
*active = Some(interrupt.clone());
|
||||
}
|
||||
let _active = ActiveExecution(&slot);
|
||||
// A second caller must not sit in a queue and execute stale source later.
|
||||
let mut running = slot.operation.try_lock().map_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())
|
||||
&& let Some(old) = running.take()
|
||||
{
|
||||
old.shutdown().await;
|
||||
}
|
||||
if cancel.is_cancelled() || interrupt.is_cancelled() || slot.closed.load(Ordering::Acquire) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if running.is_none() {
|
||||
let (new, ready) = transport::Running::spawn(
|
||||
self.runtime_dir.clone(),
|
||||
notebook.to_path_buf(),
|
||||
python.to_path_buf(),
|
||||
self.on_status.clone(),
|
||||
);
|
||||
*slot.stop.lock() = Some(new.stop.clone());
|
||||
*running = Some(new);
|
||||
if slot.closed.load(Ordering::Acquire) {
|
||||
slot.stop();
|
||||
}
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => Err(IdeError::cancelled()),
|
||||
_ = interrupt.cancelled() => Err(IdeError::cancelled()),
|
||||
result = ready => result.unwrap_or_else(|_| Err(IdeError::unavailable("kernel startup task ended"))),
|
||||
};
|
||||
if let Err(error) = result {
|
||||
if let Some(failed) = running.take() {
|
||||
failed.shutdown().await;
|
||||
}
|
||||
slot.stop.lock().take();
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
let result = running.as_ref().expect("initialized kernel").execute(code, cancel, interrupt, on_output).await;
|
||||
if running.as_ref().is_some_and(transport::Running::is_finished) {
|
||||
if let Some(dead) = running.take() {
|
||||
dead.shutdown().await;
|
||||
}
|
||||
slot.stop.lock().take();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Cancels the active request, including startup. The execution future drains
|
||||
/// reply+idle before returning, or stops the owned process on interrupt timeout.
|
||||
pub async fn interrupt(&self, notebook: &Path) -> IdeResult<()> {
|
||||
let slot = self.slots.lock().get(notebook).cloned();
|
||||
if let Some(slot) = slot {
|
||||
slot.cancel();
|
||||
// Wait for native interrupt delivery/drain, not just token mutation.
|
||||
let _drained = slot.operation.lock().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn restart(&self, notebook: &Path) -> IdeResult<()> {
|
||||
let slot = self.slots.lock().get(notebook).cloned();
|
||||
let Some(slot) = slot else { return Ok(()) };
|
||||
slot.stop();
|
||||
let mut running = slot.operation.lock().await;
|
||||
if slot.closed.load(Ordering::Acquire) {
|
||||
return Err(IdeError::unavailable("notebook kernel was closed"));
|
||||
}
|
||||
let Some(old) = running.take() else { return Ok(()) };
|
||||
let python = old.python.clone();
|
||||
old.shutdown().await;
|
||||
let (new, ready) =
|
||||
transport::Running::spawn(self.runtime_dir.clone(), notebook.to_path_buf(), python, self.on_status.clone());
|
||||
*slot.stop.lock() = Some(new.stop.clone());
|
||||
*running = Some(new);
|
||||
if slot.closed.load(Ordering::Acquire) {
|
||||
slot.stop();
|
||||
}
|
||||
let result = ready.await.unwrap_or_else(|_| Err(IdeError::unavailable("kernel restart task ended")));
|
||||
if result.is_err() {
|
||||
if let Some(failed) = running.take() {
|
||||
failed.shutdown().await;
|
||||
}
|
||||
slot.stop.lock().take();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn shutdown_kernel(&self, notebook: &Path) -> IdeResult<()> {
|
||||
let slot = {
|
||||
let slots = self.slots.lock();
|
||||
// Keep a closed tombstone until old readers/process have drained.
|
||||
// Reopening this path cannot overlap old-generation status events.
|
||||
let slot = slots.get(notebook).cloned();
|
||||
if let Some(slot) = &slot {
|
||||
slot.closed.store(true, Ordering::Release);
|
||||
slot.stop();
|
||||
}
|
||||
slot
|
||||
};
|
||||
if let Some(slot) = slot {
|
||||
if let Some(running) = slot.operation.lock().await.take() {
|
||||
running.shutdown().await;
|
||||
}
|
||||
slot.stop.lock().take();
|
||||
let mut slots = self.slots.lock();
|
||||
if slots.get(notebook).is_some_and(|current| Arc::ptr_eq(current, &slot)) {
|
||||
slots.remove(notebook);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn shutdown(&self) {
|
||||
let slots = {
|
||||
let mut slots = self.slots.lock();
|
||||
self.closed.store(true, Ordering::Release);
|
||||
slots
|
||||
.drain()
|
||||
.map(|(_, slot)| {
|
||||
slot.closed.store(true, Ordering::Release);
|
||||
slot.stop();
|
||||
slot
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
// All stop tokens are signalled before awaiting any process.
|
||||
for slot in slots {
|
||||
if let Some(running) = slot.operation.lock().await.take() {
|
||||
running.shutdown().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for KernelManager {
|
||||
fn drop(&mut self) {
|
||||
for slot in self.slots.get_mut().values() {
|
||||
slot.closed.store(true, Ordering::Release);
|
||||
slot.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use jupyter_protocol::ConnectionInfo;
|
||||
use parking_lot::Mutex;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
|
||||
use tokio::process::{Child, Command};
|
||||
use tokio::task::JoinHandle;
|
||||
use uuid::Uuid;
|
||||
|
||||
const STDERR_BYTES: usize = 16 * 1024;
|
||||
|
||||
pub(super) struct Process {
|
||||
child: Child,
|
||||
#[cfg(unix)]
|
||||
pid: Option<u32>,
|
||||
stderr: Arc<Mutex<String>>,
|
||||
drains: Vec<JoinHandle<()>>,
|
||||
// Kept until the process and sockets have stopped; contains the HMAC secret.
|
||||
_directory: tempfile::TempDir,
|
||||
#[cfg(windows)]
|
||||
windows: windows::Resources,
|
||||
}
|
||||
|
||||
impl Process {
|
||||
pub async fn spawn(runtime: &Path, notebook: &Path, python: &Path) -> IdeResult<(Self, ConnectionInfo)> {
|
||||
if !python.is_absolute() {
|
||||
return Err(IdeError::invalid("select an absolute Python executable path for this notebook"));
|
||||
}
|
||||
std::fs::create_dir_all(runtime)?;
|
||||
let directory = tempfile::Builder::new().prefix("kernel-").tempdir_in(runtime)?;
|
||||
make_private(directory.path())?;
|
||||
let ip = std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST);
|
||||
let (ports, listeners) = jupyter_zmq_client::peek_ports_with_listeners(ip, 5).await.map_err(protocol_error)?;
|
||||
let info = ConnectionInfo {
|
||||
transport: jupyter_protocol::connection_info::Transport::TCP,
|
||||
ip: ip.to_string(),
|
||||
stdin_port: ports[0],
|
||||
control_port: ports[1],
|
||||
hb_port: ports[2],
|
||||
shell_port: ports[3],
|
||||
iopub_port: ports[4],
|
||||
signature_scheme: "hmac-sha256".into(),
|
||||
key: format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple()),
|
||||
kernel_name: Some("openidea-python".into()),
|
||||
};
|
||||
let connection = directory.path().join("connection.json");
|
||||
write_private(&connection, &serde_json::to_vec(&info).map_err(protocol_error)?)?;
|
||||
#[cfg(windows)]
|
||||
let windows = windows::Resources::new()?;
|
||||
let mut argv = vec![python.as_os_str().to_os_string()];
|
||||
#[cfg(not(windows))]
|
||||
argv.extend(["-m".into(), "ipykernel_launcher".into(), "-f".into(), "{connection_file}".into()]);
|
||||
#[cfg(windows)]
|
||||
argv.extend(["-c".into(), windows::BOOTSTRAP.into(), "-f".into(), "{connection_file}".into()]);
|
||||
// App-owned spec, not registered in user/global Jupyter directories. The
|
||||
// argv array is also the launch source of truth, without shell quoting.
|
||||
let spec = serde_json::json!({
|
||||
"argv": argv.iter().map(|v| v.to_string_lossy().into_owned()).collect::<Vec<_>>(),
|
||||
"display_name": "OpenIDEA Python", "language": "python", "interrupt_mode": "signal"
|
||||
});
|
||||
write_private(&directory.path().join("kernel.json"), &serde_json::to_vec(&spec).map_err(protocol_error)?)?;
|
||||
let mut command = Command::new(python);
|
||||
for arg in &argv[1..] {
|
||||
if arg == "{connection_file}" {
|
||||
command.arg(&connection);
|
||||
} else {
|
||||
command.arg(arg);
|
||||
}
|
||||
}
|
||||
command
|
||||
.current_dir(notebook.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")))
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true)
|
||||
.env_remove("JPY_INTERRUPT_EVENT")
|
||||
.env_remove("JPY_PARENT_PID")
|
||||
.env("PYTHONUNBUFFERED", "1");
|
||||
ide_core::process::prepare(command.as_std_mut());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
command.as_std_mut().process_group(0);
|
||||
command.env("JPY_PARENT_PID", std::process::id().to_string());
|
||||
}
|
||||
#[cfg(windows)]
|
||||
windows.configure(&mut command);
|
||||
let child = command.spawn().map_err(|e| {
|
||||
IdeError::unavailable(format!(
|
||||
"cannot start selected Python {}: {e}. Select an executable environment with ipykernel installed",
|
||||
python.display()
|
||||
))
|
||||
})?;
|
||||
drop(listeners);
|
||||
#[cfg(unix)]
|
||||
let pid = child.id();
|
||||
let mut process = Self {
|
||||
child,
|
||||
#[cfg(unix)]
|
||||
pid,
|
||||
stderr: Arc::new(Mutex::new(String::new())),
|
||||
drains: Vec::new(),
|
||||
_directory: directory,
|
||||
#[cfg(windows)]
|
||||
windows,
|
||||
};
|
||||
if let Some(stderr) = process.child.stderr.take() {
|
||||
let tail = process.stderr.clone();
|
||||
process.drains.push(tokio::spawn(async move {
|
||||
let mut reader = BufReader::new(stderr);
|
||||
let mut line = Vec::new();
|
||||
loop {
|
||||
line.clear();
|
||||
match reader.read_until(b'\n', &mut line).await {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(_) => {
|
||||
let text = ide_core::output_encoding::decode_tool_output(&line);
|
||||
let mut tail = tail.lock();
|
||||
tail.push_str(&text);
|
||||
let mut start = tail.len().saturating_sub(STDERR_BYTES);
|
||||
while !tail.is_char_boundary(start) {
|
||||
start += 1;
|
||||
}
|
||||
tail.drain(..start);
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
if let Some(mut stdout) = process.child.stdout.take() {
|
||||
process.drains.push(tokio::spawn(async move {
|
||||
let mut buffer = [0_u8; 4096];
|
||||
while let Ok(count) = stdout.read(&mut buffer).await {
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
process.windows.assign_and_release(&process.child)?;
|
||||
Ok((process, info))
|
||||
}
|
||||
|
||||
pub fn stderr(&self) -> String {
|
||||
self.stderr.lock().clone()
|
||||
}
|
||||
|
||||
pub fn death(&mut self) -> IdeResult<Option<String>> {
|
||||
match self.child.try_wait()? {
|
||||
None => Ok(None),
|
||||
Some(status) => {
|
||||
self.kill_tree();
|
||||
Ok(Some(format!("kernel exited ({status}); {}", self.stderr())))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn interrupt(&self) -> IdeResult<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let pid = self.pid.ok_or_else(|| IdeError::unavailable("kernel is no longer running"))?;
|
||||
// SAFETY: this child was created in its own process group. Never
|
||||
// signal the host group or a discovered/external kernel.
|
||||
if unsafe { libc::kill(-(pid as i32), libc::SIGINT) } != 0 {
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
self.windows.interrupt()
|
||||
}
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
{
|
||||
Err(IdeError::unavailable("native kernel interruption is unsupported on this platform"))
|
||||
}
|
||||
}
|
||||
|
||||
fn kill_tree(&mut self) {
|
||||
#[cfg(unix)]
|
||||
if let Some(pid) = self.pid.take() {
|
||||
// SAFETY: group ID belongs exclusively to the owned kernel.
|
||||
unsafe {
|
||||
libc::kill(-(pid as i32), libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
self.windows.kill_tree();
|
||||
}
|
||||
|
||||
pub async fn shutdown(&mut self) {
|
||||
self.kill_tree();
|
||||
let _ = self.child.start_kill();
|
||||
let _ = tokio::time::timeout(Duration::from_secs(3), self.child.wait()).await;
|
||||
for task in self.drains.drain(..) {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Process {
|
||||
fn drop(&mut self) {
|
||||
self.kill_tree();
|
||||
let _ = self.child.start_kill();
|
||||
for task in &self.drains {
|
||||
task.abort();
|
||||
}
|
||||
// tokio Child's kill_on_drop also kills/reaps if this future is aborted.
|
||||
}
|
||||
}
|
||||
|
||||
fn protocol_error(error: impl std::fmt::Display) -> IdeError {
|
||||
IdeError::unavailable(format!("Jupyter kernel setup: {error}"))
|
||||
}
|
||||
|
||||
fn write_private(path: &Path, bytes: &[u8]) -> IdeResult<()> {
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let mut file = options.open(path)?;
|
||||
file.write_all(bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn make_private(path: &Path) -> IdeResult<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))?;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
windows::private_directory(path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows {
|
||||
use super::*;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows_sys::Win32::Foundation::{CloseHandle, ERROR_ALREADY_EXISTS, GetLastError, HANDLE, LocalFree};
|
||||
use windows_sys::Win32::Security::Authorization::{
|
||||
ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1, SE_FILE_OBJECT, SetNamedSecurityInfoW,
|
||||
};
|
||||
use windows_sys::Win32::Security::{
|
||||
DACL_SECURITY_INFORMATION, GetSecurityDescriptorDacl, PROTECTED_DACL_SECURITY_INFORMATION, SECURITY_ATTRIBUTES,
|
||||
};
|
||||
use windows_sys::Win32::System::JobObjects::{
|
||||
AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
||||
JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation, SetInformationJobObject,
|
||||
TerminateJobObject,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::{CreateEventW, SetEvent};
|
||||
|
||||
// Launcher glue only. All Jupyter traffic is authenticated native ZeroMQ.
|
||||
// Child opens its own handles: no assumption about Rust HANDLE inheritance.
|
||||
// The gate prevents any ipykernel imports/descendants before job assignment.
|
||||
pub const BOOTSTRAP: &str = r#"import ctypes, os, runpy, sys
|
||||
k = ctypes.WinDLL('kernel32', use_last_error=True)
|
||||
k.OpenEventW.argtypes = [ctypes.c_uint32, ctypes.c_int, ctypes.c_wchar_p]
|
||||
k.OpenEventW.restype = ctypes.c_void_p
|
||||
k.WaitForSingleObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
|
||||
k.WaitForSingleObject.restype = ctypes.c_uint32
|
||||
k.CloseHandle.argtypes = [ctypes.c_void_p]
|
||||
k.CloseHandle.restype = ctypes.c_int
|
||||
interrupt = k.OpenEventW(0x00100002, 0, os.environ.pop('OPENIDEA_INTERRUPT_EVENT'))
|
||||
gate = k.OpenEventW(0x00100000, 0, os.environ.pop('OPENIDEA_LAUNCH_EVENT'))
|
||||
if not interrupt or not gate:
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
if k.WaitForSingleObject(gate, 30000) != 0:
|
||||
raise RuntimeError('OpenIDEA kernel launch gate failed')
|
||||
k.CloseHandle(gate)
|
||||
os.environ['JPY_INTERRUPT_EVENT'] = str(interrupt)
|
||||
try:
|
||||
runpy.run_module('ipykernel_launcher', run_name='__main__')
|
||||
finally:
|
||||
k.CloseHandle(interrupt)
|
||||
"#;
|
||||
|
||||
struct Handle(usize);
|
||||
impl Handle {
|
||||
fn new(raw: HANDLE) -> IdeResult<Self> {
|
||||
if raw.is_null() { Err(std::io::Error::last_os_error().into()) } else { Ok(Self(raw as usize)) }
|
||||
}
|
||||
fn raw(&self) -> HANDLE {
|
||||
self.0 as HANDLE
|
||||
}
|
||||
fn signal(&self) -> IdeResult<()> {
|
||||
// SAFETY: owned live event handle, retained for this process lifetime.
|
||||
if unsafe { SetEvent(self.raw()) } == 0 { Err(std::io::Error::last_os_error().into()) } else { Ok(()) }
|
||||
}
|
||||
}
|
||||
impl Drop for Handle {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
CloseHandle(self.raw());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Descriptor(*mut std::ffi::c_void);
|
||||
impl Descriptor {
|
||||
fn new() -> IdeResult<Self> {
|
||||
// Protected ACL: owner and SYSTEM only, inherited by runtime files.
|
||||
let sddl = "D:P(A;OICI;FA;;;OW)(A;OICI;FA;;;SY)\0".encode_utf16().collect::<Vec<_>>();
|
||||
let mut raw = std::ptr::null_mut();
|
||||
if unsafe {
|
||||
ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
||||
sddl.as_ptr(),
|
||||
SDDL_REVISION_1,
|
||||
&mut raw,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
Ok(Self(raw))
|
||||
}
|
||||
}
|
||||
impl Drop for Descriptor {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
LocalFree(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn private_directory(path: &Path) -> IdeResult<()> {
|
||||
let descriptor = Descriptor::new()?;
|
||||
let mut present = 0;
|
||||
let mut defaulted = 0;
|
||||
let mut dacl = std::ptr::null_mut();
|
||||
if unsafe { GetSecurityDescriptorDacl(descriptor.0, &mut present, &mut dacl, &mut defaulted) } == 0
|
||||
|| present == 0
|
||||
{
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
let path = path.as_os_str().encode_wide().chain(Some(0)).collect::<Vec<_>>();
|
||||
let error = unsafe {
|
||||
SetNamedSecurityInfoW(
|
||||
path.as_ptr(),
|
||||
SE_FILE_OBJECT,
|
||||
DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
dacl,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if error != 0 {
|
||||
return Err(std::io::Error::from_raw_os_error(error as i32).into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub struct Resources {
|
||||
interrupt: Handle,
|
||||
gate: Handle,
|
||||
job: Handle,
|
||||
interrupt_name: String,
|
||||
gate_name: String,
|
||||
}
|
||||
impl Resources {
|
||||
pub fn new() -> IdeResult<Self> {
|
||||
let interrupt_name = format!("Local\\OpenIDEA-interrupt-{}", Uuid::new_v4());
|
||||
let gate_name = format!("Local\\OpenIDEA-launch-{}", Uuid::new_v4());
|
||||
fn event(name: &str) -> IdeResult<Handle> {
|
||||
let name = name.encode_utf16().chain(Some(0)).collect::<Vec<_>>();
|
||||
// Event-specific rights; owner and SYSTEM only. File inheritance
|
||||
// flags/FA are not used for kernel synchronization objects.
|
||||
let sddl = "D:P(A;;GA;;;OW)(A;;GA;;;SY)\0".encode_utf16().collect::<Vec<_>>();
|
||||
let mut raw = std::ptr::null_mut();
|
||||
if unsafe {
|
||||
ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
||||
sddl.as_ptr(),
|
||||
SDDL_REVISION_1,
|
||||
&mut raw,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
let descriptor = Descriptor(raw);
|
||||
let attrs = SECURITY_ATTRIBUTES {
|
||||
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
|
||||
lpSecurityDescriptor: descriptor.0,
|
||||
bInheritHandle: 0,
|
||||
};
|
||||
let handle = Handle::new(unsafe { CreateEventW(&attrs, 0, 0, name.as_ptr()) })?;
|
||||
if unsafe { GetLastError() } == ERROR_ALREADY_EXISTS {
|
||||
return Err(IdeError::unavailable("kernel event name collision"));
|
||||
}
|
||||
Ok(handle)
|
||||
}
|
||||
let interrupt = event(&interrupt_name)?;
|
||||
let gate = event(&gate_name)?;
|
||||
let job = Handle::new(unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) })?;
|
||||
let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
|
||||
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
if unsafe {
|
||||
SetInformationJobObject(
|
||||
job.raw(),
|
||||
JobObjectExtendedLimitInformation,
|
||||
&info as *const _ as *const _,
|
||||
std::mem::size_of_val(&info) as u32,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
Ok(Self { interrupt, gate, job, interrupt_name, gate_name })
|
||||
}
|
||||
pub fn configure(&self, command: &mut Command) {
|
||||
command.env("OPENIDEA_INTERRUPT_EVENT", &self.interrupt_name).env("OPENIDEA_LAUNCH_EVENT", &self.gate_name);
|
||||
}
|
||||
pub fn assign_and_release(&self, child: &Child) -> IdeResult<()> {
|
||||
let handle = child
|
||||
.raw_handle()
|
||||
.ok_or_else(|| IdeError::unavailable("kernel exited before Windows job assignment"))?;
|
||||
if unsafe { AssignProcessToJobObject(self.job.raw(), handle as HANDLE) } == 0 {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"cannot contain kernel process in owned Windows job: {}",
|
||||
std::io::Error::last_os_error()
|
||||
)));
|
||||
}
|
||||
self.gate.signal()
|
||||
}
|
||||
pub fn interrupt(&self) -> IdeResult<()> {
|
||||
self.interrupt.signal()
|
||||
}
|
||||
pub fn kill_tree(&self) {
|
||||
unsafe {
|
||||
TerminateJobObject(self.job.raw(), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,555 @@
|
||||
use super::process::Process;
|
||||
use super::{ExecutionResult, KernelOutput, KernelState, OutputCallback, StatusCallback};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use jupyter_protocol::{ExecuteRequest, JupyterMessage, KernelInfoRequest, ShutdownRequest};
|
||||
use jupyter_zmq_client::{ClientControlConnection, Connection, DealerSendConnection, RawMessage};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::Value;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc, oneshot};
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::{Instant, MissedTickBehavior};
|
||||
use uuid::Uuid;
|
||||
use zeromq::SocketRecv;
|
||||
|
||||
const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const INTERRUPT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const SEND_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
const MAX_MESSAGE_BYTES: usize = 8 * 1024 * 1024;
|
||||
const MAX_OUTPUT_BYTES: usize = 32 * 1024 * 1024;
|
||||
const MAX_OUTPUT_MESSAGES: usize = 10_000;
|
||||
const QUEUED_MESSAGES: usize = 64;
|
||||
const QUEUED_BYTES: usize = 16 * 1024 * 1024;
|
||||
|
||||
struct Admission(Arc<AtomicBool>);
|
||||
impl Drop for Admission {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(false, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
struct Execution {
|
||||
code: String,
|
||||
cancel: CancellationToken,
|
||||
interrupt: CancellationToken,
|
||||
output: OutputCallback,
|
||||
reply: oneshot::Sender<IdeResult<ExecutionResult>>,
|
||||
_admission: Admission,
|
||||
}
|
||||
|
||||
pub(super) struct Running {
|
||||
pub python: PathBuf,
|
||||
pub stop: CancellationToken,
|
||||
requests: mpsc::Sender<Execution>,
|
||||
task: Option<JoinHandle<()>>,
|
||||
busy: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Running {
|
||||
pub fn spawn(
|
||||
runtime: PathBuf,
|
||||
notebook: PathBuf,
|
||||
python: PathBuf,
|
||||
status: StatusCallback,
|
||||
) -> (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)
|
||||
}
|
||||
|
||||
pub fn is_finished(&self) -> bool {
|
||||
self.task.as_ref().is_none_or(JoinHandle::is_finished)
|
||||
}
|
||||
|
||||
pub async fn execute(
|
||||
&self,
|
||||
code: &str,
|
||||
cancel: CancellationToken,
|
||||
interrupt: CancellationToken,
|
||||
output: OutputCallback,
|
||||
) -> IdeResult<ExecutionResult> {
|
||||
if self.busy.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() {
|
||||
return Err(IdeError::unavailable("previous kernel execution has not drained"));
|
||||
}
|
||||
let (reply, result) = oneshot::channel();
|
||||
let execution = Execution {
|
||||
code: code.to_owned(),
|
||||
cancel,
|
||||
interrupt,
|
||||
output,
|
||||
reply,
|
||||
_admission: Admission(self.busy.clone()),
|
||||
};
|
||||
self.requests.try_send(execution).map_err(|_| IdeError::unavailable("kernel is busy or has exited"))?;
|
||||
result.await.unwrap_or_else(|_| Err(IdeError::unavailable("kernel execution task ended")))
|
||||
}
|
||||
|
||||
pub async fn shutdown(mut self) {
|
||||
self.stop.cancel();
|
||||
if let Some(mut task) = self.task.take()
|
||||
&& tokio::time::timeout(Duration::from_secs(8), &mut task).await.is_err()
|
||||
{
|
||||
task.abort();
|
||||
let _ = task.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Running {
|
||||
fn drop(&mut self) {
|
||||
self.stop.cancel();
|
||||
// Do not abort: supervisor owns graceful shutdown and process reaping.
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Channel {
|
||||
Shell,
|
||||
Iopub,
|
||||
}
|
||||
|
||||
struct Frame {
|
||||
channel: Channel,
|
||||
parent: String,
|
||||
kind: String,
|
||||
content: Value,
|
||||
bytes: usize,
|
||||
_permit: Option<OwnedSemaphorePermit>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Failure {
|
||||
token: CancellationToken,
|
||||
error: Arc<Mutex<Option<IdeError>>>,
|
||||
}
|
||||
impl Failure {
|
||||
fn new() -> Self {
|
||||
Self { token: CancellationToken::new(), error: Arc::new(Mutex::new(None)) }
|
||||
}
|
||||
fn fail(&self, error: IdeError) {
|
||||
self.error.lock().get_or_insert(error);
|
||||
self.token.cancel();
|
||||
}
|
||||
fn error(&self) -> IdeError {
|
||||
self.error.lock().clone().unwrap_or_else(|| IdeError::unavailable("kernel reader stopped"))
|
||||
}
|
||||
}
|
||||
|
||||
struct Readers(Vec<JoinHandle<()>>);
|
||||
impl Drop for Readers {
|
||||
fn drop(&mut self) {
|
||||
for task in &self.0 {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reader<S: SocketRecv + Send + 'static>(
|
||||
mut connection: Connection<S>,
|
||||
channel: Channel,
|
||||
tx: mpsc::Sender<Frame>,
|
||||
failure: Failure,
|
||||
queued: Arc<Semaphore>,
|
||||
) -> JoinHandle<()> {
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let result = receive(&mut connection, channel, &queued).await;
|
||||
match result {
|
||||
Ok(frame) => {
|
||||
if tx.try_send(frame).is_err() {
|
||||
failure.fail(IdeError::unavailable(
|
||||
"kernel output queue overflow; execution stopped to bound memory",
|
||||
));
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
failure.fail(error);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn receive<S: SocketRecv + Send>(
|
||||
connection: &mut Connection<S>,
|
||||
channel: Channel,
|
||||
queued: &Arc<Semaphore>,
|
||||
) -> IdeResult<Frame> {
|
||||
let multipart = connection.socket.recv().await.map_err(protocol)?;
|
||||
let bytes = multipart
|
||||
.iter()
|
||||
.try_fold(0_usize, |sum, part| sum.checked_add(part.len()))
|
||||
.ok_or_else(|| IdeError::unavailable("kernel message size overflow"))?;
|
||||
if bytes > MAX_MESSAGE_BYTES {
|
||||
return Err(IdeError::unavailable("kernel message exceeds 8 MiB limit; execution stopped"));
|
||||
}
|
||||
let permit = queued
|
||||
.clone()
|
||||
.try_acquire_many_owned(bytes as u32)
|
||||
.map_err(|_| IdeError::unavailable("kernel output queue exceeds 16 MiB; execution stopped"))?;
|
||||
// Upstream RawMessage indexes four signed parts without checking length.
|
||||
// Validate framing before calling it, including messages from a bad kernel.
|
||||
let delimiter = multipart
|
||||
.iter()
|
||||
.position(|part| part.as_ref() == b"<IDS|MSG>")
|
||||
.ok_or_else(|| protocol("missing Jupyter message delimiter"))?;
|
||||
if multipart.len() < delimiter + 6 {
|
||||
return Err(protocol("incomplete Jupyter message frames"));
|
||||
}
|
||||
let raw = RawMessage::from_multipart(multipart, &connection.mac).map_err(protocol)?;
|
||||
let header: Value = serde_json::from_slice(&raw.jparts[0]).map_err(protocol)?;
|
||||
let parent: Value = serde_json::from_slice(&raw.jparts[1]).map_err(protocol)?;
|
||||
let kind = header
|
||||
.get("msg_type")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| protocol("missing Jupyter message type"))?
|
||||
.to_owned();
|
||||
let parent = parent.get("msg_id").and_then(Value::as_str).unwrap_or("").to_owned();
|
||||
let content = serde_json::from_slice(&raw.jparts[3]).map_err(protocol)?;
|
||||
Ok(Frame { channel, parent, kind, content, bytes, _permit: Some(permit) })
|
||||
}
|
||||
|
||||
fn protocol(error: impl std::fmt::Display) -> IdeError {
|
||||
IdeError::new(ide_core::error::ErrorKind::Protocol, format!("Jupyter protocol: {error}"))
|
||||
}
|
||||
|
||||
struct Session {
|
||||
process: Process,
|
||||
shell: DealerSendConnection,
|
||||
control: ClientControlConnection,
|
||||
frames: mpsc::Receiver<Frame>,
|
||||
failure: Failure,
|
||||
_readers: Readers,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
async fn connect(
|
||||
runtime: &std::path::Path,
|
||||
notebook: &std::path::Path,
|
||||
python: &std::path::Path,
|
||||
) -> IdeResult<Self> {
|
||||
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)?;
|
||||
let (iopub, shell, control) = tokio::try_join!(
|
||||
jupyter_zmq_client::create_client_iopub_connection(&info, "", &session),
|
||||
jupyter_zmq_client::create_client_shell_connection_with_identity(&info, &session, identity),
|
||||
jupyter_zmq_client::create_client_control_connection(&info, &session),
|
||||
)
|
||||
.map_err(protocol)?;
|
||||
let (shell, shell_recv) = shell.split();
|
||||
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),
|
||||
]);
|
||||
Ok(Self { process, shell, control, frames, failure, _readers: readers })
|
||||
}
|
||||
|
||||
async fn ready(&mut self, stop: &CancellationToken) -> IdeResult<()> {
|
||||
let deadline = Instant::now() + 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;
|
||||
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()))),
|
||||
_ = probe.tick() => {
|
||||
if let Some(message) = self.process.death()? {
|
||||
return Err(IdeError::unavailable(message));
|
||||
}
|
||||
// Only readiness probes are retried, never user execution.
|
||||
// Once the shell replies, retain its ID to await IOPub idle.
|
||||
if !reply {
|
||||
let message: JupyterMessage = KernelInfoRequest {}.into();
|
||||
request = message.header.msg_id.clone();
|
||||
idle = false;
|
||||
send(&mut self.shell, message).await?;
|
||||
} else if !idle {
|
||||
// A slow subscriber can miss the first idle. Probe again
|
||||
// after a reply, proving BOTH live shell and subscription.
|
||||
reply = false;
|
||||
}
|
||||
},
|
||||
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::Iopub && is_idle(&frame) { idle = true; }
|
||||
if reply && idle { return Ok(()); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(
|
||||
&mut self,
|
||||
execution: &mut Execution,
|
||||
stop: &CancellationToken,
|
||||
notebook: &std::path::Path,
|
||||
status: &StatusCallback,
|
||||
) -> IdeResult<ExecutionResult> {
|
||||
if execution.cancel.is_cancelled() || execution.interrupt.is_cancelled() || execution.reply.is_closed() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let request: JupyterMessage = ExecuteRequest {
|
||||
code: std::mem::take(&mut execution.code),
|
||||
allow_stdin: false,
|
||||
stop_on_error: true,
|
||||
..Default::default()
|
||||
}
|
||||
.into();
|
||||
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?;
|
||||
status(notebook, KernelState::Busy, None);
|
||||
let mut completion = Completion::default();
|
||||
let mut budget = Budget::default();
|
||||
let mut interrupted = false;
|
||||
let mut interrupt_deadline = None;
|
||||
let mut death = tokio::time::interval(Duration::from_millis(100));
|
||||
death.set_missed_tick_behavior(MissedTickBehavior::Delay);
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = stop.cancelled() => return Err(IdeError::cancelled()),
|
||||
_ = self.failure.token.cancelled() => return Err(self.failure.error()),
|
||||
_ = execution.cancel.cancelled(), if !interrupted => {
|
||||
self.process.interrupt()?;
|
||||
interrupted = true;
|
||||
interrupt_deadline = Some(Instant::now() + INTERRUPT_TIMEOUT);
|
||||
},
|
||||
_ = execution.interrupt.cancelled(), if !interrupted => {
|
||||
self.process.interrupt()?;
|
||||
interrupted = true;
|
||||
interrupt_deadline = Some(Instant::now() + INTERRUPT_TIMEOUT);
|
||||
},
|
||||
_ = death.tick() => {
|
||||
if execution.reply.is_closed() && !interrupted {
|
||||
self.process.interrupt()?;
|
||||
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"));
|
||||
}
|
||||
if let Some(message) = self.process.death()? { return Err(IdeError::unavailable(message)); }
|
||||
},
|
||||
frame = self.frames.recv() => {
|
||||
let frame = frame.ok_or_else(|| IdeError::unavailable("kernel readers closed during execution"))?;
|
||||
if frame.parent != request_id { continue; }
|
||||
budget.add(frame.bytes)?;
|
||||
completion.observe(&frame, &request_id)?;
|
||||
if frame.channel == Channel::Iopub && is_output(&frame.kind) {
|
||||
(execution.output)(KernelOutput { kind: frame.kind, content: frame.content, msg_id: frame.parent });
|
||||
}
|
||||
if completion.complete() {
|
||||
status(notebook, KernelState::Idle, None);
|
||||
if interrupted || execution.cancel.is_cancelled() || execution.interrupt.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
return Ok(completion.reply.take().expect("complete reply"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn shutdown(&mut self) {
|
||||
// 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 deadline = Instant::now() + Duration::from_millis(750);
|
||||
while Instant::now() < deadline {
|
||||
match self.process.death() {
|
||||
Ok(None) => {}
|
||||
_ => break,
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
self.process.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(connection: &mut DealerSendConnection, message: JupyterMessage) -> IdeResult<()> {
|
||||
tokio::time::timeout(SEND_TIMEOUT, connection.send(message))
|
||||
.await
|
||||
.map_err(|_| IdeError::unavailable("kernel request send timed out; delivery uncertain, not retried"))?
|
||||
.map_err(protocol)
|
||||
}
|
||||
|
||||
fn is_idle(frame: &Frame) -> bool {
|
||||
frame.kind == "status" && frame.content.get("execution_state").and_then(Value::as_str) == Some("idle")
|
||||
}
|
||||
|
||||
fn is_output(kind: &str) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
"stream"
|
||||
| "display_data"
|
||||
| "execute_result"
|
||||
| "error"
|
||||
| "execute_input"
|
||||
| "clear_output"
|
||||
| "update_display_data"
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Completion {
|
||||
reply: Option<ExecutionResult>,
|
||||
idle: bool,
|
||||
}
|
||||
impl Completion {
|
||||
fn observe(&mut self, frame: &Frame, request_id: &str) -> IdeResult<()> {
|
||||
if frame.parent != request_id {
|
||||
return Ok(());
|
||||
}
|
||||
if frame.channel == Channel::Iopub && is_idle(frame) {
|
||||
self.idle = true;
|
||||
}
|
||||
if frame.channel == Channel::Shell && frame.kind == "execute_reply" {
|
||||
let status = frame
|
||||
.content
|
||||
.get("status")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| protocol("execute_reply missing status"))?;
|
||||
if !matches!(status, "ok" | "error" | "abort" | "aborted") {
|
||||
return Err(protocol("invalid execute_reply status"));
|
||||
}
|
||||
let count = match frame.content.get("execution_count") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(value) => Some(
|
||||
value
|
||||
.as_u64()
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.ok_or_else(|| protocol("invalid execution count"))?,
|
||||
),
|
||||
};
|
||||
self.reply = Some(ExecutionResult { status: status.to_owned(), execution_count: count });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn complete(&self) -> bool {
|
||||
self.idle && self.reply.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Budget {
|
||||
bytes: usize,
|
||||
messages: usize,
|
||||
}
|
||||
impl Budget {
|
||||
fn add(&mut self, bytes: usize) -> IdeResult<()> {
|
||||
self.bytes = self.bytes.saturating_add(bytes);
|
||||
self.messages = self.messages.saturating_add(1);
|
||||
if self.bytes > MAX_OUTPUT_BYTES || self.messages > MAX_OUTPUT_MESSAGES {
|
||||
return Err(IdeError::unavailable("kernel output exceeded 32 MiB or 10000 messages; execution stopped"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn supervise(
|
||||
runtime: PathBuf,
|
||||
notebook: PathBuf,
|
||||
python: PathBuf,
|
||||
status: StatusCallback,
|
||||
stop: CancellationToken,
|
||||
mut requests: mpsc::Receiver<Execution>,
|
||||
ready: oneshot::Sender<IdeResult<()>>,
|
||||
) {
|
||||
status(¬ebook, KernelState::Starting, None);
|
||||
let startup = async {
|
||||
let mut session = Session::connect(&runtime, ¬ebook, &python).await?;
|
||||
session.ready(&stop).await?;
|
||||
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"))),
|
||||
};
|
||||
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 error = IdeError::new(error.kind, message);
|
||||
status(¬ebook, KernelState::Dead, Some(error.message.clone()));
|
||||
let _ = ready.send(Err(error));
|
||||
return;
|
||||
}
|
||||
};
|
||||
status(¬ebook, KernelState::Idle, None);
|
||||
if ready.send(Ok(())).is_err() {
|
||||
stop.cancel();
|
||||
}
|
||||
let mut death = tokio::time::interval(Duration::from_millis(100));
|
||||
death.set_missed_tick_behavior(MissedTickBehavior::Delay);
|
||||
let failure = session.failure.clone();
|
||||
let mut reason = None;
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = stop.cancelled() => break,
|
||||
_ = failure.token.cancelled() => { reason = Some(failure.error().message); break; },
|
||||
_ = death.tick() => match session.process.death() {
|
||||
Ok(None) => {},
|
||||
Ok(Some(message)) => { reason = Some(message); break; },
|
||||
Err(error) => { reason = Some(error.message); break; },
|
||||
},
|
||||
request = requests.recv() => {
|
||||
let Some(mut request) = request else { break };
|
||||
let result = session.run(&mut request, &stop, ¬ebook, &status).await;
|
||||
// Cancelled with reply+idle is reusable. Stop cancellation or any
|
||||
// transport/death/overflow error invalidates this generation.
|
||||
let fatal = result.as_ref().err().is_some_and(|e| e.kind != ide_core::error::ErrorKind::Cancelled)
|
||||
|| stop.is_cancelled();
|
||||
if fatal { reason = result.as_ref().err().map(|e| e.message.clone()); }
|
||||
let Execution { reply, _admission, .. } = request;
|
||||
drop(_admission);
|
||||
let _ = reply.send(result);
|
||||
if fatal { break; }
|
||||
},
|
||||
frame = session.frames.recv() => {
|
||||
// Post-idle/background messages are deliberately NOT forwarded.
|
||||
// Keeping this drain alive also prevents stale IDs leaking into
|
||||
// later executions or another process generation.
|
||||
if frame.is_none() { reason = Some("kernel readers closed".into()); break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
requests.close();
|
||||
while let Ok(request) = requests.try_recv() {
|
||||
let _ = request.reply.send(Err(IdeError::unavailable("kernel stopped before execution admission")));
|
||||
}
|
||||
session.shutdown().await;
|
||||
status(¬ebook, KernelState::Dead, reason);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "transport_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,71 @@
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn frame(channel: Channel, parent: &str, kind: &str, content: Value) -> Frame {
|
||||
Frame { channel, parent: parent.into(), kind: kind.into(), content, bytes: 1, _permit: None }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_requires_both_channels_in_either_order_and_ignores_old_requests() {
|
||||
for idle_first in [false, true] {
|
||||
let mut completion = Completion::default();
|
||||
let idle = frame(Channel::Iopub, "current", "status", json!({"execution_state":"idle"}));
|
||||
let reply = frame(Channel::Shell, "current", "execute_reply", json!({"status":"error","execution_count":7}));
|
||||
let old_idle = frame(Channel::Iopub, "old-generation", "status", json!({"execution_state":"idle"}));
|
||||
let old_reply =
|
||||
frame(Channel::Shell, "old-generation", "execute_reply", json!({"status":"ok","execution_count":99}));
|
||||
completion.observe(&old_reply, "current").unwrap();
|
||||
completion.observe(&old_idle, "current").unwrap();
|
||||
assert!(!completion.complete());
|
||||
let (first, second) = if idle_first { (&idle, &reply) } else { (&reply, &idle) };
|
||||
completion.observe(first, "current").unwrap();
|
||||
assert!(!completion.complete(), "one channel cannot finalize execution");
|
||||
completion.observe(second, "current").unwrap();
|
||||
assert!(completion.complete());
|
||||
let result = completion.reply.unwrap();
|
||||
assert_eq!(result.status, "error");
|
||||
assert_eq!(result.execution_count, Some(7));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_channel_cannot_forge_execution_completion() {
|
||||
let mut completion = Completion::default();
|
||||
completion
|
||||
.observe(&frame(Channel::Iopub, "run", "execute_reply", json!({"status":"ok","execution_count":2})), "run")
|
||||
.unwrap();
|
||||
completion.observe(&frame(Channel::Shell, "run", "status", json!({"execution_state":"idle"})), "run").unwrap();
|
||||
assert!(!completion.complete());
|
||||
assert!(completion.reply.is_none());
|
||||
assert!(!completion.idle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_reply_is_rejected_instead_of_reported_as_success() {
|
||||
for content in [
|
||||
json!({"status":"unexpected"}),
|
||||
json!({"execution_count":1}),
|
||||
json!({"status":"ok","execution_count":-1}),
|
||||
json!({"status":"ok","execution_count":4294967296_u64}),
|
||||
] {
|
||||
let mut completion = Completion::default();
|
||||
let error = completion.observe(&frame(Channel::Shell, "run", "execute_reply", content), "run").unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::Protocol);
|
||||
assert!(!completion.complete());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_budget_stops_at_byte_or_message_boundary_without_wrapping() {
|
||||
let mut bytes = Budget::default();
|
||||
bytes.add(MAX_OUTPUT_BYTES).unwrap();
|
||||
assert_eq!(bytes.add(1).unwrap_err().kind, ide_core::error::ErrorKind::Unavailable);
|
||||
let mut messages = Budget::default();
|
||||
for _ in 0..MAX_OUTPUT_MESSAGES {
|
||||
messages.add(0).unwrap();
|
||||
}
|
||||
assert_eq!(messages.add(0).unwrap_err().kind, ide_core::error::ErrorKind::Unavailable);
|
||||
let mut overflow = Budget::default();
|
||||
assert_eq!(overflow.add(usize::MAX).unwrap_err().kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert_eq!(overflow.add(1).unwrap_err().kind, ide_core::error::ErrorKind::Unavailable);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Native notebook documents and owned Jupyter kernel sessions.
|
||||
pub mod document;
|
||||
pub mod kernel;
|
||||
|
||||
pub use document::{NotebookCell, NotebookDocument, NotebookEdit, NotebookSnapshot};
|
||||
@@ -0,0 +1,511 @@
|
||||
use std::{collections::HashSet, path::PathBuf};
|
||||
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_notebook::{NotebookDocument, NotebookEdit, kernel::KernelOutput};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const ORIGINAL: &str = r##"{
|
||||
"unknownRoot": { "escaped": "\u0061", "number": 1e+02 },
|
||||
"nbformat_minor": 5,
|
||||
"metadata": {"custom": [true, {"x": "\u03bb"}]},
|
||||
"cells": [
|
||||
{ "unknownCell": {"keep": "\u0041"}, "source": ["\u0061\n", "b\n", "\u0063"], "id": "first", "metadata": {}, "cell_type": "code", "execution_count": null, "outputs": [] },
|
||||
{ "cell_type": "markdown", "source": "# title", "metadata": {"custom": 3}, "id": "second", "attachments": {"pic.png": {"image/png": "aW1hZ2U="}}, "future": [1, 2] },
|
||||
{ "cell_type": "vendor.future", "source": ["opaque"], "metadata": {}, "id": "third", "vendor": {"raw": "\u0042"} }
|
||||
],
|
||||
"nbformat": 4
|
||||
}"##;
|
||||
|
||||
fn document(text: &str) -> NotebookDocument {
|
||||
NotebookDocument::from_text(PathBuf::from("notebook.ipynb"), text.into()).unwrap()
|
||||
}
|
||||
|
||||
fn apply(doc: &mut NotebookDocument, edit: NotebookEdit) {
|
||||
let version = doc.version();
|
||||
doc.edit(version, edit).unwrap();
|
||||
}
|
||||
|
||||
fn output(kind: &str, content: Value) -> KernelOutput {
|
||||
KernelOutput { kind: kind.into(), content, msg_id: "actual-parent-id".into() }
|
||||
}
|
||||
|
||||
fn emit(doc: &mut NotebookDocument, cell: &str, kind: &str, content: Value) -> Vec<String> {
|
||||
doc.record_output(cell, &output(kind, content)).unwrap()
|
||||
}
|
||||
|
||||
fn two_code_cells() -> NotebookDocument {
|
||||
document(&json!({
|
||||
"nbformat": 4, "nbformat_minor": 5, "metadata": {},
|
||||
"cells": [
|
||||
{"id": "a", "cell_type": "code", "metadata": {}, "source": "a()", "outputs": [], "execution_count": null},
|
||||
{"id": "b", "cell_type": "code", "metadata": {}, "source": ["b()"], "outputs": [], "execution_count": null}
|
||||
]
|
||||
}).to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noop_save_preserves_all_bytes_for_utf8_bom_crlf_and_no_final_newline() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let variants = [
|
||||
ORIGINAL.to_owned(),
|
||||
format!("{}\n", ORIGINAL),
|
||||
ORIGINAL.replace('\n', "\r\n"),
|
||||
format!("\u{feff}{}\r\n", ORIGINAL.replace('\n', "\r\n")),
|
||||
];
|
||||
for (index, text) in variants.iter().enumerate() {
|
||||
let path = dir.path().join(format!("{index}.ipynb"));
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let mut doc = NotebookDocument::load(&path).unwrap();
|
||||
assert!(!doc.snapshot().dirty);
|
||||
assert_eq!(doc.to_text(), *text);
|
||||
let before = doc.version();
|
||||
doc.save().unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), text.as_bytes());
|
||||
assert_eq!(doc.version(), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_list_edit_preserves_unchanged_elements_and_every_other_byte() {
|
||||
let mut doc = document(ORIGINAL);
|
||||
apply(&mut doc, NotebookEdit::SetSource { cell: "first".into(), source: "a\nB\nc".into() });
|
||||
let expected = ORIGINAL.replace(r#"["\u0061\n", "b\n", "\u0063"]"#, r#"["\u0061\n", "B\n", "\u0063"]"#);
|
||||
assert_eq!(doc.to_text(), expected);
|
||||
assert!(doc.snapshot().dirty);
|
||||
let edited_version = doc.version();
|
||||
doc.undo().unwrap();
|
||||
assert_eq!(doc.to_text(), ORIGINAL);
|
||||
assert!(!doc.snapshot().dirty);
|
||||
assert!(doc.version() > edited_version);
|
||||
doc.redo().unwrap();
|
||||
assert_eq!(doc.to_text(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn string_source_stays_a_string_and_attachments_and_unknown_cells_survive() {
|
||||
let mut doc = document(ORIGINAL);
|
||||
apply(&mut doc, NotebookEdit::SetSource { cell: "second".into(), source: "new\n标题".into() });
|
||||
assert_eq!(doc.to_text(), ORIGINAL.replace(r##""# title""##, r#""new\n标题""#));
|
||||
let parsed: Value = serde_json::from_str(&doc.to_text()).unwrap();
|
||||
assert!(parsed["cells"][1]["source"].is_string());
|
||||
assert_eq!(parsed["cells"][1]["attachments"]["pic.png"]["image/png"], "aW1hZ2U=");
|
||||
assert_eq!(parsed["cells"][2]["vendor"]["raw"], "B");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_minor_and_invalid_or_duplicate_persisted_ids_are_not_repaired_on_load_or_edit() {
|
||||
let text = r#"{"nbformat":4,"nbformat_minor":2,"metadata":{},"cells":[{"cell_type":"raw","metadata":{},"source":"one","id":"duplicate"},{"cell_type":"raw","metadata":{},"source":"two","id":"duplicate"},{"cell_type":"raw","metadata":{},"source":"three","id":"bad id"},{"cell_type":"raw","metadata":{},"source":"four"}]}"#;
|
||||
let mut doc = document(text);
|
||||
let before = doc.snapshot();
|
||||
assert_eq!(before.cells.iter().map(|cell| &cell.id).collect::<HashSet<_>>().len(), 4);
|
||||
assert_eq!(doc.to_text(), text);
|
||||
apply(&mut doc, NotebookEdit::SetSource { cell: before.cells[3].id.clone(), source: "changed".into() });
|
||||
let after = doc.snapshot();
|
||||
assert_eq!(
|
||||
before.cells.iter().map(|cell| &cell.id).collect::<Vec<_>>(),
|
||||
after.cells.iter().map(|cell| &cell.id).collect::<Vec<_>>()
|
||||
);
|
||||
apply(&mut doc, NotebookEdit::InsertCell { after: None, cell_type: "code".into() });
|
||||
let parsed: Value = serde_json::from_str(&doc.to_text()).unwrap();
|
||||
assert_eq!(parsed["nbformat_minor"], 2);
|
||||
assert!(parsed["cells"][0].get("id").is_none());
|
||||
assert_eq!(parsed["cells"][1]["id"], "duplicate");
|
||||
assert_eq!(parsed["cells"][2]["id"], "duplicate");
|
||||
assert_eq!(parsed["cells"][3]["id"], "bad id");
|
||||
assert!(parsed["cells"][4].get("id").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_cells_get_valid_ids_only_for_minor_five_and_keep_identity_through_history() {
|
||||
let mut doc = document(ORIGINAL);
|
||||
apply(&mut doc, NotebookEdit::InsertCell { after: Some("first".into()), cell_type: "markdown".into() });
|
||||
let inserted = doc.snapshot().cells[1].id.clone();
|
||||
let parsed: Value = serde_json::from_str(&doc.to_text()).unwrap();
|
||||
assert_eq!(parsed["cells"][1]["id"], inserted);
|
||||
assert!(inserted.len() <= 64 && inserted.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'));
|
||||
doc.undo().unwrap();
|
||||
assert_eq!(doc.to_text(), ORIGINAL);
|
||||
doc.redo().unwrap();
|
||||
assert_eq!(doc.snapshot().cells[1].id, inserted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_and_delete_restore_exact_raw_subtrees_and_container_punctuation() {
|
||||
let mut doc = document(ORIGINAL);
|
||||
apply(&mut doc, NotebookEdit::MoveCell { cell: "third".into(), before: Some("first".into()) });
|
||||
assert_eq!(
|
||||
doc.snapshot().cells.iter().map(|cell| cell.id.as_str()).collect::<Vec<_>>(),
|
||||
["third", "first", "second"]
|
||||
);
|
||||
assert!(doc.to_text().contains(r#""vendor": {"raw": "\u0042"}"#));
|
||||
apply(&mut doc, NotebookEdit::DeleteCell { cell: "first".into() });
|
||||
assert_eq!(doc.snapshot().cells.iter().map(|cell| cell.id.as_str()).collect::<Vec<_>>(), ["third", "second"]);
|
||||
doc.undo().unwrap();
|
||||
doc.undo().unwrap();
|
||||
assert_eq!(doc.to_text(), ORIGINAL);
|
||||
doc.redo().unwrap();
|
||||
doc.redo().unwrap();
|
||||
assert_eq!(doc.snapshot().cells.iter().map(|cell| cell.id.as_str()).collect::<Vec<_>>(), ["third", "second"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_last_cell_and_reinsert_into_empty_notebook_are_supported() {
|
||||
let text = r#"{"nbformat":4,"nbformat_minor":5,"metadata":{},"cells":[ {"id":"only","cell_type":"raw","source":"x","metadata":{}} ]}"#;
|
||||
let mut doc = document(text);
|
||||
apply(&mut doc, NotebookEdit::DeleteCell { cell: "only".into() });
|
||||
assert_eq!(serde_json::from_str::<Value>(&doc.to_text()).unwrap()["cells"], json!([]));
|
||||
doc.undo().unwrap();
|
||||
assert_eq!(doc.to_text(), text);
|
||||
apply(&mut doc, NotebookEdit::DeleteCell { cell: "only".into() });
|
||||
apply(&mut doc, NotebookEdit::InsertCell { after: None, cell_type: "code".into() });
|
||||
assert_eq!(doc.snapshot().cells[0].cell_type, "code");
|
||||
assert_eq!(doc.snapshot().cells[0].outputs, Vec::<Value>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_conversion_keeps_unknown_fields_and_restores_removed_fields_exactly() {
|
||||
let text =
|
||||
ORIGINAL.replace("\"outputs\": []", r#""outputs": [{"output_type":"vendor.output","payload":{"x":"\u0061"}}]"#);
|
||||
let mut doc = document(&text);
|
||||
apply(&mut doc, NotebookEdit::SetCellType { cell: "first".into(), cell_type: "markdown".into() });
|
||||
let converted: Value = serde_json::from_str(&doc.to_text()).unwrap();
|
||||
assert!(converted["cells"][0].get("outputs").is_none());
|
||||
assert!(converted["cells"][0].get("execution_count").is_none());
|
||||
assert_eq!(converted["cells"][0]["unknownCell"]["keep"], "A");
|
||||
doc.undo().unwrap();
|
||||
assert_eq!(doc.to_text(), text);
|
||||
apply(&mut doc, NotebookEdit::SetCellType { cell: "second".into(), cell_type: "code".into() });
|
||||
let converted: Value = serde_json::from_str(&doc.to_text()).unwrap();
|
||||
assert_eq!(converted["cells"][1]["outputs"], json!([]));
|
||||
assert_eq!(converted["cells"][1]["execution_count"], Value::Null);
|
||||
assert_eq!(converted["cells"][1]["attachments"]["pic.png"]["image/png"], "aW1hZ2U=");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_only_revisions_accept_pending_source_edits_but_stale_user_edits_are_rejected() {
|
||||
let mut doc = two_code_cells();
|
||||
let base = doc.version();
|
||||
emit(&mut doc, "a", "stream", json!({"name":"stdout", "text":"hello"}));
|
||||
assert!(doc.version() > base);
|
||||
doc.edit(base, NotebookEdit::SetSource { cell: "a".into(), source: "new source".into() }).unwrap();
|
||||
assert_eq!(doc.snapshot().cells[0].outputs[0]["text"], "hello");
|
||||
let current = doc.version();
|
||||
let stale = doc.edit(base, NotebookEdit::SetSource { cell: "b".into(), source: "stale".into() }).unwrap_err();
|
||||
assert_eq!(stale.kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(doc.version(), current);
|
||||
let future = doc.edit(current + 1, NotebookEdit::DeleteCell { cell: "a".into() }).unwrap_err();
|
||||
assert_eq!(future.kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(doc.snapshot().cells[1].source, "b()");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_undo_preserves_execution_outputs_and_output_does_not_clear_redo() {
|
||||
let mut doc = two_code_cells();
|
||||
let initial_version = doc.version();
|
||||
apply(&mut doc, NotebookEdit::SetSource { cell: "a".into(), source: "print(1)".into() });
|
||||
doc.begin_execution("a").unwrap();
|
||||
emit(&mut doc, "a", "execute_input", json!({"execution_count": 7}));
|
||||
emit(&mut doc, "a", "stream", json!({"name":"stdout", "text":"1\n"}));
|
||||
let output_version = doc.version();
|
||||
doc.undo().unwrap();
|
||||
let state = doc.snapshot();
|
||||
assert_eq!(state.cells[0].source, "a()");
|
||||
assert_eq!(state.cells[0].execution_count, Some(7));
|
||||
assert_eq!(state.cells[0].outputs[0]["text"], "1\n");
|
||||
assert!(state.version > output_version && output_version > initial_version);
|
||||
emit(&mut doc, "a", "stream", json!({"name":"stderr", "text":"later"}));
|
||||
assert!(doc.snapshot().can_redo);
|
||||
doc.redo().unwrap();
|
||||
let state = doc.snapshot();
|
||||
assert_eq!(state.cells[0].source, "print(1)");
|
||||
assert_eq!(state.cells[0].outputs[1]["text"], "later");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_is_rejected_until_execution_batch_is_drained() {
|
||||
let mut doc = two_code_cells();
|
||||
apply(&mut doc, NotebookEdit::SetSource { cell: "a".into(), source: "changed".into() });
|
||||
doc.set_execution_active(true).unwrap();
|
||||
assert!(!doc.snapshot().can_undo);
|
||||
assert_eq!(doc.undo().unwrap_err().kind, ErrorKind::InvalidInput);
|
||||
assert_eq!(doc.redo().unwrap_err().kind, ErrorKind::InvalidInput);
|
||||
assert_eq!(doc.reload().unwrap_err().kind, ErrorKind::InvalidInput);
|
||||
assert!(doc.set_execution_active(true).is_err());
|
||||
doc.set_execution_active(false).unwrap();
|
||||
doc.undo().unwrap();
|
||||
assert_eq!(doc.snapshot().cells[0].source, "a()");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserted_cell_redo_retains_outputs_produced_after_its_creation() {
|
||||
let mut doc = two_code_cells();
|
||||
apply(&mut doc, NotebookEdit::InsertCell { after: None, cell_type: "code".into() });
|
||||
let id = doc.snapshot().cells[0].id.clone();
|
||||
emit(&mut doc, &id, "stream", json!({"name":"stdout", "text":"keep"}));
|
||||
doc.undo().unwrap();
|
||||
doc.redo().unwrap();
|
||||
assert_eq!(doc.snapshot().cells[0].id, id);
|
||||
assert_eq!(doc.snapshot().cells[0].outputs[0]["text"], "keep");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_updates_reach_earlier_cells_and_never_persist_transient_ids() {
|
||||
let mut doc = two_code_cells();
|
||||
let display = json!({"data":{"text/plain":"old", "vendor/mime":{"arbitrary":true}}, "metadata":{"custom":1}, "transient":{"display_id":"shared"}, "vendorField": 9});
|
||||
emit(&mut doc, "a", "display_data", display.clone());
|
||||
emit(&mut doc, "b", "execute_result", {
|
||||
let mut value = display;
|
||||
value["execution_count"] = json!(3);
|
||||
value
|
||||
});
|
||||
let changed = emit(
|
||||
&mut doc,
|
||||
"b",
|
||||
"update_display_data",
|
||||
json!({"data":{"text/plain":"new"}, "metadata":{"custom":2}, "transient":{"display_id":"shared"}}),
|
||||
);
|
||||
assert_eq!(changed.into_iter().collect::<HashSet<_>>(), HashSet::from(["a".to_owned(), "b".to_owned()]));
|
||||
let state = doc.snapshot();
|
||||
assert_eq!(state.cells[0].outputs[0]["data"]["text/plain"], "new");
|
||||
assert_eq!(state.cells[1].outputs[0]["data"]["text/plain"], "new");
|
||||
assert_eq!(state.cells[0].outputs[0]["vendorField"], 9);
|
||||
assert_eq!(state.cells[1].outputs[0]["execution_count"], 3);
|
||||
assert!(!doc.to_text().contains("display_id"));
|
||||
assert!(!doc.to_text().contains("transient"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deferred_clear_is_applied_only_to_next_output_and_removes_display_targets() {
|
||||
let mut doc = two_code_cells();
|
||||
emit(
|
||||
&mut doc,
|
||||
"a",
|
||||
"display_data",
|
||||
json!({"data":{"text/plain":"old"}, "metadata":{}, "transient":{"display_id":"d"}}),
|
||||
);
|
||||
let version = doc.version();
|
||||
assert!(emit(&mut doc, "a", "clear_output", json!({"wait":true})).is_empty());
|
||||
assert_eq!(doc.version(), version);
|
||||
assert_eq!(doc.snapshot().cells[0].outputs[0]["data"]["text/plain"], "old");
|
||||
emit(&mut doc, "a", "execute_input", json!({"execution_count":2}));
|
||||
assert_eq!(doc.snapshot().cells[0].outputs[0]["data"]["text/plain"], "old");
|
||||
assert_eq!(emit(&mut doc, "a", "stream", json!({"name":"stdout","text":"replacement"})), ["a"]);
|
||||
let state = doc.snapshot();
|
||||
assert_eq!(state.cells[0].outputs, vec![json!({"output_type":"stream", "name":"stdout", "text":"replacement"})]);
|
||||
assert!(
|
||||
emit(
|
||||
&mut doc,
|
||||
"b",
|
||||
"update_display_data",
|
||||
json!({"data":{"text/plain":"not resurrected"}, "metadata":{}, "transient":{"display_id":"d"}})
|
||||
)
|
||||
.is_empty()
|
||||
);
|
||||
emit(&mut doc, "a", "clear_output", json!({"wait":false}));
|
||||
assert_eq!(doc.snapshot().cells[0].outputs, Vec::<Value>::new());
|
||||
assert_eq!(doc.snapshot().cells[0].execution_count, Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streams_merge_only_adjacent_same_names_and_errors_and_mime_data_are_retained() {
|
||||
let mut doc = two_code_cells();
|
||||
emit(&mut doc, "a", "stream", json!({"name":"stdout", "text":"one"}));
|
||||
emit(&mut doc, "a", "stream", json!({"name":"stdout", "text":" two"}));
|
||||
emit(&mut doc, "a", "stream", json!({"name":"stderr", "text":"warning"}));
|
||||
emit(&mut doc, "a", "stream", json!({"name":"stdout", "text":"three"}));
|
||||
emit(
|
||||
&mut doc,
|
||||
"a",
|
||||
"error",
|
||||
json!({"ename":"ValueError", "evalue":"bad", "traceback":["line one", "line two"], "vendor":true}),
|
||||
);
|
||||
emit(
|
||||
&mut doc,
|
||||
"a",
|
||||
"display_data",
|
||||
json!({"data":{"image/png":"aW1hZ2U=", "application/vnd.vendor+json":{"x":1}}, "metadata":{"width":100}}),
|
||||
);
|
||||
let state = doc.snapshot();
|
||||
assert_eq!(state.cells[0].outputs[0]["text"], "one two");
|
||||
assert_eq!(state.cells[0].outputs[1]["text"], "warning");
|
||||
assert_eq!(state.cells[0].outputs[2]["text"], "three");
|
||||
assert_eq!(state.cells[0].outputs[3]["traceback"], json!(["line one", "line two"]));
|
||||
assert_eq!(state.cells[0].outputs[3]["vendor"], true);
|
||||
assert_eq!(state.cells[0].outputs[4]["data"]["application/vnd.vendor+json"]["x"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_undo_and_reload_track_the_exact_disk_baseline_and_document_incarnation() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("document.ipynb");
|
||||
std::fs::write(&path, ORIGINAL).unwrap();
|
||||
let mut doc = NotebookDocument::load(&path).unwrap();
|
||||
let id = doc.id().to_owned();
|
||||
apply(&mut doc, NotebookEdit::SetSource { cell: "second".into(), source: "saved".into() });
|
||||
let saved = doc.to_text();
|
||||
assert!(!doc.save().unwrap().dirty);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), saved);
|
||||
assert!(doc.undo().unwrap().dirty);
|
||||
assert_eq!(doc.to_text(), ORIGINAL);
|
||||
let version = doc.version();
|
||||
let reloaded = doc.reload().unwrap();
|
||||
assert_eq!(reloaded.id, id);
|
||||
assert!(reloaded.version > version);
|
||||
assert!(!reloaded.dirty && !reloaded.can_undo && !reloaded.can_redo);
|
||||
assert_eq!(doc.to_text(), saved);
|
||||
assert_ne!(NotebookDocument::load(&path).unwrap().id(), id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_conflict_is_detected_even_when_clean_and_failed_save_retains_history() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("conflict.ipynb");
|
||||
std::fs::write(&path, ORIGINAL).unwrap();
|
||||
let mut doc = NotebookDocument::load(&path).unwrap();
|
||||
std::fs::write(&path, format!("{ORIGINAL}\n")).unwrap();
|
||||
assert_eq!(doc.save().unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
apply(&mut doc, NotebookEdit::SetSource { cell: "second".into(), source: "unsaved".into() });
|
||||
let unsaved = doc.to_text();
|
||||
let version = doc.version();
|
||||
assert_eq!(doc.save().unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(doc.to_text(), unsaved);
|
||||
assert_eq!(doc.version(), version);
|
||||
assert!(doc.snapshot().dirty && doc.snapshot().can_undo);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), format!("{ORIGINAL}\n"));
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert_eq!(doc.save().unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert!(!path.exists());
|
||||
doc.undo().unwrap();
|
||||
assert_eq!(doc.to_text(), ORIGINAL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_source_duplicate_json_keys_unsupported_format_and_invalid_utf8_are_rejected() {
|
||||
for text in [
|
||||
ORIGINAL.replace(r#"["\u0061\n", "b\n", "\u0063"]"#, "[123]"),
|
||||
ORIGINAL.replace("\"nbformat\": 4", "\"nbformat\": 3"),
|
||||
ORIGINAL.replace("\"nbformat\": 4", "\"nbformat\": 4, \"nbformat\": 4"),
|
||||
] {
|
||||
assert!(NotebookDocument::from_text(PathBuf::from("invalid.ipynb"), text).is_err());
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("invalid.ipynb");
|
||||
std::fs::write(&path, [0xff, 0xfe, 0x80]).unwrap();
|
||||
assert!(NotebookDocument::load(&path).is_err());
|
||||
assert_eq!(std::fs::read(&path).unwrap(), [0xff, 0xfe, 0x80]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_kernel_output_does_not_apply_a_pending_clear_or_advance_revision() {
|
||||
let mut doc = two_code_cells();
|
||||
emit(&mut doc, "a", "stream", json!({"name":"stdout", "text":"keep"}));
|
||||
emit(&mut doc, "a", "clear_output", json!({"wait":true}));
|
||||
let before = doc.to_text();
|
||||
let version = doc.version();
|
||||
let error = doc.record_output("a", &output("display_data", json!({"data": {}}))).unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::InvalidInput);
|
||||
assert_eq!(doc.to_text(), before);
|
||||
assert_eq!(doc.version(), version);
|
||||
emit(&mut doc, "a", "stream", json!({"name":"stdout", "text":"replacement"}));
|
||||
assert_eq!(doc.snapshot().cells[0].outputs[0]["text"], "replacement");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn late_output_never_recreates_deleted_cells() {
|
||||
let mut doc = two_code_cells();
|
||||
apply(&mut doc, NotebookEdit::DeleteCell { cell: "a".into() });
|
||||
let before = doc.to_text();
|
||||
let error = doc.record_output("a", &output("stream", json!({"name":"stdout", "text":"late"}))).unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::NotFound);
|
||||
assert_eq!(doc.to_text(), before);
|
||||
assert_eq!(doc.snapshot().cells[0].id, "b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minor_five_existing_duplicate_and_missing_ids_remain_untouched_after_mutation() {
|
||||
let text = ORIGINAL.replace("\"id\": \"second\"", "\"id\": \"first\"").replace(", \"id\": \"third\"", "");
|
||||
let mut doc = document(&text);
|
||||
let state = doc.snapshot();
|
||||
assert_eq!(state.cells.iter().map(|cell| &cell.id).collect::<HashSet<_>>().len(), 3);
|
||||
assert_eq!(doc.to_text(), text);
|
||||
apply(&mut doc, NotebookEdit::SetSource { cell: state.cells[0].id.clone(), source: "changed".into() });
|
||||
apply(&mut doc, NotebookEdit::InsertCell { after: Some(state.cells[2].id.clone()), cell_type: "raw".into() });
|
||||
let parsed: Value = serde_json::from_str(&doc.to_text()).unwrap();
|
||||
assert_eq!(parsed["cells"][0]["id"], "first");
|
||||
assert_eq!(parsed["cells"][1]["id"], "first");
|
||||
assert!(parsed["cells"][2].get("id").is_none());
|
||||
assert_eq!(parsed["cells"][3]["id"], doc.snapshot().cells[3].id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edited_crlf_bom_notebook_preserves_every_unaffected_byte() {
|
||||
let text = format!("\u{feff}{}\r\n", ORIGINAL.replace('\n', "\r\n"));
|
||||
let mut doc = document(&text);
|
||||
apply(&mut doc, NotebookEdit::SetSource { cell: "second".into(), source: "edited".into() });
|
||||
assert_eq!(doc.to_text(), text.replace(r##""# title""##, r#""edited""#));
|
||||
doc.undo().unwrap();
|
||||
assert_eq!(doc.to_text(), text);
|
||||
assert!(!doc.is_dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ineffective_edits_do_not_create_dirty_state_history_or_revisions() {
|
||||
let mut doc = two_code_cells();
|
||||
let version = doc.version();
|
||||
apply(&mut doc, NotebookEdit::SetSource { cell: "a".into(), source: "a()".into() });
|
||||
apply(&mut doc, NotebookEdit::SetCellType { cell: "a".into(), cell_type: "code".into() });
|
||||
apply(&mut doc, NotebookEdit::MoveCell { cell: "a".into(), before: Some("a".into()) });
|
||||
apply(&mut doc, NotebookEdit::MoveCell { cell: "b".into(), before: None });
|
||||
doc.begin_execution("a").unwrap();
|
||||
assert!(emit(&mut doc, "a", "clear_output", json!({"wait":false})).is_empty());
|
||||
let state = doc.snapshot();
|
||||
assert_eq!(state.version, version);
|
||||
assert!(!state.dirty && !state.can_undo && !state.can_redo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_output_replacement_strips_transient_fields_without_discarding_user_redo() {
|
||||
let mut doc = two_code_cells();
|
||||
apply(&mut doc, NotebookEdit::SetSource { cell: "a".into(), source: "changed".into() });
|
||||
doc.undo().unwrap();
|
||||
let base = doc.version();
|
||||
apply(
|
||||
&mut doc,
|
||||
NotebookEdit::SetOutputs {
|
||||
cell: "a".into(),
|
||||
execution_count: Some(4),
|
||||
outputs: vec![
|
||||
json!({"output_type":"vendor.output", "payload":{"keep":true}, "transient":{"display_id":"not persisted"}}),
|
||||
],
|
||||
},
|
||||
);
|
||||
assert!(doc.version() > base);
|
||||
assert!(doc.snapshot().can_redo);
|
||||
assert!(!doc.to_text().contains("transient"));
|
||||
doc.edit(base, NotebookEdit::SetSource { cell: "b".into(), source: "accepted across output-only revision".into() })
|
||||
.unwrap();
|
||||
assert_eq!(doc.snapshot().cells[0].outputs[0]["payload"]["keep"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_stored_outputs_and_failed_output_edits_never_modify_the_document() {
|
||||
let text =
|
||||
ORIGINAL.replace("\"outputs\": []", r#""outputs": [{"output_type":"stream","name":"stdout","text":[123]}]"#);
|
||||
assert!(NotebookDocument::from_text(PathBuf::from("invalid.ipynb"), text).is_err());
|
||||
let mut doc = two_code_cells();
|
||||
let before = doc.to_text();
|
||||
let version = doc.version();
|
||||
let error = doc
|
||||
.edit(
|
||||
version,
|
||||
NotebookEdit::SetOutputs {
|
||||
cell: "a".into(),
|
||||
execution_count: Some(1),
|
||||
outputs: vec![json!({"output_type":"error","ename":"E","evalue":"bad","traceback":[42]})],
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::InvalidInput);
|
||||
assert_eq!(doc.to_text(), before);
|
||||
assert_eq!(doc.version(), version);
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
//! Opt-in native acceptance tests. Set OPENIDEA_TEST_PYTHON to an absolute
|
||||
//! ipykernel-enabled interpreter and run this target with --ignored.
|
||||
//! These tests execute real Python over authenticated native ZeroMQ, no server.
|
||||
|
||||
use ide_core::{CancellationToken, IdeResult, error::ErrorKind};
|
||||
use ide_notebook::kernel::{ExecutionResult, KernelManager, KernelOutput, KernelState};
|
||||
use serde_json::Value;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
type Outputs = Arc<Mutex<Vec<KernelOutput>>>;
|
||||
|
||||
fn python() -> PathBuf {
|
||||
let path = PathBuf::from(
|
||||
std::env::var_os("OPENIDEA_TEST_PYTHON").expect("set OPENIDEA_TEST_PYTHON to a real ipykernel Python"),
|
||||
);
|
||||
assert!(path.is_absolute());
|
||||
path
|
||||
}
|
||||
|
||||
fn manager(root: &Path) -> Arc<KernelManager> {
|
||||
Arc::new(KernelManager::new(root.join("runtime"), Arc::new(|_, _, _| {})))
|
||||
}
|
||||
|
||||
async fn run(
|
||||
manager: &KernelManager,
|
||||
notebook: &Path,
|
||||
python: &Path,
|
||||
code: &str,
|
||||
) -> (IdeResult<ExecutionResult>, Vec<KernelOutput>) {
|
||||
let outputs: Outputs = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = outputs.clone();
|
||||
let result = tokio::time::timeout(
|
||||
Duration::from_secs(45),
|
||||
manager.execute(
|
||||
notebook,
|
||||
python,
|
||||
code,
|
||||
CancellationToken::new(),
|
||||
Arc::new(move |output| sink.lock().unwrap().push(output)),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("real kernel request exceeded test deadline");
|
||||
let outputs = std::mem::take(&mut *outputs.lock().unwrap());
|
||||
(result, outputs)
|
||||
}
|
||||
|
||||
fn json_display(outputs: &[KernelOutput]) -> &Value {
|
||||
&outputs
|
||||
.iter()
|
||||
.find(|output| output.kind == "display_data" && output.content["data"]["application/json"].is_object())
|
||||
.expect("expected native JSON display output")
|
||||
.content["data"]["application/json"]
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_before_admission_cannot_become_an_interpreter_error() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let manager = manager(root.path());
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
let result = manager
|
||||
.execute(
|
||||
&root.path().join("cancelled.ipynb"),
|
||||
&root.path().join("does-not-exist"),
|
||||
"raise RuntimeError('must never execute')",
|
||||
cancel,
|
||||
Arc::new(|_| panic!("cancelled code emitted output")),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result.unwrap_err().kind, ErrorKind::Cancelled);
|
||||
manager.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires OPENIDEA_TEST_PYTHON with real ipykernel"]
|
||||
async fn real_kernel_preserves_state_interpreter_mime_and_request_identity() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let statuses = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = statuses.clone();
|
||||
let manager =
|
||||
KernelManager::new(root.path().join("runtime"), Arc::new(move |_, state, _| sink.lock().unwrap().push(state)));
|
||||
let notebook = root.path().join("native.ipynb");
|
||||
let python = python();
|
||||
let (result, outputs) = run(&manager, ¬ebook, &python, r#"
|
||||
import os, sys
|
||||
from IPython.display import display, update_display, clear_output
|
||||
persisted_value = 41
|
||||
print('native stdout', flush=True)
|
||||
print('native stderr', file=sys.stderr, flush=True)
|
||||
display({'application/x-openidea-test': {'opaque': [1, {'unknown': 'kept'}]}, 'text/plain': 'custom'}, raw=True, display_id='stable-display')
|
||||
update_display({'text/plain': 'updated'}, raw=True, display_id='stable-display')
|
||||
clear_output(wait=True)
|
||||
display({'text/html': '<table><tr><td>42</td></tr></table>', 'image/svg+xml': '<svg xmlns="http://www.w3.org/2000/svg"/>'}, raw=True)
|
||||
persisted_value + 1
|
||||
"#).await;
|
||||
let result = result.unwrap();
|
||||
assert_eq!(result.status, "ok");
|
||||
let request = &outputs.iter().find(|o| o.kind == "execute_input").unwrap().msg_id;
|
||||
assert!(!request.is_empty(), "Jupyter must supply a real parent request ID");
|
||||
assert!(outputs.iter().all(|o| &o.msg_id == request && o.kind != "status"));
|
||||
assert!(outputs.iter().any(|o| o.kind == "stream"
|
||||
&& o.content["name"] == "stdout"
|
||||
&& o.content["text"].as_str().unwrap().contains("native stdout")));
|
||||
assert!(outputs.iter().any(|o| o.kind == "stream"
|
||||
&& o.content["name"] == "stderr"
|
||||
&& o.content["text"].as_str().unwrap().contains("native stderr")));
|
||||
assert!(outputs.iter().any(|o| o.content["data"]["application/x-openidea-test"]["opaque"][1]["unknown"] == "kept"));
|
||||
assert!(
|
||||
outputs
|
||||
.iter()
|
||||
.any(|o| o.kind == "update_display_data" && o.content["transient"]["display_id"] == "stable-display")
|
||||
);
|
||||
assert!(outputs.iter().any(|o| o.kind == "clear_output" && o.content["wait"] == true));
|
||||
assert!(outputs.iter().any(|o| o.kind == "execute_result" && o.content["data"]["text/plain"] == "42"));
|
||||
let (result, next) = run(&manager, ¬ebook, &python,
|
||||
"display({'application/json': {'value': persisted_value, 'executable': sys.executable, 'cwd': os.getcwd()}}, raw=True)").await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
let value = json_display(&next);
|
||||
assert_eq!(value["value"], 41);
|
||||
assert_eq!(
|
||||
std::fs::canonicalize(value["executable"].as_str().unwrap()).unwrap(),
|
||||
std::fs::canonicalize(&python).unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::canonicalize(value["cwd"].as_str().unwrap()).unwrap(),
|
||||
std::fs::canonicalize(root.path()).unwrap()
|
||||
);
|
||||
assert!(next.iter().all(|o| o.msg_id != *request));
|
||||
let (result, errors) = run(&manager, ¬ebook, &python, "input('must not hang')").await;
|
||||
assert_eq!(result.unwrap().status, "error");
|
||||
assert!(errors.iter().any(|o| o.kind == "error" && o.content["ename"] == "StdinNotImplementedError"));
|
||||
let states = statuses.lock().unwrap().clone();
|
||||
assert_eq!(states.first(), Some(&KernelState::Starting));
|
||||
assert!(states.windows(2).any(|pair| pair == [KernelState::Busy, KernelState::Idle]));
|
||||
manager.shutdown().await;
|
||||
}
|
||||
|
||||
async fn long_run(
|
||||
manager: Arc<KernelManager>,
|
||||
notebook: PathBuf,
|
||||
python: PathBuf,
|
||||
cancel: CancellationToken,
|
||||
catches_interrupt: bool,
|
||||
) -> (tokio::task::JoinHandle<IdeResult<ExecutionResult>>, oneshot::Receiver<()>) {
|
||||
let (ready, received) = oneshot::channel();
|
||||
let ready = Mutex::new(Some(ready));
|
||||
let code = if catches_interrupt {
|
||||
"import time, os\nkept_after_interrupt = 123\ntry:\n print('INTERRUPT-READY', flush=True)\n while True: time.sleep(0.01)\nexcept KeyboardInterrupt:\n caught_interrupt = True\n"
|
||||
} else {
|
||||
"import time, os\nkept_after_interrupt = 123\nprint('INTERRUPT-READY', flush=True)\nwhile True: time.sleep(0.01)\n"
|
||||
};
|
||||
let task = tokio::spawn(async move {
|
||||
manager
|
||||
.execute(
|
||||
¬ebook,
|
||||
&python,
|
||||
code,
|
||||
cancel,
|
||||
Arc::new(move |output| {
|
||||
if output.kind == "stream"
|
||||
&& output.content["text"].as_str().is_some_and(|s| s.contains("INTERRUPT-READY"))
|
||||
&& let Some(ready) = ready.lock().unwrap().take()
|
||||
{
|
||||
let _ = ready.send(());
|
||||
}
|
||||
}),
|
||||
)
|
||||
.await
|
||||
});
|
||||
(task, received)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires real ipykernel; Windows must exercise JPY_INTERRUPT_EVENT"]
|
||||
async fn real_interrupt_drains_and_keeps_interpreter_state() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let manager = manager(root.path());
|
||||
let notebook = root.path().join("interrupt.ipynb");
|
||||
let python = python();
|
||||
let (task, ready) =
|
||||
long_run(manager.clone(), notebook.clone(), python.clone(), CancellationToken::new(), false).await;
|
||||
tokio::time::timeout(Duration::from_secs(45), ready).await.unwrap().unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(10), manager.interrupt(¬ebook)).await.unwrap().unwrap();
|
||||
assert_eq!(task.await.unwrap().unwrap_err().kind, ErrorKind::Cancelled);
|
||||
let (result, outputs) = run(
|
||||
&manager,
|
||||
¬ebook,
|
||||
&python,
|
||||
"from IPython.display import display\ndisplay({'application/json': {'kept': kept_after_interrupt}}, raw=True)",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
assert_eq!(json_display(&outputs)["kept"], 123, "interrupt must not emulate success by restarting Python");
|
||||
manager.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires OPENIDEA_TEST_PYTHON with real ipykernel"]
|
||||
async fn token_cancellation_is_not_success_when_python_catches_keyboard_interrupt() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let manager = manager(root.path());
|
||||
let notebook = root.path().join("catch.ipynb");
|
||||
let python = python();
|
||||
let cancel = CancellationToken::new();
|
||||
let (task, ready) = long_run(manager.clone(), notebook.clone(), python.clone(), cancel.clone(), true).await;
|
||||
tokio::time::timeout(Duration::from_secs(45), ready).await.unwrap().unwrap();
|
||||
cancel.cancel();
|
||||
let error = tokio::time::timeout(Duration::from_secs(10), task).await.unwrap().unwrap().unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::Cancelled);
|
||||
let (result, outputs) = run(&manager, ¬ebook, &python,
|
||||
"from IPython.display import display\ndisplay({'application/json': {'caught': caught_interrupt, 'kept': kept_after_interrupt}}, raw=True)").await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
assert_eq!(json_display(&outputs)["caught"], true);
|
||||
assert_eq!(json_display(&outputs)["kept"], 123);
|
||||
manager.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires OPENIDEA_TEST_PYTHON with real ipykernel"]
|
||||
async fn stale_parent_output_is_dropped_and_restart_invalidates_state() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let manager = manager(root.path());
|
||||
let notebook = root.path().join("generation.ipynb");
|
||||
let python = python();
|
||||
let (result, _) = run(
|
||||
&manager,
|
||||
¬ebook,
|
||||
&python,
|
||||
r#"
|
||||
import threading, os
|
||||
from IPython.display import display
|
||||
kernel = get_ipython().kernel
|
||||
old_parent = kernel.get_parent()
|
||||
old_release = threading.Event()
|
||||
old_done = threading.Event()
|
||||
old_state = 99
|
||||
def old_worker():
|
||||
old_release.wait()
|
||||
kernel.session.send(kernel.iopub_socket, 'stream',
|
||||
{'name': 'stdout', 'text': 'OLD-GENERATION\n'},
|
||||
parent=old_parent)
|
||||
old_done.set()
|
||||
threading.Thread(target=old_worker, daemon=True).start()
|
||||
"#,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
// Send an explicitly old protocol parent during the next execution.
|
||||
// Ordinary thread print() can inherit ipykernel's current global parent.
|
||||
let (result, outputs) = run(&manager, ¬ebook, &python,
|
||||
"old_release.set()\nassert old_done.wait(5)\nprint('CURRENT-GENERATION', flush=True)\ndisplay({'application/json': {'pid': os.getpid()}}, raw=True)").await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
assert!(!outputs.iter().any(|o| o.content["text"].as_str().is_some_and(|s| s.contains("OLD-GENERATION"))));
|
||||
assert!(outputs.iter().any(|o| o.content["text"].as_str().is_some_and(|s| s.contains("CURRENT-GENERATION"))));
|
||||
let old_pid = json_display(&outputs)["pid"].as_u64().unwrap();
|
||||
manager.restart(¬ebook).await.unwrap();
|
||||
let (result, outputs) = run(&manager, ¬ebook, &python,
|
||||
"import os\nfrom IPython.display import display\ndisplay({'application/json': {'pid': os.getpid(), 'old': 'old_state' in globals()}}, raw=True)").await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
assert_ne!(json_display(&outputs)["pid"], old_pid);
|
||||
assert_eq!(json_display(&outputs)["old"], false);
|
||||
manager.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires OPENIDEA_TEST_PYTHON with real ipykernel"]
|
||||
async fn process_death_and_output_overflow_fail_explicitly_and_can_restart() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let manager = manager(root.path());
|
||||
let notebook = root.path().join("death.ipynb");
|
||||
let python = python();
|
||||
let (result, _) = run(&manager, ¬ebook, &python, "import os\nos._exit(23)").await;
|
||||
assert!(result.is_err(), "owned process death cannot report execute success");
|
||||
manager.restart(¬ebook).await.unwrap();
|
||||
let (result, _) = run(
|
||||
&manager,
|
||||
¬ebook,
|
||||
&python,
|
||||
"from IPython.display import display\ndisplay({'text/plain': 'x' * (9 * 1024 * 1024)}, raw=True)",
|
||||
)
|
||||
.await;
|
||||
let error = result.unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::Unavailable);
|
||||
assert!(error.message.contains("limit") || error.message.contains("overflow") || error.message.contains("exceed"));
|
||||
manager.restart(¬ebook).await.unwrap();
|
||||
let (result, outputs) = run(&manager, ¬ebook, &python, "print('RECOVERED', flush=True)").await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
assert!(outputs.iter().any(|o| o.content["text"].as_str().is_some_and(|s| s.contains("RECOVERED"))));
|
||||
manager.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires OPENIDEA_TEST_PYTHON and OPENIDEA_TEST_PYTHON_SECOND"]
|
||||
async fn changing_selected_python_recreates_kernel_instead_of_reusing_old_environment() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let manager = manager(root.path());
|
||||
let notebook = root.path().join("selection.ipynb");
|
||||
let first = python();
|
||||
let second = PathBuf::from(
|
||||
std::env::var_os("OPENIDEA_TEST_PYTHON_SECOND").expect("set a second absolute ipykernel interpreter path"),
|
||||
);
|
||||
assert_ne!(first, second);
|
||||
let (result, outputs) = run(&manager, ¬ebook, &first,
|
||||
"import os\nfrom IPython.display import display\nold_environment_state = 1\ndisplay({'application/json': {'pid': os.getpid()}}, raw=True)").await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
let first_pid = json_display(&outputs)["pid"].as_u64().unwrap();
|
||||
let (result, outputs) = run(&manager, ¬ebook, &second,
|
||||
"import os, sys\nfrom IPython.display import display\ndisplay({'application/json': {'pid': os.getpid(), 'executable': sys.executable, 'old': 'old_environment_state' in globals()}}, raw=True)").await;
|
||||
assert_eq!(result.unwrap().status, "ok");
|
||||
let data = json_display(&outputs);
|
||||
assert_ne!(data["pid"], first_pid);
|
||||
assert_eq!(data["old"], false);
|
||||
assert_eq!(
|
||||
std::fs::canonicalize(data["executable"].as_str().unwrap()).unwrap(),
|
||||
std::fs::canonicalize(second).unwrap()
|
||||
);
|
||||
manager.shutdown().await;
|
||||
}
|
||||
@@ -17,7 +17,7 @@ tokio.workspace = true
|
||||
portable-pty.workspace = true
|
||||
parking_lot.workspace = true
|
||||
tracing.workspace = true
|
||||
zip = { version = "=2.4.2", default-features = false, features = ["deflate"] }
|
||||
zip.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
@@ -55,6 +55,8 @@ pub(crate) fn local_path(root: &Path) -> PathBuf {
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct FileDoc {
|
||||
#[serde(default, rename = "suppressed-ids")]
|
||||
suppressed_ids: Vec<String>,
|
||||
#[serde(default)]
|
||||
configurations: Vec<FileConfig>,
|
||||
#[serde(default)]
|
||||
@@ -195,6 +197,10 @@ pub(crate) fn load_templates(root: &Path) -> IdeResult<Vec<RunConfig>> {
|
||||
Ok(read_doc(&config_path(root))?.map(|d| convert(d.templates, false)).unwrap_or_default())
|
||||
}
|
||||
|
||||
pub(crate) fn load_suppressed(root: &Path) -> IdeResult<Vec<String>> {
|
||||
Ok(read_doc(&local_path(root))?.map(|d| d.suppressed_ids).unwrap_or_default())
|
||||
}
|
||||
|
||||
fn to_table(c: &RunConfig) -> Table {
|
||||
let mut t = Table::new();
|
||||
t.insert("id", value(&c.id));
|
||||
@@ -284,13 +290,13 @@ fn to_table(c: &RunConfig) -> Table {
|
||||
}
|
||||
|
||||
/// Replaces the `key` array of tables in the file at `path`, keeping unrelated keys and comments.
|
||||
fn write_array(path: &Path, key: &str, configs: &[&RunConfig]) -> IdeResult<()> {
|
||||
fn write_array(path: &Path, key: &str, configs: &[&RunConfig], suppressed: Option<&[String]>) -> IdeResult<()> {
|
||||
let existing = match fs::read_to_string(path) {
|
||||
Ok(t) => Some(t),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
if existing.is_none() && configs.is_empty() {
|
||||
if existing.is_none() && configs.is_empty() && suppressed.is_none_or(|ids| ids.is_empty()) {
|
||||
return Ok(());
|
||||
}
|
||||
// A file we cannot parse is replaced.
|
||||
@@ -304,6 +310,13 @@ fn write_array(path: &Path, key: &str, configs: &[&RunConfig]) -> IdeResult<()>
|
||||
}
|
||||
doc.insert(key, Item::ArrayOfTables(array));
|
||||
}
|
||||
if let Some(ids) = suppressed {
|
||||
if ids.is_empty() {
|
||||
doc.remove("suppressed-ids");
|
||||
} else {
|
||||
doc.insert("suppressed-ids", value(ids.iter().collect::<Array>()));
|
||||
}
|
||||
}
|
||||
let text = doc.to_string();
|
||||
if existing.as_deref() == Some(text.as_str()) {
|
||||
return Ok(());
|
||||
@@ -343,15 +356,20 @@ fn ignore_local(root: &Path) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn save(root: &Path, configs: &[RunConfig]) -> IdeResult<()> {
|
||||
pub(crate) fn save(root: &Path, configs: &[RunConfig], removed_detected_ids: &[String]) -> IdeResult<()> {
|
||||
let mut suppressed = load_suppressed(root)?;
|
||||
suppressed.extend_from_slice(removed_detected_ids);
|
||||
suppressed.sort();
|
||||
suppressed.dedup();
|
||||
suppressed.retain(|id| !configs.iter().any(|c| &c.id == id));
|
||||
let (local, shared): (Vec<&RunConfig>, Vec<&RunConfig>) = configs.iter().partition(|c| c.extras.local);
|
||||
write_array(&config_path(root), CONFIGURATIONS, &shared)?;
|
||||
if !local.is_empty() {
|
||||
write_array(&config_path(root), CONFIGURATIONS, &shared, None)?;
|
||||
if !local.is_empty() || !suppressed.is_empty() {
|
||||
ignore_local(root)?;
|
||||
}
|
||||
write_array(&local_path(root), CONFIGURATIONS, &local)
|
||||
write_array(&local_path(root), CONFIGURATIONS, &local, Some(&suppressed))
|
||||
}
|
||||
|
||||
pub(crate) fn save_templates(root: &Path, templates: &[RunConfig]) -> IdeResult<()> {
|
||||
write_array(&config_path(root), TEMPLATES, &templates.iter().collect::<Vec<_>>())
|
||||
write_array(&config_path(root), TEMPLATES, &templates.iter().collect::<Vec<_>>(), None)
|
||||
}
|
||||
@@ -10,12 +10,16 @@ use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) fn detect(root: &Path) -> Vec<RunConfig> {
|
||||
detect_excluding(root, &[])
|
||||
}
|
||||
|
||||
pub(crate) fn detect_excluding(root: &Path, excluded_poms: &[PathBuf]) -> Vec<RunConfig> {
|
||||
let mut out = Vec::new();
|
||||
detect_node(root, &mut out);
|
||||
detect_deno(root, &mut out);
|
||||
detect_cargo(root, &mut out);
|
||||
detect_gradle(root, &mut out);
|
||||
detect_maven(root, &mut out);
|
||||
detect_maven(root, excluded_poms, &mut out);
|
||||
detect_go(root, &mut out);
|
||||
detect_python(root, &mut out);
|
||||
detect_make(root, &mut out);
|
||||
@@ -489,9 +493,13 @@ fn collect_texts_from_subdirs(root: &Path, names: &[&str]) -> String {
|
||||
text
|
||||
}
|
||||
|
||||
fn detect_maven(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
fn detect_maven(root: &Path, excluded_poms: &[PathBuf], out: &mut Vec<RunConfig>) {
|
||||
for dir in build_dirs(root, &["pom.xml"]) {
|
||||
detect_maven_build(root, &dir, out);
|
||||
let pom = dir.join("pom.xml");
|
||||
let relative = pom.strip_prefix(root).unwrap_or(&pom);
|
||||
if !excluded_poms.iter().any(|excluded| excluded == relative) {
|
||||
detect_maven_build(root, &dir, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
//! VM options for the JVMs a Gradle build forks (`bootRun`, `run`, `test`): Gradle has no
|
||||
//! command-line switch for them, so a launch passes an init script that adds them to every
|
||||
//! `JavaExec` and `Test` task (`--init-script <file>`). Gradle's own JVM is left alone.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Groovy string literal (single-quoted, `\` and `'` escaped).
|
||||
fn groovy_string(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len() + 2);
|
||||
out.push('\'');
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\'' => out.push_str("\\'"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('\'');
|
||||
out
|
||||
}
|
||||
|
||||
/// The init script adding `jvm_args` (one argument each) to the forked JVMs.
|
||||
pub fn init_script(jvm_args: &[String]) -> String {
|
||||
let list = jvm_args.iter().map(|a| groovy_string(a)).collect::<Vec<_>>().join(", ");
|
||||
format!(
|
||||
"// Written by OpenIDEA: VM options of the run configuration.\n\
|
||||
allprojects {{\n \
|
||||
tasks.withType(JavaExec).configureEach {{ jvmArgs([{list}]) }}\n \
|
||||
tasks.withType(Test).configureEach {{ jvmArgs([{list}]) }}\n\
|
||||
}}\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// Where the scripts are written.
|
||||
pub fn default_dir() -> PathBuf {
|
||||
std::env::temp_dir().join("openidea-gradle")
|
||||
}
|
||||
|
||||
/// Writes the script for `jvm_args` under `dir` (named by its content, so launches share
|
||||
/// it and nothing needs deleting) and returns its path.
|
||||
pub fn write_init_script(dir: &Path, jvm_args: &[String]) -> std::io::Result<PathBuf> {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let text = init_script(jvm_args);
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
text.hash(&mut h);
|
||||
let file = dir.join(format!("jvm-args-{:016x}.init.gradle", h.finish()));
|
||||
if std::fs::read_to_string(&file).is_ok_and(|t| t == text) {
|
||||
return Ok(file);
|
||||
}
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let tmp = file.with_extension(format!("{}.tmp", std::process::id()));
|
||||
std::fs::write(&tmp, &text)?;
|
||||
std::fs::rename(&tmp, &file).inspect_err(|_| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
})?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn args(a: &[&str]) -> Vec<String> {
|
||||
a.iter().map(|s| (*s).to_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adds_each_argument_to_java_exec_and_test_tasks() {
|
||||
let script = init_script(&args(&["-Ddemo.flag=on", "--add-opens", "java.base/java.lang=ALL-UNNAMED"]));
|
||||
let list = "['-Ddemo.flag=on', '--add-opens', 'java.base/java.lang=ALL-UNNAMED']";
|
||||
assert!(script.contains(&format!("tasks.withType(JavaExec).configureEach {{ jvmArgs({list}) }}")), "{script}");
|
||||
assert!(script.contains(&format!("tasks.withType(Test).configureEach {{ jvmArgs({list}) }}")), "{script}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escapes_quotes_backslashes_and_keeps_spaces_and_dollars() {
|
||||
let script = init_script(&args(&[r"-Dpath=C:\Program Files\app", "-Dq=it's", "-Dv=${x}"]));
|
||||
assert!(script.contains(r"'-Dpath=C:\\Program Files\\app'"), "{script}");
|
||||
assert!(script.contains(r"'-Dq=it\'s'"), "{script}");
|
||||
// Single-quoted Groovy strings don't interpolate.
|
||||
assert!(script.contains("'-Dv=${x}'"), "{script}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_one_file_per_content() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let a = write_init_script(dir.path(), &args(&["-Xmx1g"])).unwrap();
|
||||
let again = write_init_script(dir.path(), &args(&["-Xmx1g"])).unwrap();
|
||||
let b = write_init_script(dir.path(), &args(&["-Xmx2g"])).unwrap();
|
||||
assert_eq!(a, again);
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(std::fs::read_to_string(&a).unwrap(), init_script(&args(&["-Xmx1g"])));
|
||||
assert!(a.to_string_lossy().ends_with(".init.gradle"));
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,11 @@
|
||||
mod config;
|
||||
mod detect;
|
||||
pub mod envfile;
|
||||
pub mod gradle_jvm;
|
||||
pub mod java_cmdline;
|
||||
pub mod junit;
|
||||
mod output_encoding;
|
||||
mod process;
|
||||
pub mod python_path;
|
||||
mod utf8;
|
||||
pub mod which;
|
||||
pub mod wrap;
|
||||
@@ -188,6 +189,11 @@ pub fn detect(root: &Path) -> Vec<RunConfig> {
|
||||
detect::detect(root)
|
||||
}
|
||||
|
||||
/// Detects configurations excluding the supplied project-relative Maven POM paths.
|
||||
pub fn detect_excluding(root: &Path, excluded_poms: &[PathBuf]) -> Vec<RunConfig> {
|
||||
detect::detect_excluding(root, excluded_poms)
|
||||
}
|
||||
|
||||
/// Reads `<root>/.openidea/run.toml`; a missing file yields no configs.
|
||||
pub fn load_user_configs(root: &Path) -> IdeResult<Vec<RunConfig>> {
|
||||
config::load(root)
|
||||
@@ -196,7 +202,22 @@ pub fn load_user_configs(root: &Path) -> IdeResult<Vec<RunConfig>> {
|
||||
/// Writes `<root>/.openidea/run.toml` (and the workspace-local `run.local.toml` for
|
||||
/// configurations not stored as project files), preserving unrelated content.
|
||||
pub fn save_user_configs(root: &Path, configs: &[RunConfig]) -> IdeResult<()> {
|
||||
config::save(root, configs)
|
||||
config::save(root, configs, &[])
|
||||
}
|
||||
|
||||
/// Detected ids explicitly removed in this workspace.
|
||||
pub fn load_suppressed_config_ids(root: &Path) -> IdeResult<Vec<String>> {
|
||||
config::load_suppressed(root)
|
||||
}
|
||||
|
||||
/// Saves user configurations and suppresses explicitly removed detections.
|
||||
/// Saving a configuration with a suppressed id restores that id.
|
||||
pub fn save_user_configs_with_removals(
|
||||
root: &Path,
|
||||
configs: &[RunConfig],
|
||||
removed_detected_ids: &[String],
|
||||
) -> IdeResult<()> {
|
||||
config::save(root, configs, removed_detected_ids)
|
||||
}
|
||||
|
||||
/// Configuration templates (per-type defaults for new configurations) from `run.toml`.
|
||||
@@ -217,3 +238,23 @@ pub fn system_env() -> BTreeMap<String, String> {
|
||||
pub fn user_configs_path(root: &Path) -> PathBuf {
|
||||
config::config_path(root)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod linkage_tests {
|
||||
#[test]
|
||||
fn detection_skips_unlinked_maven_roots() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
for name in ["a", "b"] {
|
||||
std::fs::create_dir(tmp.path().join(name)).unwrap();
|
||||
std::fs::write(tmp.path().join(name).join("pom.xml"), "<project/>").unwrap();
|
||||
}
|
||||
let configs = super::detect_excluding(tmp.path(), &["a/pom.xml".into()]);
|
||||
assert!(configs.iter().any(|c| c.kind == "maven"));
|
||||
assert!(
|
||||
configs
|
||||
.iter()
|
||||
.filter(|c| c.kind == "maven")
|
||||
.all(|c| c.cwd.as_ref().is_some_and(|d| d.as_ref() == std::path::Path::new("b")))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
//! Makes the output of JVM and Python processes match the console's encoding.
|
||||
//!
|
||||
//! On Windows both write piped output in the ANSI code page (GBK on a Chinese
|
||||
//! system: `javac` errors, Maven / Gradle logs, `print`), while the console decodes
|
||||
//! the configured encoding (UTF-8 by default). They are told which one to use:
|
||||
//! `java` through `stdout.encoding` / `stderr.encoding` (JDK 19+) and their
|
||||
//! `sun.*` forerunners (JDK 8–18), Maven and Gradle through `MAVEN_OPTS` /
|
||||
//! `GRADLE_OPTS`, Python through `PYTHONIOENCODING`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const JAVA_PROPERTIES: &[&str] = &["stdout.encoding", "stderr.encoding", "sun.stdout.encoding", "sun.stderr.encoding"];
|
||||
|
||||
/// What a launch needs: `-D` options to put first on a `java` command line, and
|
||||
/// environment variables to set.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct EncodingFix {
|
||||
pub java_args: Vec<String>,
|
||||
pub env: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
fn is_utf8(encoding: &str) -> bool {
|
||||
matches!(encoding.to_ascii_lowercase().replace('_', "-").as_str(), "utf-8" | "utf8")
|
||||
}
|
||||
|
||||
fn java_options(encoding: &str) -> Vec<String> {
|
||||
JAVA_PROPERTIES.iter().map(|p| format!("-D{p}={encoding}")).collect()
|
||||
}
|
||||
|
||||
fn sets_java_encoding(text: &str) -> bool {
|
||||
JAVA_PROPERTIES.iter().any(|p| text.contains(&format!("-D{p}=")))
|
||||
}
|
||||
|
||||
/// The options for a launch of `program` (`args`, environment `vars` over the
|
||||
/// `inherited` one) whose output is decoded as `encoding`; nothing when the
|
||||
/// process already writes it (UTF-8 off Windows) or the user chose the options.
|
||||
pub fn fix(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
vars: &BTreeMap<String, String>,
|
||||
inherited: impl Fn(&str) -> Option<String>,
|
||||
encoding: &str,
|
||||
windows: bool,
|
||||
) -> EncodingFix {
|
||||
let encoding = encoding.trim();
|
||||
let mut out = EncodingFix::default();
|
||||
if encoding.is_empty() || (!windows && is_utf8(encoding)) {
|
||||
return out;
|
||||
}
|
||||
let current = |key: &str| vars.get(key).cloned().or_else(|| inherited(key));
|
||||
let name = crate::wrap::program_name(program).to_ascii_lowercase();
|
||||
match name.as_str() {
|
||||
"java" | "javaw" => {
|
||||
if !args.iter().any(|a| sets_java_encoding(a))
|
||||
&& !current("JDK_JAVA_OPTIONS").is_some_and(|o| sets_java_encoding(&o))
|
||||
{
|
||||
out.java_args = java_options(encoding);
|
||||
}
|
||||
}
|
||||
"mvn" | "mvnw" | "mvnd" | "gradle" | "gradlew" => {
|
||||
let key = if name.starts_with("gradle") { "GRADLE_OPTS" } else { "MAVEN_OPTS" };
|
||||
let opts = current(key).unwrap_or_default();
|
||||
if !sets_java_encoding(&opts) {
|
||||
let added = java_options(encoding).join(" ");
|
||||
let value = if opts.trim().is_empty() { added } else { format!("{} {added}", opts.trim()) };
|
||||
out.env.push((key.to_owned(), value));
|
||||
}
|
||||
}
|
||||
_ if is_python(&name) && current("PYTHONIOENCODING").is_none_or(|v| v.trim().is_empty()) => {
|
||||
out.env.push(("PYTHONIOENCODING".to_owned(), encoding.to_owned()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `python`, `python3`, `python3.12`, `py`, and the runners that start one.
|
||||
fn is_python(name: &str) -> bool {
|
||||
name == "python"
|
||||
|| name == "py"
|
||||
|| name.strip_prefix("python").is_some_and(|v| v.chars().all(|c| c.is_ascii_digit() || c == '.'))
|
||||
|| matches!(name, "uv" | "poetry" | "pdm" | "pytest" | "pipenv")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn run(program: &str, args: &[&str], vars: &[(&str, &str)], encoding: &str, windows: bool) -> EncodingFix {
|
||||
let args: Vec<String> = args.iter().map(|a| (*a).to_owned()).collect();
|
||||
let vars: BTreeMap<String, String> = vars.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
|
||||
fix(program, &args, &vars, |_| None, encoding, windows)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_launches_write_the_console_encoding_on_windows() {
|
||||
let expected = [
|
||||
"-Dstdout.encoding=UTF-8",
|
||||
"-Dstderr.encoding=UTF-8",
|
||||
"-Dsun.stdout.encoding=UTF-8",
|
||||
"-Dsun.stderr.encoding=UTF-8",
|
||||
];
|
||||
// The reported case: a source-file launch through the Oracle `javapath` shim.
|
||||
let java = "C:/Program Files/Common Files/Oracle/Java/javapath/java.exe";
|
||||
for program in [java, "java", "javaw.exe", r"C:\jdk\bin\java.exe"] {
|
||||
let f = run(program, &["Main.java"], &[], "UTF-8", true);
|
||||
assert_eq!(f.java_args, expected, "{program}");
|
||||
assert!(f.env.is_empty());
|
||||
}
|
||||
assert_eq!(run("java", &["-cp", "x", "a.Main"], &[], "GBK", true).java_args[0], "-Dstdout.encoding=GBK");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_changes_where_output_already_matches() {
|
||||
for (program, args) in [("java", vec!["Main.java"]), ("mvn", vec!["package"]), ("python3", vec!["a.py"])] {
|
||||
assert_eq!(run(program, &args, &[], "UTF-8", false), EncodingFix::default(), "{program}");
|
||||
assert_eq!(run(program, &args, &[], "utf8", false), EncodingFix::default(), "{program}");
|
||||
assert_eq!(run(program, &args, &[], "", true), EncodingFix::default(), "{program}");
|
||||
}
|
||||
for program in ["node", "cargo", "go", "npm.cmd", "cmd.exe"] {
|
||||
assert_eq!(run(program, &[], &[], "UTF-8", true), EncodingFix::default(), "{program}");
|
||||
}
|
||||
// A console set to another encoding elsewhere still gets it.
|
||||
assert_eq!(run("java", &["Main"], &[], "GBK", false).java_args.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_chosen_by_the_user_win() {
|
||||
assert!(run("java", &["-Dstdout.encoding=GBK", "Main"], &[], "UTF-8", true).java_args.is_empty());
|
||||
assert!(
|
||||
run("java", &["Main"], &[("JDK_JAVA_OPTIONS", "-Dsun.stdout.encoding=GBK")], "UTF-8", true)
|
||||
.java_args
|
||||
.is_empty()
|
||||
);
|
||||
assert!(run("mvn.cmd", &[], &[("MAVEN_OPTS", "-Dstdout.encoding=GBK")], "UTF-8", true).env.is_empty());
|
||||
assert!(run("python.exe", &[], &[("PYTHONIOENCODING", "gbk")], "UTF-8", true).env.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_tools_and_python_get_environment_variables() {
|
||||
let opts =
|
||||
"-Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8";
|
||||
for program in ["mvn.cmd", "mvnw.cmd", r"C:\maven\bin\mvn.cmd"] {
|
||||
assert_eq!(
|
||||
run(program, &["package"], &[], "UTF-8", true).env,
|
||||
[("MAVEN_OPTS".to_owned(), opts.to_owned())]
|
||||
);
|
||||
}
|
||||
for program in ["gradlew.bat", "gradle.bat"] {
|
||||
assert_eq!(run(program, &["build"], &[], "UTF-8", true).env, [("GRADLE_OPTS".to_owned(), opts.to_owned())]);
|
||||
}
|
||||
// Existing options are kept, from the configuration or the inherited environment.
|
||||
let f = run("mvn.cmd", &[], &[("MAVEN_OPTS", "-Xmx1g")], "UTF-8", true);
|
||||
assert_eq!(f.env, [("MAVEN_OPTS".to_owned(), format!("-Xmx1g {opts}"))]);
|
||||
let inherited =
|
||||
fix("gradlew.bat", &[], &BTreeMap::new(), |k| (k == "GRADLE_OPTS").then(|| "-Xmx2g".into()), "UTF-8", true);
|
||||
assert_eq!(inherited.env, [("GRADLE_OPTS".to_owned(), format!("-Xmx2g {opts}"))]);
|
||||
for program in ["python.exe", "python3", "python3.12", "py.exe", "uv.exe", "poetry"] {
|
||||
assert_eq!(
|
||||
run(program, &[], &[], "UTF-8", true).env,
|
||||
[("PYTHONIOENCODING".to_owned(), "UTF-8".to_owned())],
|
||||
"{program}"
|
||||
);
|
||||
}
|
||||
assert_eq!(run("python3", &[], &[], "GBK", false).env, [("PYTHONIOENCODING".to_owned(), "GBK".to_owned())]);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 536 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача