дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 13:32:29 +02:00
Порівняти коміти
115
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
56d9788747 | ||
|
|
ef1b159544 | ||
|
|
7bfba926c2 | ||
|
|
1042f5fa56 | ||
|
|
fdad01034c | ||
|
|
6dddfde3bc | ||
|
|
0324bc368d | ||
|
|
96c6e65aad | ||
|
|
6eebd895ea | ||
|
|
cfad729dbd | ||
|
|
bd905c6689 | ||
|
|
7138becb3a | ||
|
|
6f7d2ce34d | ||
|
|
719961e34e | ||
|
|
11c432fc23 | ||
|
|
0b8698e47c | ||
|
|
f595a7abf0 | ||
|
|
fe7fa7d505 | ||
|
|
e998e2ca8e | ||
|
|
18424b322f | ||
|
|
daee26e680 | ||
|
|
5886e055b4 | ||
|
|
8d4b360933 | ||
|
|
f6704b53f6 | ||
|
|
91da88d09d | ||
|
|
5ab91245dd | ||
|
|
fb063c1f84 | ||
|
|
f926390d2e | ||
|
|
9b66744e72 | ||
|
|
071f768635 | ||
|
|
bbe9cf7a86 | ||
|
|
c10d2f0732 | ||
|
|
ec02a121e9 | ||
|
|
12eb2db641 | ||
|
|
2735d45d7e | ||
|
|
60262c92ba | ||
|
|
ca472742bf | ||
|
|
023408eb26 | ||
|
|
92c0e304cd | ||
|
|
3d534b447d | ||
|
|
89a3359aaf | ||
|
|
d88c4c87b6 | ||
|
|
197c7d6141 | ||
|
|
c61bb2b56d | ||
|
|
b9429858a6 | ||
|
|
c1e9707c7e | ||
|
|
a483ea77f4 | ||
|
|
de36b46660 | ||
|
|
5918605b2b | ||
|
|
f69d394480 | ||
|
|
eb078a0a19 | ||
|
|
5a884d7cba | ||
|
|
2ba2f33232 | ||
|
|
c9bb5a3169 | ||
|
|
bfbc70a438 | ||
|
|
e74edbcedc | ||
|
|
ebeb6476eb | ||
|
|
b8b245da5f | ||
|
|
5aeadcc888 | ||
|
|
edc750174b | ||
|
|
cdff357fdd | ||
|
|
de971848ab | ||
|
|
90cb56e9f8 | ||
|
|
baa0171d8a | ||
|
|
0d493fb515 | ||
|
|
a56add66ea | ||
|
|
2d568980c5 | ||
|
|
7920a4985e | ||
|
|
d6c7e7edc4 | ||
|
|
b1c69d1991 | ||
|
|
a869acdca2 | ||
|
|
fb3a037b7e | ||
|
|
dfaa784513 | ||
|
|
67e58f61b6 | ||
|
|
e75deb11c0 | ||
|
|
94b67515a5 | ||
|
|
a0b2678466 | ||
|
|
e3dc7e950b | ||
|
|
0a53c7b864 | ||
|
|
d4447c7aba | ||
|
|
9740edbfd4 | ||
|
|
b49b0e5c98 | ||
|
|
c88e379c8b | ||
|
|
db63c6c93b | ||
|
|
54a7962043 | ||
|
|
7c3b9824e6 | ||
|
|
0450de5321 | ||
|
|
fadd2a78aa | ||
|
|
53f5ecb233 | ||
|
|
0b079af75d | ||
|
|
6dab294dbf | ||
|
|
fc0ca1e029 | ||
|
|
fe024713da | ||
|
|
42c7834023 | ||
|
|
96f73c82da | ||
|
|
854c81e49b | ||
|
|
b19922b71d | ||
|
|
afab9d0ba2 | ||
|
|
04ed8712b5 | ||
|
|
971b520399 | ||
|
|
c67363ec6b | ||
|
|
2568772700 | ||
|
|
536f85b9df | ||
|
|
e5c5915f2e | ||
|
|
ca2bf89f86 | ||
|
|
735fe5dd30 | ||
|
|
0cfd17979b | ||
|
|
41165bb8c0 | ||
|
|
91264713e7 | ||
|
|
71a4f7cb63 | ||
|
|
dfa632cf18 | ||
|
|
f1425854fb | ||
|
|
752650b971 | ||
|
|
d33ee53c92 | ||
|
|
57eac70018 |
No files matched your search
+2
-21
@@ -149,27 +149,8 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": [
|
||||
"evals/**/*.ts",
|
||||
"perf/**/*.ts",
|
||||
"smoke/**/*.ts",
|
||||
"src/features/vcs/**/*.ts",
|
||||
"src/features/vcs/**/*.tsx",
|
||||
"src/features/run/**/*.ts",
|
||||
"src/features/run/**/*.tsx",
|
||||
"src/features/database/**/*.ts",
|
||||
"src/features/database/**/*.tsx",
|
||||
"src/features/analysis/**/*.ts",
|
||||
"src/features/analysis/**/*.tsx",
|
||||
"src/features/project-tree/**/*.ts",
|
||||
"src/features/project-tree/**/*.tsx",
|
||||
"src/features/http-client/**/*.ts",
|
||||
"src/features/http-client/**/*.tsx",
|
||||
"src/platform/**/*.ts",
|
||||
"src/platform/**/*.tsx",
|
||||
"src/features/debugger/**/*.ts",
|
||||
"src/features/debugger/**/*.tsx"
|
||||
],
|
||||
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
|
||||
"excludeFiles": ["e2e/**"],
|
||||
"rules": {
|
||||
"no-await-in-loop": "error"
|
||||
}
|
||||
|
||||
Створено
+54
-48
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4172,7 +4172,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4184,7 +4184,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4195,7 +4195,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4213,7 +4213,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4227,7 +4227,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4238,7 +4238,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4249,25 +4249,29 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"libc",
|
||||
"portable-pty",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"specta",
|
||||
"specta-typescript",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4280,7 +4284,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4309,7 +4313,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4348,7 +4352,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4361,7 +4365,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4375,7 +4379,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4395,7 +4399,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-flutter"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
@@ -4406,7 +4410,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4418,7 +4422,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4431,7 +4435,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4450,7 +4454,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4526,7 +4530,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
@@ -4545,7 +4549,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4568,7 +4572,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4580,7 +4584,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4596,7 +4600,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4605,7 +4609,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4616,7 +4620,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4675,7 +4679,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4704,7 +4708,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4723,7 +4727,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
@@ -4744,7 +4748,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4766,7 +4770,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4780,7 +4784,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4800,7 +4804,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4824,7 +4828,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4840,7 +4844,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4866,7 +4870,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4887,7 +4891,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4900,7 +4904,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4925,7 +4929,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4938,7 +4942,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4953,7 +4957,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4967,7 +4971,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4980,10 +4984,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
"http",
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
"libc",
|
||||
@@ -5001,7 +5007,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5023,7 +5029,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5050,7 +5056,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5066,7 +5072,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6695,7 +6701,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -6,6 +6,24 @@
|
||||
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
|
||||
## Agent logos
|
||||
|
||||
The `src/ui/openidea/agents/` logos of agents listed in the
|
||||
[ACP agent registry](https://github.com/agentclientprotocol/registry) (`agoragentic-acp`, `amp-acp`,
|
||||
`antigravity-acp`, `autohand`, `bob`, `cline`, `codebuddy-code`, `cortex-code`, `corust-agent`,
|
||||
`crow-cli`, `deepagents`, `devin`, `dimcode`, `dirac`, `factory-droid`, `fast-agent`, `glm-acp-agent`,
|
||||
`grok-build`, `harn`, `junie`, `kilo`, `kimchi`, `minimax-code`, `minion-code`, `muse-code`, `nova`,
|
||||
`pi-acp`, `poolside`, `sigit`, `stakpak`, `vtcode`) are the registry's icons, with a root `fill`
|
||||
moved onto a group. The registry is licensed under Apache-2.0; the logos remain trademarks of
|
||||
their owners.
|
||||
|
||||
## Microsoft ConPTY
|
||||
|
||||
`crates/ide-core/resources/conpty/` contains the unmodified Microsoft Windows Console
|
||||
ConPTY runtime 1.25.260930003, embedded in Windows builds. Copyright (c) Microsoft
|
||||
Corporation. Licensed under MIT; see its [license](crates/ide-core/resources/conpty/LICENSE)
|
||||
and [package provenance](crates/ide-core/resources/conpty/README.md).
|
||||
|
||||
## Project Lombok
|
||||
|
||||
`java/lombok/lombok-1.18.48-openidea.3.jar` contains Project Lombok v1.18.48 with the Equinox
|
||||
|
||||
@@ -2291,14 +2291,25 @@ impl AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops sending events to UI sinks (project closing).
|
||||
pub fn detach_sinks(&self) {
|
||||
self.shared.sinks.write().clear();
|
||||
}
|
||||
|
||||
/// Stops every agent (project closed).
|
||||
pub fn shutdown(&self) {
|
||||
for task in self.tasks.read().values() {
|
||||
task.kill();
|
||||
// What arrived after the last save (a subagent's late updates).
|
||||
task.persist();
|
||||
self.detach_sinks();
|
||||
let tasks: Vec<_> = self.tasks.read().values().cloned().collect();
|
||||
for task in tasks {
|
||||
let was_live = task.kill().is_some();
|
||||
if was_live {
|
||||
// Persist late subagent updates and cleared live background state.
|
||||
task.persist();
|
||||
} else {
|
||||
// Flush pending delayed saves without rewriting untouched or archived tasks.
|
||||
task.save();
|
||||
}
|
||||
}
|
||||
self.shared.sinks.write().clear();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -505,7 +505,16 @@ impl Shim {
|
||||
"_openidea/context_usage" => {
|
||||
let session = self.session(¶ms)?;
|
||||
let proc = session.st.lock().proc.clone().ok_or_else(|| internal("Claude Code is not running"))?;
|
||||
rt.block_on(proc.control(json!({ "subtype": "get_context_usage" }))).map_err(internal)
|
||||
let usage = rt.block_on(proc.control(json!({ "subtype": "get_context_usage" }))).map_err(internal)?;
|
||||
// The meter shows the same numbers as these details from now on.
|
||||
let n = |k: &str| usage.get(k).and_then(Value::as_u64);
|
||||
if let (Some(used), Some(size)) = (n("totalTokens"), n("maxTokens").filter(|m| *m > 0)) {
|
||||
let update = session.st.lock().tr.on_context_usage(used, size);
|
||||
if let Some(shim) = session.shim() {
|
||||
shim.notify(vec![update]);
|
||||
}
|
||||
}
|
||||
Ok(usage)
|
||||
}
|
||||
"_openidea/stop_task" => {
|
||||
let session = self.session(¶ms)?;
|
||||
|
||||
@@ -1148,6 +1148,24 @@ fn a_compaction_replaces_the_context_usage() {
|
||||
assert!(t.on_result(&result).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_codes_own_window_wins_over_the_results_context_window() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), true);
|
||||
let assistant = |model: &str| {
|
||||
json!({"type": "assistant", "parent_tool_use_id": null,
|
||||
"message": {"id": "m1", "model": model, "content": [], "usage": {"input_tokens": 900, "output_tokens": 100}}})
|
||||
};
|
||||
t.on_message(&assistant("x"));
|
||||
let result = json!({"modelUsage": {"x": {"contextWindow": 1_000_000}, "y": {"contextWindow": 200_000}}});
|
||||
assert_eq!(t.on_result(&result)[0].update["size"], 1_000_000);
|
||||
// `get_context_usage` reports the window Claude Code compacts against.
|
||||
assert_eq!(t.on_context_usage(1000, 400_000).update["size"], 400_000);
|
||||
assert_eq!(t.on_result(&result)[0].update["size"], 400_000);
|
||||
// Another model: its own window again until Claude Code reports one for it.
|
||||
t.on_message(&assistant("y"));
|
||||
assert_eq!(t.on_result(&result)[0].update["size"], 200_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rate_limits_and_cost() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), false);
|
||||
|
||||
@@ -58,6 +58,10 @@ pub(super) struct Translator {
|
||||
pub used: Option<u64>,
|
||||
pub model: Option<String>,
|
||||
windows: HashMap<String, u64>,
|
||||
/// The window Claude Code itself counts against (`get_context_usage` `maxTokens`) and the
|
||||
/// model it was read for. It can be smaller than the model's `contextWindow` in a `result`
|
||||
/// (its compaction threshold follows this one), so it wins while the model is the same.
|
||||
context_max: Option<(Option<String>, u64)>,
|
||||
/// The session's cost so far in USD, as the last `result` reported it.
|
||||
cost_usd: Option<f64>,
|
||||
}
|
||||
@@ -77,6 +81,7 @@ impl Translator {
|
||||
used: None,
|
||||
model: None,
|
||||
windows: HashMap::new(),
|
||||
context_max: None,
|
||||
cost_usd: None,
|
||||
}
|
||||
}
|
||||
@@ -571,6 +576,7 @@ impl Translator {
|
||||
/// The context usage Claude Code reports (`get_context_usage`), as a usage update.
|
||||
pub fn on_context_usage(&mut self, used: u64, size: u64) -> Update {
|
||||
self.used = Some(used);
|
||||
self.context_max = Some((self.model.clone(), size));
|
||||
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
|
||||
if let Some(amount) = self.cost_usd {
|
||||
update["cost"] = json!({ "amount": amount, "currency": "USD" });
|
||||
@@ -580,13 +586,14 @@ impl Translator {
|
||||
|
||||
fn usage_update(&self) -> Option<Update> {
|
||||
let used = self.used?;
|
||||
let size = self
|
||||
.model
|
||||
.as_ref()
|
||||
.and_then(|m| {
|
||||
self.windows
|
||||
.get(m)
|
||||
.or_else(|| self.windows.iter().find(|(k, _)| k.starts_with(m.as_str())).map(|(_, v)| v))
|
||||
let own = self.context_max.as_ref().filter(|(model, _)| *model == self.model).map(|(_, size)| size);
|
||||
let size = own
|
||||
.or_else(|| {
|
||||
self.model.as_ref().and_then(|m| {
|
||||
self.windows
|
||||
.get(m)
|
||||
.or_else(|| self.windows.iter().find(|(k, _)| k.starts_with(m.as_str())).map(|(_, v)| v))
|
||||
})
|
||||
})
|
||||
.or_else(|| (self.windows.len() == 1).then(|| self.windows.values().next()).flatten())?;
|
||||
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
|
||||
|
||||
@@ -751,3 +751,47 @@ async fn stop_ends_a_turn_left_running_only_by_background_shells() {
|
||||
assert_eq!(res["stopReason"], "cancelled");
|
||||
assert!(!server.calls.lock().iter().any(|(m, _)| m == "session.abort"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skills() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates, move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
let meta = json!({
|
||||
"openidea": {
|
||||
"skills": {
|
||||
"copilotSkillDirectories": ["/farm/task-1/copilot"],
|
||||
"copilotDisabledSkills": ["muted", "off"],
|
||||
}
|
||||
}
|
||||
});
|
||||
let _: Value =
|
||||
client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [], "_meta": meta }), None).await.unwrap();
|
||||
let _: Value = client
|
||||
.request(
|
||||
"session/load",
|
||||
json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [], "_meta": meta }),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let calls = server.calls.lock();
|
||||
for method in ["session.create", "session.resume"] {
|
||||
let params = calls.iter().find_map(|(m, p)| (m == method).then_some(p)).expect(method);
|
||||
assert_eq!(params["skillDirectories"], json!(["/farm/task-1/copilot"]), "{method}: {params}");
|
||||
assert_eq!(params["disabledSkills"], json!(["muted", "off"]), "{method}: {params}");
|
||||
assert!(params.get("enableConfigDiscovery").is_none(), "{method} must not auto-enable workspace MCP discovery");
|
||||
}
|
||||
}
|
||||
@@ -649,11 +649,14 @@ pub struct Delivery {
|
||||
|
||||
/// Stages the skills a session of `provider` runs with into `farm` — linking (copying on
|
||||
/// Windows, where directory symlinks need Developer Mode) every active skill folder into
|
||||
/// the CLI's tree — and reports what to hand the CLI. Skills the CLI discovers natively
|
||||
/// (its own folders of the working directory and the home) are not staged again: it already
|
||||
/// sees them, and seeing both would list one skill twice. Skills `off` are never staged;
|
||||
/// the CLI's native disable (where it has one) receives their names or paths. An ACP
|
||||
/// agent gets nothing here: its `/` menu is filtered instead.
|
||||
/// the CLI's tree — and reports what to hand the CLI. For Claude Code and Codex, skills
|
||||
/// the CLI discovers natively (its own folders of the working directory and the home) are
|
||||
/// not staged again so the CLI does not see duplicates. For Copilot (`copilot --headless`),
|
||||
/// config discovery is off by default (enabling it would also auto-load workspace `.mcp.json`
|
||||
/// outside OpenIDEA's MCP approvals), so every active `Auto` skill is staged into
|
||||
/// `skillDirectories`. Skills `off` are never staged; the CLI's native disable (where it has
|
||||
/// one) receives their names or paths. An ACP agent gets nothing here: its `/` menu is
|
||||
/// filtered instead.
|
||||
pub fn stage(
|
||||
farm: &Path,
|
||||
provider: &str,
|
||||
@@ -705,7 +708,7 @@ pub fn stage(
|
||||
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
|
||||
link_skill(&tree.join(name), path)?;
|
||||
}
|
||||
if let Some(tree) = copilot_tree.as_ref().filter(|_| !native_copilot(&state.skill, &cwd, home)) {
|
||||
if let Some(tree) = copilot_tree.as_ref() {
|
||||
link_skill(&tree.join(name), path)?;
|
||||
}
|
||||
if let Some(tree) = codex_tree.as_ref().filter(|_| !native_codex(&state.skill, &cwd, home)) {
|
||||
@@ -794,29 +797,6 @@ fn native_claude(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Copilot natively scans `.github/skills`, `.agents/skills` and `.claude/skills` in `cwd`,
|
||||
/// plus `~/.copilot` and `~/.agents/skills` in `home`. `.openidea/skills` is NOT native.
|
||||
fn native_copilot(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
let target = skill.path.0.as_path();
|
||||
for rel in [".github/skills", ".agents/skills", ".claude/skills"] {
|
||||
let root = cwd.join(rel);
|
||||
if is_under(target, &root) || direct_link_matches(&root, &skill.name, target) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if let Some(h) = home {
|
||||
let h = dunce::canonicalize(h).unwrap_or_else(|_| h.to_path_buf());
|
||||
if is_under(target, &h.join(".copilot"))
|
||||
|| is_under(target, &h.join(".agents/skills"))
|
||||
|| direct_link_matches(&h.join(".copilot/skills"), &skill.name, target)
|
||||
|| direct_link_matches(&h.join(".agents/skills"), &skill.name, target)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Codex natively scans `.codex/skills` and `.agents/skills` in `cwd` and `home`.
|
||||
fn native_codex(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
let target = skill.path.0.as_path();
|
||||
@@ -1232,8 +1212,9 @@ mod tests {
|
||||
true,
|
||||
);
|
||||
|
||||
//For a local session, `.github/skills`, `.agents/skills` and `~/.agents/skills` are
|
||||
// already scanned natively by Copilot; `.openidea/skills` and `~/.codex/skills` are staged.
|
||||
// Copilot headless does not run disk config discovery unless explicitly opted in, so
|
||||
// every active `Auto` skill — including `.github/skills`, `.agents/skills`, `~/.agents/skills`,
|
||||
// `~/.copilot/installed-plugins`, `.openidea/skills`, and `~/.codex/skills` — must be staged.
|
||||
let mut states = states;
|
||||
std::fs::create_dir_all(repo.join(".openidea/skills/ideonly")).unwrap();
|
||||
states.push(AgentSkillState {
|
||||
@@ -1241,6 +1222,13 @@ mod tests {
|
||||
mode: AgentSkillMode::Auto,
|
||||
origin: AgentSkillOrigin::None,
|
||||
});
|
||||
let copilot_plugin_skills = home.join(".copilot/installed-plugins/_direct/azure/skills");
|
||||
std::fs::create_dir_all(copilot_plugin_skills.join("azure-ai")).unwrap();
|
||||
states.push(AgentSkillState {
|
||||
skill: skill("azure-ai", AgentSkillSource::CopilotUser, &copilot_plugin_skills),
|
||||
mode: AgentSkillMode::Auto,
|
||||
origin: AgentSkillOrigin::None,
|
||||
});
|
||||
|
||||
let farm = farm_dir(&root.join("store"), "task-1");
|
||||
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
|
||||
@@ -1249,7 +1237,7 @@ mod tests {
|
||||
let staged = listed(&claude_tree);
|
||||
assert_eq!(
|
||||
staged,
|
||||
["codexy", "gh", "ideonly", "lint", "muted", "tdd"],
|
||||
["azure-ai", "codexy", "gh", "ideonly", "lint", "muted", "tdd"],
|
||||
"everything but the off one: none is native to Claude here, and slash-only needs the folder"
|
||||
);
|
||||
|
||||
@@ -1259,8 +1247,8 @@ mod tests {
|
||||
let copilot_staged = listed(&farm.join("copilot"));
|
||||
assert_eq!(
|
||||
copilot_staged,
|
||||
["codexy", "ideonly"],
|
||||
"`gh` (.github), `tdd` (.agents) and `lint` (~/.agents) are native to Copilot; `.openidea` & `~/.codex` are staged"
|
||||
["azure-ai", "codexy", "gh", "ideonly", "lint", "tdd"],
|
||||
"all active Auto skills (including .github, .agents, ~/.agents, and ~/.copilot/installed-plugins) are staged for Copilot headless"
|
||||
);
|
||||
assert_eq!(
|
||||
delivery.codex_off,
|
||||
@@ -1276,12 +1264,12 @@ mod tests {
|
||||
]
|
||||
);
|
||||
|
||||
// A worktree task: the repo's skills are untracked, so workspace skills are staged now.
|
||||
// A worktree task also stages all active workspace, user, and plugin skills.
|
||||
let worktree = root.join("wt");
|
||||
std::fs::create_dir_all(&worktree).unwrap();
|
||||
let _ = stage(&farm, "copilot", &states, &worktree, Some(&home)).unwrap();
|
||||
let copilot_staged = listed(&farm.join("copilot"));
|
||||
assert!(copilot_staged.contains(&"gh".to_string()) && copilot_staged.contains(&"tdd".to_string()));
|
||||
assert_eq!(copilot_staged, ["azure-ai", "codexy", "gh", "ideonly", "lint", "tdd"]);
|
||||
|
||||
// Slash-only reaches Claude as `user-invocable-only`, off as `off`.
|
||||
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
|
||||
@@ -1289,7 +1277,7 @@ mod tests {
|
||||
assert_eq!(settings["skillOverrides"]["muted"], "user-invocable-only");
|
||||
assert_eq!(settings["skillOverrides"]["off"], "off");
|
||||
|
||||
// Restaging after a session turned `lint` off drops its link and leaves the skill.
|
||||
// Restaging after a session turned `lint` off drops its link and leaves the skill on disk.
|
||||
let session = BTreeMap::from([("lint".to_owned(), AgentSkillMode::Off)]);
|
||||
let restated = resolve(
|
||||
states.iter().map(|s| s.skill.clone()).collect(),
|
||||
@@ -1299,10 +1287,14 @@ mod tests {
|
||||
true,
|
||||
);
|
||||
stage(&farm, "claude", &restated, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(listed(&claude_tree), ["codexy", "gh", "ideonly", "muted", "tdd"]);
|
||||
assert_eq!(listed(&claude_tree), ["azure-ai", "codexy", "gh", "ideonly", "muted", "tdd"]);
|
||||
assert!(home.join(".agents/skills/lint").is_dir());
|
||||
assert!(farm.join("copilot").is_dir(), "restaging Claude's tree leaves Copilot's alone");
|
||||
|
||||
let delivery = stage(&farm, "copilot", &restated, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(listed(&farm.join("copilot")), ["azure-ai", "codexy", "gh", "ideonly", "tdd"]);
|
||||
assert_eq!(delivery.copilot_disabled_skills, ["lint", "muted", "off"]);
|
||||
|
||||
// An ACP agent gets no farm.
|
||||
let delivery = stage(&farm, "cursor-acp", &states, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(delivery, Delivery::default());
|
||||
|
||||
@@ -1632,6 +1632,47 @@ async fn shutdown_writes_the_saves_still_waiting_and_a_delete_drops_them() {
|
||||
assert_eq!(saved_title(&kept_path).as_deref(), Some("renamed"));
|
||||
}
|
||||
|
||||
/// Closing a project with many restored/archived tasks must not rewrite tasks that never changed.
|
||||
#[tokio::test]
|
||||
async fn shutdown_skips_rewriting_untouched_restored_tasks() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let untouched = idle_task(&mgr, "untouched").await;
|
||||
let archived = idle_task(&mgr, "archived").await;
|
||||
mgr.archive(&archived.id).unwrap();
|
||||
let dirty = idle_task(&mgr, "dirty").await;
|
||||
mgr.shutdown();
|
||||
|
||||
let (untouched_path, archived_path, dirty_path) =
|
||||
(task_file(tmp.path(), &untouched.id), task_file(tmp.path(), &archived.id), task_file(tmp.path(), &dirty.id));
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let before_untouched = FILE_WRITES.lock().get(&untouched_path).copied().unwrap_or(0);
|
||||
let before_archived = FILE_WRITES.lock().get(&archived_path).copied().unwrap_or(0);
|
||||
let before_dirty = FILE_WRITES.lock().get(&dirty_path).copied().unwrap_or(0);
|
||||
|
||||
let dirty_handle = restored.task(&dirty.id).unwrap();
|
||||
dirty_handle.state.lock().task.title = "updated".into();
|
||||
dirty_handle.persist_soon();
|
||||
|
||||
restored.shutdown();
|
||||
|
||||
assert_eq!(
|
||||
FILE_WRITES.lock().get(&untouched_path).copied().unwrap_or(0),
|
||||
before_untouched,
|
||||
"untouched task should not be rewritten on shutdown"
|
||||
);
|
||||
assert_eq!(
|
||||
FILE_WRITES.lock().get(&archived_path).copied().unwrap_or(0),
|
||||
before_archived,
|
||||
"archived task should not be rewritten on shutdown"
|
||||
);
|
||||
assert!(
|
||||
FILE_WRITES.lock().get(&dirty_path).copied().unwrap_or(0) > before_dirty,
|
||||
"pending persist_soon task must still be flushed on shutdown"
|
||||
);
|
||||
assert_eq!(saved_title(&dirty_path).as_deref(), Some("updated"));
|
||||
}
|
||||
|
||||
/// Archiving saves the task as it is, including changes nobody asked to be saved.
|
||||
#[tokio::test]
|
||||
async fn archiving_saves_the_task_before_it_returns() {
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::io::Read;
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// `(byte length, mtime, blake3 hex)`; the hash is recorded for files inside the project only.
|
||||
type Stamp = (u64, SystemTime, Option<String>);
|
||||
pub(crate) type Stamp = (u64, SystemTime, Option<String>);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LaunchFingerprint {
|
||||
@@ -182,7 +182,7 @@ fn collect(
|
||||
}
|
||||
|
||||
/// Scans every input, storing project inputs relative to the project.
|
||||
pub(super) fn scan_all(
|
||||
pub(crate) fn scan_all(
|
||||
root: &Path,
|
||||
inputs: Vec<PathBuf>,
|
||||
cancel: &CancellationToken,
|
||||
@@ -282,6 +282,11 @@ pub(super) fn module_fingerprint(
|
||||
}
|
||||
|
||||
impl LaunchFingerprint {
|
||||
/// The fingerprint of `parameters` and the files under `inputs` (see [`scan_all`]).
|
||||
pub(crate) fn new(parameters: String, files: BTreeMap<PathBuf, Option<Stamp>>) -> Self {
|
||||
LaunchFingerprint { version: 2, parameters, files }
|
||||
}
|
||||
|
||||
/// Folders (relative to the project) of the Maven projects whose POM is an input.
|
||||
pub(super) fn project_dirs(&self) -> impl Iterator<Item = &Path> {
|
||||
self.files
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! background with cancellation and parses the compiler output into messages
|
||||
//! for the Build tool window, the Problems view and the editor.
|
||||
|
||||
mod fingerprint;
|
||||
pub(crate) mod fingerprint;
|
||||
mod launch_resources;
|
||||
mod modules;
|
||||
mod parse;
|
||||
@@ -236,10 +236,13 @@ pub fn plan(
|
||||
let project_name = root.file_name().map_or_else(|| "project".to_owned(), |n| n.to_string_lossy().into_owned());
|
||||
let module_dir = match file {
|
||||
Some(f) => {
|
||||
let scope = model
|
||||
.gradle
|
||||
.iter()
|
||||
.flat_map(|g| std::iter::once(root.join(&g.dir)).chain(g.projects.iter().map(|p| root.join(&p.dir))))
|
||||
let maven_dirs = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| normalize(&root.join(&p.dir))));
|
||||
let gradle_dirs = model.gradle.iter().flat_map(|g| {
|
||||
std::iter::once(normalize(&root.join(&g.dir)))
|
||||
.chain(g.projects.iter().map(|p| normalize(&root.join(&p.dir))))
|
||||
});
|
||||
let scope = maven_dirs
|
||||
.chain(gradle_dirs)
|
||||
.filter(|dir| f.starts_with(dir))
|
||||
.max_by_key(|dir| dir.components().count())
|
||||
.unwrap_or_else(|| root.to_path_buf());
|
||||
@@ -251,10 +254,13 @@ pub fn plan(
|
||||
None => None,
|
||||
};
|
||||
let dir = module_dir.clone().unwrap_or_else(|| root.to_path_buf());
|
||||
// A folder of sibling projects has no build file itself; its Maven projects are built one by one.
|
||||
let system = detect_dir(&dir, model, root)
|
||||
.or((!model.gradle.is_empty()).then_some(BuildSystem::Gradle))
|
||||
.or_else(|| model.maven.as_ref().filter(|m| !m.projects.is_empty()).map(|_| BuildSystem::Maven))
|
||||
let direct_system = detect_dir(&dir, model, root);
|
||||
let has_gradle = !model.gradle.is_empty();
|
||||
let has_maven = model.maven.as_ref().is_some_and(|m| !m.projects.is_empty());
|
||||
// A folder of sibling projects has no build file itself; build every linked Gradle and Maven project in it.
|
||||
let system = direct_system
|
||||
.or(has_gradle.then_some(BuildSystem::Gradle))
|
||||
.or(has_maven.then_some(BuildSystem::Maven))
|
||||
.ok_or_else(|| {
|
||||
IdeError::not_found("no supported build system (Maven, Gradle, .NET, Cargo, Go, TypeScript, CMake) found")
|
||||
})?;
|
||||
@@ -267,17 +273,26 @@ pub fn plan(
|
||||
),
|
||||
None => project_name,
|
||||
};
|
||||
let steps = match system {
|
||||
BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref(), cache, cancel)?,
|
||||
BuildSystem::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?,
|
||||
BuildSystem::Cargo => cargo_steps(&dir, kind),
|
||||
// Go builds the file's package (a module holds many).
|
||||
BuildSystem::Go => go_steps(file.and_then(Path::parent).unwrap_or(&dir), kind)?,
|
||||
BuildSystem::TypeScript => ts_steps(&dir, kind),
|
||||
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
|
||||
BuildSystem::Dotnet => dotnet_steps(&dir, kind)?,
|
||||
// Never detected from a folder: it comes from the Project Structure (`structure_plan`).
|
||||
BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")),
|
||||
let steps = if module_dir.is_none() && direct_system.is_none() && has_gradle && has_maven {
|
||||
let mut combined = gradle_steps(root, model, kind, None)?;
|
||||
combined.extend(maven_steps(root, model, kind, None, cache, cancel)?);
|
||||
combined
|
||||
} else {
|
||||
match system {
|
||||
BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref(), cache, cancel)?,
|
||||
BuildSystem::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?,
|
||||
BuildSystem::Cargo => cargo_steps(&dir, kind),
|
||||
// Go builds the file's package (a module holds many); a directory target builds itself.
|
||||
BuildSystem::Go => {
|
||||
let pkg = file.map(|f| if f.is_dir() { f } else { f.parent().unwrap_or(f) }).unwrap_or(&dir);
|
||||
go_steps(pkg, kind)?
|
||||
}
|
||||
BuildSystem::TypeScript => ts_steps(&dir, kind),
|
||||
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
|
||||
BuildSystem::Dotnet => dotnet_steps(&dir, kind)?,
|
||||
// Never detected from a folder: it comes from the Project Structure (`structure_plan`).
|
||||
BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")),
|
||||
}
|
||||
};
|
||||
Ok(BuildPlan { system, title, steps })
|
||||
}
|
||||
@@ -845,6 +860,28 @@ fn reactor_projects<'a>(m: &'a maven::MavenModel, top: &'a maven::MavenProject)
|
||||
projects
|
||||
}
|
||||
|
||||
/// A step running Maven, its output parsed as Maven's.
|
||||
pub(crate) fn maven_build_step(program: &str, args: &[&str], cwd: &Path) -> BuildStep {
|
||||
BuildStep::new(program, args, cwd, Format::Maven)
|
||||
}
|
||||
|
||||
pub(crate) fn gradle_build_step(program: &str, args: &[&str], cwd: &Path) -> BuildStep {
|
||||
BuildStep::new(program, args, cwd, Format::Gradle)
|
||||
}
|
||||
|
||||
/// The linked reactor root building the project at `module` (project-relative).
|
||||
pub(crate) fn maven_reactor_dir<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
|
||||
maven_reactor(m, module)
|
||||
}
|
||||
|
||||
/// The projects of the reactor `top`.
|
||||
pub(crate) fn reactor_projects_of<'a>(
|
||||
m: &'a maven::MavenModel,
|
||||
top: &'a maven::MavenProject,
|
||||
) -> Vec<&'a maven::MavenProject> {
|
||||
reactor_projects(m, top)
|
||||
}
|
||||
|
||||
fn maven_reactor<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
|
||||
m.projects.iter().filter(|p| !p.aggregated).find(|top| reactor_projects(m, top).iter().any(|p| p.dir == module))
|
||||
}
|
||||
@@ -1890,4 +1927,92 @@ mod tests {
|
||||
assert_eq!(launch_class_dirs(BuildSystem::Gradle, m, true)[0], m.join("build/classes/kotlin/test"));
|
||||
assert_eq!(launch_class_dirs(BuildSystem::Maven, m, true), [m.join("target/classes")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polyglot_root_targets_selected_subproject_or_combines_sibling_builds() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("polyglot");
|
||||
write(&root, "Cargo.toml", "[package]\nname = \"root\"\nversion = \"0.1.0\"\n");
|
||||
write(
|
||||
&root,
|
||||
"fixtures/java-app/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>app</artifactId><version>1</version></project>",
|
||||
);
|
||||
write(&root, "fixtures/kotlin-gradle/build.gradle.kts", "plugins { kotlin(\"jvm\") }\n");
|
||||
let model = crate::load(&root, &tmp.path().join("cache"), None);
|
||||
|
||||
let maven = plan(
|
||||
&root,
|
||||
&model,
|
||||
BuildKind::Build,
|
||||
Some(&root.join("fixtures/java-app")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(maven.system, BuildSystem::Maven);
|
||||
assert_eq!(maven.steps.len(), 1);
|
||||
assert_eq!(maven.steps[0].cwd, root.join("fixtures/java-app"));
|
||||
|
||||
let gradle = plan(
|
||||
&root,
|
||||
&model,
|
||||
BuildKind::Build,
|
||||
Some(&root.join("fixtures/kotlin-gradle")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(gradle.system, BuildSystem::Gradle);
|
||||
assert_eq!(gradle.steps.len(), 1);
|
||||
assert_eq!(gradle.steps[0].cwd, root.join("fixtures/kotlin-gradle"));
|
||||
|
||||
let cargo = plan(&root, &model, BuildKind::Build, Some(&root), None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(cargo.system, BuildSystem::Cargo);
|
||||
assert_eq!(cargo.steps[0].cwd, root);
|
||||
|
||||
// Folder without a root build file builds both linked Gradle and Maven subprojects on Build Project.
|
||||
let mixed = tmp.path().join("mixed");
|
||||
write(&mixed, "gradle-app/build.gradle.kts", "plugins { java }\n");
|
||||
write(
|
||||
&mixed,
|
||||
"maven-app/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>m</artifactId><version>1</version></project>",
|
||||
);
|
||||
let mixed_model = crate::load(&mixed, &tmp.path().join("cache2"), None);
|
||||
let all = plan(&mixed, &mixed_model, BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(all.steps.len(), 2);
|
||||
assert_eq!(all.steps[0].cwd, mixed.join("gradle-app"));
|
||||
assert_eq!(all.steps[1].cwd, mixed.join("maven-app"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_directory_target_builds_that_package_without_stepping_to_parent() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("go-app");
|
||||
write(&root, "go.mod", "module example.com/app\n\ngo 1.22\n");
|
||||
write(&root, "cmd/server/main.go", "package main\nfunc main() {}\n");
|
||||
|
||||
let pkg = plan(
|
||||
&root,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
Some(&root.join("cmd/server")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(pkg.system, BuildSystem::Go);
|
||||
assert_eq!(pkg.steps[0].cwd, root);
|
||||
assert_eq!(pkg.steps[0].args, ["build", "./cmd/server/..."]);
|
||||
|
||||
let whole =
|
||||
plan(&root, &BuildModel::default(), BuildKind::Build, Some(&root), None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
assert_eq!(whole.steps[0].cwd, root);
|
||||
assert_eq!(whole.steps[0].args, ["build", "./..."]);
|
||||
}
|
||||
}
|
||||
@@ -364,9 +364,9 @@ pub fn parse_reported_projects(output: &str) -> Vec<ReportedProject> {
|
||||
output.lines().filter_map(|l| serde_json::from_str(l.trim_end().strip_prefix(MODEL_LINE)?).ok()).collect()
|
||||
}
|
||||
|
||||
/// Source roots of the reported source sets: `(absolute folder, is test, is resources)`.
|
||||
pub fn reported_source_roots(reported: &[ReportedProject]) -> Vec<(PathBuf, ReportedRoot)> {
|
||||
let mut out: Vec<(PathBuf, ReportedRoot)> = Vec::new();
|
||||
/// Source roots of the reported source sets: `(absolute folder, role, absolute folder of its project)`.
|
||||
pub fn reported_source_roots(reported: &[ReportedProject]) -> Vec<(PathBuf, ReportedRoot, PathBuf)> {
|
||||
let mut out: Vec<(PathBuf, ReportedRoot, PathBuf)> = Vec::new();
|
||||
for p in reported {
|
||||
for set in &p.source_sets {
|
||||
let (src, res) = if set.test {
|
||||
@@ -377,14 +377,14 @@ pub fn reported_source_roots(reported: &[ReportedProject]) -> Vec<(PathBuf, Repo
|
||||
for (dir, kind) in set.src.iter().map(|d| (d, src)).chain(set.res.iter().map(|d| (d, res))) {
|
||||
let dir = PathBuf::from(dir);
|
||||
// A folder shared by `main` and another set is `main`'s, as in IDEA.
|
||||
if !out.iter().any(|(d, _)| *d == dir) {
|
||||
out.push((dir, kind));
|
||||
if !out.iter().any(|(d, _, _)| *d == dir) {
|
||||
out.push((dir, kind, PathBuf::from(&p.dir)));
|
||||
}
|
||||
}
|
||||
}
|
||||
// IDEA excludes the build folder of every module.
|
||||
if let Some(b) = &p.build_dir {
|
||||
out.push((PathBuf::from(b), ReportedRoot::Excluded));
|
||||
out.push((PathBuf::from(b), ReportedRoot::Excluded, PathBuf::from(&p.dir)));
|
||||
}
|
||||
}
|
||||
out
|
||||
|
||||
@@ -0,0 +1,482 @@
|
||||
//! What the incremental build needs from a class file (JVMS §4): its name, supertypes, the
|
||||
//! classes its constant pool refers to, and fingerprints of its API and of its compile-time
|
||||
//! constants. Bounds-checked: a malformed file is `None`, never a panic.
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// A class file, as the dependency graph and the API diff see it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ClassFile {
|
||||
/// Internal name (`com/acme/Order$Line`).
|
||||
pub name: String,
|
||||
pub super_name: Option<String>,
|
||||
pub interfaces: Vec<String>,
|
||||
/// Classes named in the constant pool: references, descriptors, signatures, annotation types.
|
||||
pub refs: BTreeSet<String>,
|
||||
/// What other classes compile against: non-private, non-synthetic members and their
|
||||
/// signatures, supertypes, nested classes, permitted subclasses, record components.
|
||||
pub api: u64,
|
||||
/// The compile-time constants (`static final` fields with a `ConstantValue`), which javac
|
||||
/// copies into the classes that use them: a change can't be traced through references.
|
||||
pub constants: u64,
|
||||
}
|
||||
|
||||
const ACC_PRIVATE: u16 = 0x0002;
|
||||
const ACC_SYNTHETIC: u16 = 0x1000;
|
||||
|
||||
struct Bytes<'a> {
|
||||
data: &'a [u8],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl<'a> Bytes<'a> {
|
||||
fn take(&mut self, n: usize) -> Option<&'a [u8]> {
|
||||
let end = self.pos.checked_add(n)?;
|
||||
let slice = self.data.get(self.pos..end)?;
|
||||
self.pos = end;
|
||||
Some(slice)
|
||||
}
|
||||
fn u1(&mut self) -> Option<u8> {
|
||||
Some(self.take(1)?[0])
|
||||
}
|
||||
fn u2(&mut self) -> Option<u16> {
|
||||
let b = self.take(2)?;
|
||||
Some(u16::from_be_bytes([b[0], b[1]]))
|
||||
}
|
||||
fn u4(&mut self) -> Option<u32> {
|
||||
let b = self.take(4)?;
|
||||
Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Entry {
|
||||
Empty,
|
||||
Utf8(String),
|
||||
Class(u16),
|
||||
String(u16),
|
||||
/// Integer, float, long, double: the raw bytes.
|
||||
Number(Vec<u8>),
|
||||
NameAndType(u16),
|
||||
MethodType(u16),
|
||||
Other,
|
||||
}
|
||||
|
||||
struct Pool(Vec<Entry>);
|
||||
|
||||
impl Pool {
|
||||
fn utf8(&self, index: u16) -> Option<&str> {
|
||||
match self.0.get(index as usize)? {
|
||||
Entry::Utf8(s) => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn class(&self, index: u16) -> Option<&str> {
|
||||
match self.0.get(index as usize)? {
|
||||
Entry::Class(name) => self.utf8(*name),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// A `ConstantValue`'s value, as bytes.
|
||||
fn constant(&self, index: u16) -> Option<Vec<u8>> {
|
||||
match self.0.get(index as usize)? {
|
||||
Entry::Number(bytes) => Some(bytes.clone()),
|
||||
Entry::String(utf8) => Some(self.utf8(*utf8)?.as_bytes().to_vec()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// FNV-1a: stable across Rust versions, so recorded fingerprints stay comparable.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Fnv(u64);
|
||||
|
||||
impl Fnv {
|
||||
fn new() -> Self {
|
||||
Fnv(0xcbf2_9ce4_8422_2325)
|
||||
}
|
||||
fn bytes(&mut self, bytes: &[u8]) {
|
||||
for b in bytes {
|
||||
self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3);
|
||||
}
|
||||
// A separator, so `ab`+`c` and `a`+`bc` differ.
|
||||
self.0 = (self.0 ^ 0xff).wrapping_mul(0x100_0000_01b3);
|
||||
}
|
||||
fn str(&mut self, s: &str) {
|
||||
self.bytes(s.as_bytes());
|
||||
}
|
||||
fn u16(&mut self, v: u16) {
|
||||
self.bytes(&v.to_be_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the class names a descriptor or signature mentions (`Lcom/acme/Order<Lx/Y;>;`).
|
||||
fn descriptor_refs(text: &str, out: &mut BTreeSet<String>) {
|
||||
let bytes = text.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'L'
|
||||
&& (i == 0
|
||||
|| matches!(
|
||||
bytes[i - 1],
|
||||
b'(' | b')'
|
||||
| b'['
|
||||
| b';'
|
||||
| b'<'
|
||||
| b'>'
|
||||
| b'+'
|
||||
| b'-'
|
||||
| b':'
|
||||
| b'*'
|
||||
| b'I'
|
||||
| b'J'
|
||||
| b'Z'
|
||||
| b'B'
|
||||
| b'C'
|
||||
| b'S'
|
||||
| b'F'
|
||||
| b'D'
|
||||
| b'V'
|
||||
| b'^'
|
||||
))
|
||||
{
|
||||
let start = i + 1;
|
||||
let mut end = start;
|
||||
while end < bytes.len() && !matches!(bytes[end], b';' | b'<' | b'.') {
|
||||
end += 1;
|
||||
}
|
||||
if end < bytes.len() && end > start {
|
||||
let name = &text[start..end];
|
||||
if name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'$' | b'_') || b >= 0x80) {
|
||||
out.insert(name.to_owned());
|
||||
}
|
||||
}
|
||||
i = end;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn class_ref(name: &str, out: &mut BTreeSet<String>) {
|
||||
if name.starts_with('[') {
|
||||
descriptor_refs(name, out);
|
||||
} else {
|
||||
out.insert(name.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
struct Member {
|
||||
access: u16,
|
||||
name: String,
|
||||
descriptor: String,
|
||||
/// Fingerprint of the attributes that are part of the API.
|
||||
extra: u64,
|
||||
constant: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
fn attributes(r: &mut Bytes, pool: &Pool, mut on: impl FnMut(&str, &[u8])) -> Option<()> {
|
||||
let count = r.u2()?;
|
||||
for _ in 0..count {
|
||||
let name = pool.utf8(r.u2()?)?.to_owned();
|
||||
let len = r.u4()? as usize;
|
||||
let body = r.take(len)?;
|
||||
on(&name, body);
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Vec<Member>> {
|
||||
let count = r.u2()?;
|
||||
let mut out = Vec::with_capacity(count as usize);
|
||||
for _ in 0..count {
|
||||
let access = r.u2()?;
|
||||
let name = pool.utf8(r.u2()?)?.to_owned();
|
||||
let descriptor = pool.utf8(r.u2()?)?.to_owned();
|
||||
descriptor_refs(&descriptor, refs);
|
||||
let mut extra = Fnv::new();
|
||||
let mut constant = None;
|
||||
attributes(r, pool, |attr, body| {
|
||||
let mut b = Bytes { data: body, pos: 0 };
|
||||
match attr {
|
||||
"Signature" => {
|
||||
if let Some(sig) = b.u2().and_then(|i| pool.utf8(i)) {
|
||||
descriptor_refs(sig, refs);
|
||||
extra.str("S");
|
||||
extra.str(sig);
|
||||
}
|
||||
}
|
||||
"ConstantValue" => constant = b.u2().and_then(|i| pool.constant(i)),
|
||||
"Exceptions" => {
|
||||
let mut names: Vec<&str> = Vec::new();
|
||||
if let Some(n) = b.u2() {
|
||||
for _ in 0..n {
|
||||
if let Some(c) = b.u2().and_then(|i| pool.class(i)) {
|
||||
names.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
names.sort_unstable();
|
||||
extra.str("E");
|
||||
for n in names {
|
||||
extra.str(n);
|
||||
}
|
||||
}
|
||||
// An annotation element's default value is compiled into its uses.
|
||||
"AnnotationDefault" => {
|
||||
extra.str("D");
|
||||
element_value(&mut b, pool, refs, &mut extra);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
})?;
|
||||
out.push(Member { access, name, descriptor, extra: extra.0, constant });
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Parses a class file; `None` when it isn't a well-formed one.
|
||||
pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
if r.u4()? != 0xCAFE_BABE {
|
||||
return None;
|
||||
}
|
||||
r.u2()?;
|
||||
r.u2()?;
|
||||
let count = r.u2()?;
|
||||
let mut entries = vec![Entry::Empty];
|
||||
let mut i = 1;
|
||||
while i < count {
|
||||
let tag = r.u1()?;
|
||||
let entry = match tag {
|
||||
1 => {
|
||||
let len = r.u2()? as usize;
|
||||
Entry::Utf8(String::from_utf8_lossy(r.take(len)?).into_owned())
|
||||
}
|
||||
3 | 4 => Entry::Number(r.take(4)?.to_vec()),
|
||||
5 | 6 => Entry::Number(r.take(8)?.to_vec()),
|
||||
7 => Entry::Class(r.u2()?),
|
||||
8 => Entry::String(r.u2()?),
|
||||
9..=11 => {
|
||||
r.take(4)?;
|
||||
Entry::Other
|
||||
}
|
||||
12 => {
|
||||
r.u2()?;
|
||||
Entry::NameAndType(r.u2()?)
|
||||
}
|
||||
15 => {
|
||||
r.take(3)?;
|
||||
Entry::Other
|
||||
}
|
||||
16 => Entry::MethodType(r.u2()?),
|
||||
17 | 18 => {
|
||||
r.take(4)?;
|
||||
Entry::Other
|
||||
}
|
||||
19 | 20 => {
|
||||
r.take(2)?;
|
||||
Entry::Other
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let wide = matches!(tag, 5 | 6);
|
||||
entries.push(entry);
|
||||
i += 1;
|
||||
if wide {
|
||||
entries.push(Entry::Empty);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let pool = Pool(entries);
|
||||
let mut refs = BTreeSet::new();
|
||||
for entry in &pool.0 {
|
||||
match entry {
|
||||
Entry::Class(name) => class_ref(pool.utf8(*name)?, &mut refs),
|
||||
Entry::NameAndType(descriptor) | Entry::MethodType(descriptor) => {
|
||||
descriptor_refs(pool.utf8(*descriptor)?, &mut refs)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let access = r.u2()?;
|
||||
let name = pool.class(r.u2()?)?.to_owned();
|
||||
let super_index = r.u2()?;
|
||||
let super_name = if super_index == 0 { None } else { Some(pool.class(super_index)?.to_owned()) };
|
||||
let mut interfaces = Vec::new();
|
||||
for _ in 0..r.u2()? {
|
||||
interfaces.push(pool.class(r.u2()?)?.to_owned());
|
||||
}
|
||||
let fields = members(&mut r, &pool, &mut refs)?;
|
||||
let methods = members(&mut r, &pool, &mut refs)?;
|
||||
|
||||
let mut api = Fnv::new();
|
||||
// ACC_SUPER and ACC_SYNTHETIC say nothing about what compiles against the class.
|
||||
api.u16(access & !(0x0020 | ACC_SYNTHETIC));
|
||||
api.str(&name);
|
||||
api.str(super_name.as_deref().unwrap_or(""));
|
||||
let mut sorted = interfaces.clone();
|
||||
sorted.sort();
|
||||
for i in &sorted {
|
||||
api.str(i);
|
||||
}
|
||||
let mut class_attrs: Vec<(String, u64)> = Vec::new();
|
||||
attributes(&mut r, &pool, |attr, body| {
|
||||
let mut b = Bytes { data: body, pos: 0 };
|
||||
let mut h = Fnv::new();
|
||||
match attr {
|
||||
"Signature" => {
|
||||
if let Some(sig) = b.u2().and_then(|i| pool.utf8(i)) {
|
||||
descriptor_refs(sig, &mut refs);
|
||||
h.str(sig);
|
||||
}
|
||||
}
|
||||
"PermittedSubclasses" => {
|
||||
let mut names = Vec::new();
|
||||
for _ in 0..b.u2().unwrap_or(0) {
|
||||
if let Some(c) = b.u2().and_then(|i| pool.class(i)) {
|
||||
names.push(c.to_owned());
|
||||
}
|
||||
}
|
||||
names.sort();
|
||||
names.iter().for_each(|n| h.str(n));
|
||||
}
|
||||
"Record" => {
|
||||
for _ in 0..b.u2().unwrap_or(0) {
|
||||
let (Some(n), Some(d)) = (b.u2().and_then(|i| pool.utf8(i)), b.u2().and_then(|i| pool.utf8(i)))
|
||||
else {
|
||||
break;
|
||||
};
|
||||
h.str(n);
|
||||
h.str(d);
|
||||
let mut component = |attr: &str, body: &[u8]| {
|
||||
if attr == "Signature"
|
||||
&& let Some(sig) = (Bytes { data: body, pos: 0 }).u2().and_then(|i| pool.utf8(i))
|
||||
{
|
||||
h.str(sig);
|
||||
}
|
||||
};
|
||||
if attributes(&mut b, &pool, &mut component).is_none() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Nested classes this class declares, and their access.
|
||||
"InnerClasses" => {
|
||||
let mut nested = Vec::new();
|
||||
for _ in 0..b.u2().unwrap_or(0) {
|
||||
let (Some(inner), Some(outer), Some(_), Some(flags)) = (b.u2(), b.u2(), b.u2(), b.u2()) else {
|
||||
break;
|
||||
};
|
||||
let inner = pool.class(inner).unwrap_or("");
|
||||
if outer != 0 && pool.class(outer) == Some(name.as_str()) && flags & ACC_PRIVATE == 0 {
|
||||
nested.push(format!("{inner}:{flags}"));
|
||||
}
|
||||
}
|
||||
nested.sort();
|
||||
nested.iter().for_each(|n| h.str(n));
|
||||
}
|
||||
"RuntimeVisibleAnnotations" | "RuntimeInvisibleAnnotations" => {
|
||||
// Annotation types are dependencies; their values aren't API.
|
||||
annotation_types(body, &pool, &mut refs);
|
||||
return;
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
class_attrs.push((attr.to_owned(), h.0));
|
||||
})?;
|
||||
class_attrs.sort();
|
||||
for (attr, h) in &class_attrs {
|
||||
api.str(attr);
|
||||
api.bytes(&h.to_be_bytes());
|
||||
}
|
||||
let mut constants = Fnv::new();
|
||||
let mut api_members: Vec<(u8, &str, &str, u16, u64)> = Vec::new();
|
||||
for (kind, list) in [(0u8, &fields), (1u8, &methods)] {
|
||||
for m in list.iter() {
|
||||
if kind == 0
|
||||
&& let Some(value) = &m.constant
|
||||
{
|
||||
// Private constants are inlined too, but only in their own class.
|
||||
if m.access & ACC_PRIVATE == 0 {
|
||||
constants.str(&m.name);
|
||||
constants.str(&m.descriptor);
|
||||
constants.bytes(value);
|
||||
}
|
||||
}
|
||||
if m.access & (ACC_PRIVATE | ACC_SYNTHETIC) != 0 || m.name == "<clinit>" {
|
||||
continue;
|
||||
}
|
||||
api_members.push((kind, &m.name, &m.descriptor, m.access & !ACC_SYNTHETIC, m.extra));
|
||||
}
|
||||
}
|
||||
api_members.sort();
|
||||
for (kind, name, descriptor, access, extra) in api_members {
|
||||
api.bytes(&[kind]);
|
||||
api.str(name);
|
||||
api.str(descriptor);
|
||||
api.u16(access);
|
||||
api.bytes(&extra.to_be_bytes());
|
||||
}
|
||||
refs.remove(&name);
|
||||
refs.retain(|r| !r.starts_with("java/"));
|
||||
Some(ClassFile { name, super_name, interfaces, refs, api: api.0, constants: constants.0 })
|
||||
}
|
||||
|
||||
/// Adds the types of the annotations in a `Runtime*Annotations` attribute.
|
||||
fn annotation_types(body: &[u8], pool: &Pool, refs: &mut BTreeSet<String>) {
|
||||
let mut b = Bytes { data: body, pos: 0 };
|
||||
let Some(count) = b.u2() else { return };
|
||||
let mut ignored = Fnv::new();
|
||||
for _ in 0..count {
|
||||
if annotation(&mut b, pool, refs, &mut ignored).is_none() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn annotation(b: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>, h: &mut Fnv) -> Option<()> {
|
||||
let ty = pool.utf8(b.u2()?)?;
|
||||
descriptor_refs(ty, refs);
|
||||
h.str(ty);
|
||||
for _ in 0..b.u2()? {
|
||||
h.str(pool.utf8(b.u2()?)?);
|
||||
element_value(b, pool, refs, h)?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// An annotation element value: its class names go to `refs`, its value (resolved, not the
|
||||
/// constant pool indices) to `h`.
|
||||
fn element_value(b: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>, h: &mut Fnv) -> Option<()> {
|
||||
let tag = b.u1()?;
|
||||
h.bytes(&[tag]);
|
||||
match tag {
|
||||
b'B' | b'C' | b'D' | b'F' | b'I' | b'J' | b'S' | b'Z' => h.bytes(&pool.constant(b.u2()?)?),
|
||||
b's' => h.str(pool.utf8(b.u2()?)?),
|
||||
b'e' => {
|
||||
let ty = pool.utf8(b.u2()?)?;
|
||||
descriptor_refs(ty, refs);
|
||||
h.str(ty);
|
||||
h.str(pool.utf8(b.u2()?)?);
|
||||
}
|
||||
b'c' => {
|
||||
let ty = pool.utf8(b.u2()?)?;
|
||||
descriptor_refs(ty, refs);
|
||||
h.str(ty);
|
||||
}
|
||||
b'@' => annotation(b, pool, refs, h)?,
|
||||
b'[' => {
|
||||
for _ in 0..b.u2()? {
|
||||
element_value(b, pool, refs, h)?;
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// The simple name of a class (`com/acme/Order$Line` → `Line`), which a new class can shadow.
|
||||
pub fn simple_name(name: &str) -> &str {
|
||||
let tail = name.rsplit('/').next().unwrap_or(name);
|
||||
tail.rsplit('$').next().unwrap_or(tail)
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
// OpenIDEA's Java build of a Gradle build (ide_build::jbuild). With -Popenidea.build.output=<dir>,
|
||||
// every Java source set writes its classes and resources to <dir>/[<group>.]<project>/classes|test-classes,
|
||||
// so neither the language server nor a terminal `gradle` writes what the IDE runs. The task
|
||||
// `openideaBuildModel` (-Popenidea.build.model=<file>) runs what generates sources, processes the
|
||||
// resources and writes, as JSON, each source set's roots, classpaths and how JavaCompile compiles it:
|
||||
// the same model the Maven extension writes (java/java-build, BuildModel).
|
||||
import groovy.json.JsonOutput
|
||||
import org.gradle.api.tasks.compile.AbstractCompile
|
||||
import org.gradle.api.tasks.compile.JavaCompile
|
||||
import org.gradle.jvm.tasks.Jar
|
||||
|
||||
def property = { String name -> gradle.startParameter.projectProperties[name] }
|
||||
def outRoot = property('openidea.build.output')
|
||||
if (outRoot == null || gradle.parent != null) return
|
||||
|
||||
// The project's name in the build: unique, unlike `name`.
|
||||
def nameOf = { Project p -> p == p.rootProject ? p.name : p.path.substring(1).replace(':', '.') }
|
||||
def outputOf = { Project p, String set ->
|
||||
def folder = p.group ? "${p.group}.${nameOf(p)}" : nameOf(p)
|
||||
new File(outRoot, folder + '/' + (set == 'main' ? 'classes' : 'test-classes'))
|
||||
}
|
||||
def javaSets = { Project p ->
|
||||
def sets = p.extensions.findByName('sourceSets')
|
||||
sets == null ? [] : ['main', 'test'].collect { sets.findByName(it) }.findAll { it != null }
|
||||
}
|
||||
|
||||
gradle.projectsEvaluated {
|
||||
def root = gradle.rootProject
|
||||
root.allprojects.each { p ->
|
||||
javaSets(p).each { ss ->
|
||||
def out = outputOf(p, ss.name)
|
||||
ss.java.destinationDirectory.set(out)
|
||||
ss.output.resourcesDir = out
|
||||
p.tasks.named(ss.processResourcesTaskName).configure { destinationDir = out }
|
||||
}
|
||||
}
|
||||
root.tasks.register('openideaBuildModel') {
|
||||
// What compiling needs from the same project (generated sources), and the resources.
|
||||
dependsOn {
|
||||
root.allprojects.collectMany { p ->
|
||||
javaSets(p).collectMany { ss ->
|
||||
def compile = p.tasks.getByName(ss.compileJavaTaskName)
|
||||
def generators = compile.taskDependencies.getDependencies(compile).findAll {
|
||||
it.project == p && !(it instanceof AbstractCompile) && !(it instanceof Jar)
|
||||
}
|
||||
generators + [p.tasks.getByName(ss.processResourcesTaskName)]
|
||||
}
|
||||
}
|
||||
}
|
||||
doLast {
|
||||
// Project artifacts resolve to the projects' outputs.
|
||||
def artifacts = [:]
|
||||
root.allprojects.each { p ->
|
||||
def main = javaSets(p).find { it.name == 'main' }
|
||||
if (main == null) return
|
||||
def jar = p.tasks.findByName('jar')
|
||||
if (jar instanceof Jar) artifacts[jar.archiveFile.get().asFile.canonicalPath] = outputOf(p, 'main')
|
||||
}
|
||||
def files = { collection ->
|
||||
def out = []
|
||||
try {
|
||||
collection?.files?.each { f ->
|
||||
def mapped = artifacts[f.canonicalPath] ?: f
|
||||
if (!out.contains(mapped.canonicalPath)) out << mapped.canonicalPath
|
||||
}
|
||||
} catch (e) {
|
||||
out << "!${e.message}".toString()
|
||||
}
|
||||
out
|
||||
}
|
||||
def included = gradle.includedBuilds.collect { it.name }
|
||||
def projects = root.allprojects.findAll { !javaSets(it).isEmpty() }.collect { p ->
|
||||
def problems = included.isEmpty() ? [] : ["it is a composite build (${included.join(', ')})".toString()]
|
||||
def others = p.tasks.withType(AbstractCompile).findAll {
|
||||
!(it instanceof JavaCompile) && it.name ==~ /(?i)compile.*(Kotlin|Groovy|Scala|Aspectj).*/
|
||||
}.collect { "${it.class.name.replace('_Decorated', '')}@${it.name}".toString() }
|
||||
def setModel = { String name ->
|
||||
def ss = javaSets(p).find { it.name == name }
|
||||
if (ss == null) return [sourceRoots: [], output: outputOf(p, name).path, classpath: [], runtimeClasspath: []]
|
||||
JavaCompile compile = p.tasks.getByName(ss.compileJavaTaskName)
|
||||
def o = compile.options
|
||||
def classpath = files(compile.classpath)
|
||||
def runtime = files(ss.runtimeClasspath)
|
||||
(classpath + runtime).findAll { it.startsWith('!') }.each { problems << "Cannot resolve the dependencies: ${it.substring(1)}".toString() }
|
||||
def processorPath = files(o.annotationProcessorPath)
|
||||
def processorProblems = processorPath.findAll { it.startsWith('!') }
|
||||
def projectProcessors = processorPath.findAll { path -> artifacts.values().any { it.canonicalPath == path } }
|
||||
def home = null
|
||||
try { home = compile.javaCompiler.orNull?.metadata?.installationPath?.asFile?.canonicalPath } catch (ignored) {}
|
||||
[
|
||||
sourceRoots: ss.java.srcDirs.collect { it.canonicalPath },
|
||||
output: outputOf(p, name).canonicalPath,
|
||||
classpath: classpath.findAll { !it.startsWith('!') },
|
||||
runtimeClasspath: runtime.findAll { !it.startsWith('!') },
|
||||
resources: ss.resources.srcDirs.collect { [directory: it.canonicalPath, filtering: false] },
|
||||
compiler: [
|
||||
compilerId: 'javac',
|
||||
source: compile.sourceCompatibility,
|
||||
target: compile.targetCompatibility,
|
||||
release: o.release.orNull?.toString(),
|
||||
encoding: o.encoding,
|
||||
debug: o.debug,
|
||||
debuglevel: o.debugOptions.debugLevel,
|
||||
showWarnings: o.warnings,
|
||||
showDeprecation: o.deprecation,
|
||||
fork: home != null,
|
||||
executable: home == null ? null : new File(home, 'bin/javac').path,
|
||||
generatedSourcesDirectory: o.generatedSourceOutputDirectory.asFile.orNull?.canonicalPath,
|
||||
includes: ss.java.includes as List,
|
||||
excludes: ss.java.excludes as List,
|
||||
compilerArgs: o.allCompilerArgs.collect { it.toString() },
|
||||
processorPath: processorProblems.isEmpty() && projectProcessors.isEmpty() ? processorPath : null,
|
||||
processorPathError: !processorProblems.isEmpty()
|
||||
? processorProblems[0].substring(1)
|
||||
: (projectProcessors.isEmpty() ? null : 'its annotation processors are built in the same build'),
|
||||
],
|
||||
]
|
||||
}
|
||||
def mainModel = setModel('main')
|
||||
def testModel = setModel('test')
|
||||
// Gradle compiles tests against the main classes: they're the main output here.
|
||||
[
|
||||
dir: p.projectDir.canonicalPath,
|
||||
groupId: (p.group ?: '').toString(),
|
||||
artifactId: nameOf(p),
|
||||
version: p.version.toString(),
|
||||
packaging: 'jar',
|
||||
main: mainModel,
|
||||
test: testModel,
|
||||
otherCompilers: others,
|
||||
testGenerators: [],
|
||||
problems: problems,
|
||||
gradlePath: p.path,
|
||||
]
|
||||
}
|
||||
def modelFile = property('openidea.build.model')
|
||||
if (modelFile != null) {
|
||||
def file = new File(modelFile)
|
||||
def temporary = new File(file.parentFile, file.name + '.tmp')
|
||||
temporary.text = JsonOutput.toJson([version: 1, projects: projects])
|
||||
temporary.renameTo(file) || { file.delete(); temporary.renameTo(file) }()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
//! Class-level incremental compilation (#4078 step 3). Each source set records, per class it
|
||||
//! compiled, the source it came from, its supertypes, the classes its constant pool names and
|
||||
//! fingerprints of its API and constants ([`super::classfile`]). A build compiles the changed
|
||||
//! sources, then the sources of classes that refer to a class whose API changed (or to a
|
||||
//! subclass of one), round after round until no API changes. Sets compiled against this one
|
||||
//! read its log of API changes; a changed compile-time constant, which javac copies into the
|
||||
//! classes that use it, recompiles the whole set and every set compiled against it.
|
||||
use super::*;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
|
||||
pub(super) struct ClassRecord {
|
||||
/// The source javac compiled it from; `None` for classes an annotation processor wrote
|
||||
/// without naming an originating source.
|
||||
pub source: Option<PathBuf>,
|
||||
pub file: PathBuf,
|
||||
pub super_name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub interfaces: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub refs: Vec<String>,
|
||||
pub api: u64,
|
||||
pub constants: u64,
|
||||
}
|
||||
|
||||
impl ClassRecord {
|
||||
pub fn new(class: classfile::ClassFile, file: PathBuf, source: Option<PathBuf>) -> (String, Self) {
|
||||
let record = ClassRecord {
|
||||
source,
|
||||
file,
|
||||
super_name: class.super_name,
|
||||
interfaces: class.interfaces,
|
||||
refs: class.refs.into_iter().collect(),
|
||||
api: class.api,
|
||||
constants: class.constants,
|
||||
};
|
||||
(class.name, record)
|
||||
}
|
||||
|
||||
fn has_constants(&self) -> bool {
|
||||
self.constants != NO_CONSTANTS
|
||||
}
|
||||
}
|
||||
|
||||
/// The constant fingerprint of a class without compile-time constants.
|
||||
pub(super) const NO_CONSTANTS: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
|
||||
/// The classes whose API one compilation of a set changed.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
|
||||
pub(super) struct ApiChange {
|
||||
/// The set's generation before and after the compilation.
|
||||
pub since: u64,
|
||||
pub generation: u64,
|
||||
pub classes: Vec<String>,
|
||||
/// Everything counts as changed: a constant changed, or there was nothing to compare with.
|
||||
pub all: bool,
|
||||
}
|
||||
|
||||
/// How many compilations' API changes a set keeps for the sets compiled against it; one that
|
||||
/// fell further behind compiles from scratch.
|
||||
const CHANGE_LOG: usize = 64;
|
||||
|
||||
/// The inputs of a source set that, when changed, compile it from scratch.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
|
||||
pub(super) struct SetStamp {
|
||||
pub options: Vec<String>,
|
||||
/// Classpath entries outside the reactor's outputs, with their stamps (folders have none).
|
||||
pub libraries: Vec<(PathBuf, Option<FileStamp>)>,
|
||||
/// The reactor outputs on the classpath, in order.
|
||||
pub reactor: Vec<PathBuf>,
|
||||
pub processor_path: Vec<(PathBuf, Option<FileStamp>)>,
|
||||
pub java_home: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize)]
|
||||
pub(super) struct SetState {
|
||||
pub stamp: SetStamp,
|
||||
/// The sources as of the last compilation.
|
||||
pub sources: BTreeMap<PathBuf, FileStamp>,
|
||||
/// Changes whenever the set's classes do.
|
||||
pub generation: u64,
|
||||
/// The generation of each reactor output it was compiled against.
|
||||
pub upstream: BTreeMap<PathBuf, u64>,
|
||||
pub classes: BTreeMap<String, ClassRecord>,
|
||||
/// Sources a failed compilation left uncompiled.
|
||||
pub dirty: BTreeSet<PathBuf>,
|
||||
pub changes: Vec<ApiChange>,
|
||||
/// Sources annotation processors wrote, and other files they wrote without an originating
|
||||
/// source (`META-INF/services`…): processors that aggregate. While there are any, a change
|
||||
/// compiles the set from scratch.
|
||||
pub generated: Vec<PathBuf>,
|
||||
pub unowned: Vec<PathBuf>,
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
impl SetState {
|
||||
/// The classes whose API changed since generation `since`; `None` when unknown (the log
|
||||
/// doesn't reach back that far) or when everything counts as changed.
|
||||
pub fn changes_since(&self, since: u64) -> Option<BTreeSet<String>> {
|
||||
let mut changed = BTreeSet::new();
|
||||
let mut at = since;
|
||||
while at != self.generation {
|
||||
let change = self.changes.iter().find(|c| c.since == at)?;
|
||||
if change.all {
|
||||
return None;
|
||||
}
|
||||
changed.extend(change.classes.iter().cloned());
|
||||
at = change.generation;
|
||||
}
|
||||
Some(changed)
|
||||
}
|
||||
|
||||
pub fn log(&mut self, generation: u64, classes: BTreeSet<String>, all: bool) {
|
||||
self.changes.push(ApiChange {
|
||||
since: self.generation,
|
||||
generation,
|
||||
classes: classes.into_iter().collect(),
|
||||
all,
|
||||
});
|
||||
if self.changes.len() > CHANGE_LOG {
|
||||
self.changes.drain(..self.changes.len() - CHANGE_LOG);
|
||||
}
|
||||
self.generation = generation;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn load_state(path: &Path) -> Option<SetState> {
|
||||
serde_json::from_slice(&std::fs::read(path).ok()?).ok()
|
||||
}
|
||||
|
||||
/// `seeds` and the classes of `classes` that extend or implement one of them, transitively:
|
||||
/// a class that inherits a changed member changes for the classes that use it.
|
||||
pub(super) fn with_subclasses(classes: &BTreeMap<String, ClassRecord>, seeds: &BTreeSet<String>) -> BTreeSet<String> {
|
||||
let mut out = seeds.clone();
|
||||
loop {
|
||||
let before = out.len();
|
||||
for (name, record) in classes {
|
||||
if !out.contains(name)
|
||||
&& (record.super_name.as_ref().is_some_and(|s| out.contains(s))
|
||||
|| record.interfaces.iter().any(|i| out.contains(i)))
|
||||
{
|
||||
out.insert(name.clone());
|
||||
}
|
||||
}
|
||||
if out.len() == before {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The sources of the classes that refer to one of `affected`.
|
||||
pub(super) fn dependent_sources(
|
||||
classes: &BTreeMap<String, ClassRecord>,
|
||||
affected: &BTreeSet<String>,
|
||||
) -> BTreeSet<PathBuf> {
|
||||
if affected.is_empty() {
|
||||
return BTreeSet::new();
|
||||
}
|
||||
classes
|
||||
.iter()
|
||||
.filter(|(name, r)| affected.contains(*name) || r.refs.iter().any(|x| affected.contains(x)))
|
||||
.filter_map(|(_, r)| r.source.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The sources of the classes that refer to a class with the same simple name as one of
|
||||
/// `added`: a new class can take a simple name over from an on-demand import.
|
||||
pub(super) fn shadowed_sources(classes: &BTreeMap<String, ClassRecord>, added: &BTreeSet<String>) -> BTreeSet<PathBuf> {
|
||||
let names: BTreeSet<&str> = added.iter().map(|n| classfile::simple_name(n)).collect();
|
||||
if names.is_empty() {
|
||||
return BTreeSet::new();
|
||||
}
|
||||
classes
|
||||
.iter()
|
||||
.filter(|(name, r)| {
|
||||
!added.contains(*name)
|
||||
&& r.refs.iter().any(|x| !added.contains(x) && names.contains(classfile::simple_name(x)))
|
||||
})
|
||||
.filter_map(|(_, r)| r.source.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What one round's classes changed, compared with the classes the round replaced.
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct RoundDiff {
|
||||
pub api: BTreeSet<String>,
|
||||
pub added: BTreeSet<String>,
|
||||
pub constants: bool,
|
||||
}
|
||||
|
||||
pub(super) fn diff(old: &BTreeMap<String, ClassRecord>, new: &BTreeMap<String, ClassRecord>) -> RoundDiff {
|
||||
let mut out = RoundDiff::default();
|
||||
for (name, record) in new {
|
||||
match old.get(name) {
|
||||
Some(before) => {
|
||||
if before.api != record.api {
|
||||
out.api.insert(name.clone());
|
||||
}
|
||||
if before.constants != record.constants {
|
||||
out.constants = true;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
out.api.insert(name.clone());
|
||||
out.added.insert(name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (name, before) in old {
|
||||
if !new.contains_key(name) {
|
||||
out.api.insert(name.clone());
|
||||
out.constants |= before.has_constants();
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
//! Resident javac processes (`java/java-build`, `ai.openidea.javac.Server`): one JVM per JDK
|
||||
//! and JVM options, kept warm between builds, compiling one request at a time in process.
|
||||
use super::*;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
/// A message of the server about one request.
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq)]
|
||||
#[serde(tag = "kind", rename_all = "kebab-case", rename_all_fields = "camelCase")]
|
||||
pub enum Reply {
|
||||
Diagnostic {
|
||||
severity: String,
|
||||
path: Option<PathBuf>,
|
||||
/// 1-based.
|
||||
line: Option<u32>,
|
||||
/// 0-based UTF-16.
|
||||
column: Option<u32>,
|
||||
end_line: Option<u32>,
|
||||
end_column: Option<u32>,
|
||||
code: Option<String>,
|
||||
message: String,
|
||||
},
|
||||
/// A class (or resource) file javac wrote, and the source it came from.
|
||||
Output {
|
||||
path: PathBuf,
|
||||
source: Option<PathBuf>,
|
||||
},
|
||||
/// A source file an annotation processor wrote.
|
||||
Generated {
|
||||
path: PathBuf,
|
||||
source: Option<PathBuf>,
|
||||
},
|
||||
OutputText {
|
||||
text: String,
|
||||
},
|
||||
Done {
|
||||
success: bool,
|
||||
cancelled: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct Request<'a> {
|
||||
id: u64,
|
||||
op: &'static str,
|
||||
options: &'a [String],
|
||||
sources: &'a [PathBuf],
|
||||
encoding: Option<&'a str>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
|
||||
pub struct ServerKey {
|
||||
pub java_home: PathBuf,
|
||||
/// Options of the compiler's JVM (`.mvn/jvm.config`: `--add-opens` for processors).
|
||||
pub jvm_args: Vec<String>,
|
||||
}
|
||||
|
||||
type Pending = Arc<Mutex<HashMap<u64, mpsc::Sender<Reply>>>>;
|
||||
|
||||
pub struct JavacServer {
|
||||
child: Mutex<Child>,
|
||||
stdin: Mutex<ChildStdin>,
|
||||
pending: Pending,
|
||||
alive: Arc<AtomicBool>,
|
||||
next: AtomicU64,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
impl JavacServer {
|
||||
fn start(jar: &Path, key: &ServerKey) -> IdeResult<Self> {
|
||||
let java = key.java_home.join("bin").join(if cfg!(windows) { "java.exe" } else { "java" });
|
||||
let mut cmd = Command::new(&java);
|
||||
cmd.args(&key.jvm_args)
|
||||
.args(["-XX:+UseSerialGC", "-XX:TieredStopAtLevel=1", "-Dfile.encoding=UTF-8", "-cp"])
|
||||
.arg(jar)
|
||||
.arg("ai.openidea.javac.Server")
|
||||
.env("JAVA_HOME", &key.java_home)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
ide_core::process::own_group(&mut cmd);
|
||||
let mut child =
|
||||
cmd.spawn().map_err(|e| IdeError::unavailable(format!("Cannot start javac ({}): {e}", java.display())))?;
|
||||
let stdin = child.stdin.take().expect("piped");
|
||||
let stdout = child.stdout.take().expect("piped");
|
||||
let pending: Pending = Arc::default();
|
||||
let alive = Arc::new(AtomicBool::new(true));
|
||||
let (ready_tx, ready_rx) = mpsc::channel::<Result<String, String>>();
|
||||
{
|
||||
let (pending, alive) = (pending.clone(), alive.clone());
|
||||
std::thread::Builder::new()
|
||||
.name("javac-server".into())
|
||||
.spawn(move || {
|
||||
let mut ready = Some(ready_tx);
|
||||
for line in BufReader::new(stdout).lines() {
|
||||
let Ok(line) = line else { break };
|
||||
let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) else { continue };
|
||||
match value.get("kind").and_then(|k| k.as_str()) {
|
||||
Some("ready") => {
|
||||
let version = value.get("version").and_then(|v| v.as_str()).unwrap_or("").to_owned();
|
||||
if let Some(ready) = ready.take() {
|
||||
let _ = ready.send(Ok(version));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Some("fatal") => {
|
||||
let message = value.get("message").and_then(|v| v.as_str()).unwrap_or("").to_owned();
|
||||
if let Some(ready) = ready.take() {
|
||||
let _ = ready.send(Err(message));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let Some(id) = value.get("id").and_then(|v| v.as_u64()) else { continue };
|
||||
let Ok(reply) = serde_json::from_value::<Reply>(value) else { continue };
|
||||
let done = matches!(reply, Reply::Done { .. });
|
||||
let mut pending = pending.lock().unwrap();
|
||||
if let Some(tx) = pending.get(&id) {
|
||||
let _ = tx.send(reply);
|
||||
}
|
||||
if done {
|
||||
pending.remove(&id);
|
||||
}
|
||||
}
|
||||
alive.store(false, Ordering::SeqCst);
|
||||
// Requests still waiting learn that the server is gone.
|
||||
for (_, tx) in pending.lock().unwrap().drain() {
|
||||
let _ = tx.send(Reply::Diagnostic {
|
||||
severity: "error".into(),
|
||||
path: None,
|
||||
line: None,
|
||||
column: None,
|
||||
end_line: None,
|
||||
end_column: None,
|
||||
code: None,
|
||||
message: "The javac process exited".into(),
|
||||
});
|
||||
let _ = tx.send(Reply::Done { success: false, cancelled: false });
|
||||
}
|
||||
if let Some(ready) = ready.take() {
|
||||
let _ = ready.send(Err("The javac process exited while starting".into()));
|
||||
}
|
||||
})
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
}
|
||||
let version = match ready_rx.recv_timeout(Duration::from_secs(60)) {
|
||||
Ok(Ok(version)) => version,
|
||||
Ok(Err(message)) => {
|
||||
ide_core::process::kill_tree(&mut child);
|
||||
return Err(IdeError::unavailable(format!("Cannot start javac ({}): {message}", java.display())));
|
||||
}
|
||||
Err(_) => {
|
||||
ide_core::process::kill_tree(&mut child);
|
||||
return Err(IdeError::unavailable(format!("javac ({}) did not start", java.display())));
|
||||
}
|
||||
};
|
||||
Ok(JavacServer {
|
||||
child: Mutex::new(child),
|
||||
stdin: Mutex::new(stdin),
|
||||
pending,
|
||||
alive,
|
||||
next: AtomicU64::new(1),
|
||||
version,
|
||||
})
|
||||
}
|
||||
|
||||
fn alive(&self) -> bool {
|
||||
self.alive.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn send(&self, value: &impl Serialize) -> IdeResult<()> {
|
||||
let mut line = serde_json::to_vec(value).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
line.push(b'\n');
|
||||
let mut stdin = self.stdin.lock().unwrap();
|
||||
stdin.write_all(&line).and_then(|()| stdin.flush()).map_err(|e| IdeError::internal(format!("javac: {e}")))
|
||||
}
|
||||
|
||||
/// Compiles `sources` with javac `options`, passing each reply to `on_reply`, until the
|
||||
/// compilation ends. Cancelling stops javac at its next phase.
|
||||
pub fn compile(
|
||||
&self,
|
||||
options: &[String],
|
||||
sources: &[PathBuf],
|
||||
encoding: Option<&str>,
|
||||
cancel: &CancellationToken,
|
||||
mut on_reply: impl FnMut(&Reply),
|
||||
) -> IdeResult<bool> {
|
||||
let id = self.next.fetch_add(1, Ordering::SeqCst);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.pending.lock().unwrap().insert(id, tx);
|
||||
if let Err(e) = self.send(&Request { id, op: "compile", options, sources, encoding }) {
|
||||
self.pending.lock().unwrap().remove(&id);
|
||||
return Err(e);
|
||||
}
|
||||
let mut cancelled = false;
|
||||
loop {
|
||||
match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok(reply) => {
|
||||
if let Reply::Done { success, cancelled: stopped } = reply {
|
||||
if stopped || cancelled {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
return Ok(success);
|
||||
}
|
||||
on_reply(&reply);
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {
|
||||
if cancel.is_cancelled() && !cancelled {
|
||||
cancelled = true;
|
||||
let _ = self.send(&serde_json::json!({ "op": "cancel", "id": id }));
|
||||
}
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => {
|
||||
return Err(IdeError::internal("The javac process exited"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for JavacServer {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.send(&serde_json::json!({ "op": "exit" }));
|
||||
let mut child = self.child.lock().unwrap();
|
||||
for _ in 0..20 {
|
||||
if child.try_wait().ok().flatten().is_some() {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
ide_core::process::kill_tree(&mut child);
|
||||
}
|
||||
}
|
||||
|
||||
/// The resident javac servers of one IDE process.
|
||||
#[derive(Default)]
|
||||
pub struct JavacPool {
|
||||
servers: Mutex<HashMap<ServerKey, Arc<JavacServer>>>,
|
||||
}
|
||||
|
||||
impl JavacPool {
|
||||
/// The running server for `key`, started on first use (or after it died).
|
||||
pub fn server(&self, jar: &Path, key: &ServerKey) -> IdeResult<Arc<JavacServer>> {
|
||||
let mut servers = self.servers.lock().unwrap();
|
||||
if let Some(server) = servers.get(key).filter(|s| s.alive()) {
|
||||
return Ok(server.clone());
|
||||
}
|
||||
let server = Arc::new(JavacServer::start(jar, key)?);
|
||||
servers.insert(key.clone(), server.clone());
|
||||
Ok(server)
|
||||
}
|
||||
|
||||
/// Stops every server (the project closed).
|
||||
pub fn shutdown(&self) {
|
||||
self.servers.lock().unwrap().clear();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,342 @@
|
||||
//! The build model of a Maven reactor or Gradle build as the build tool itself configures it,
|
||||
//! recorded by the prepare run (`java/java-build` `BuildModel`, `gradle-build.init.gradle`), and when that run is due.
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
/// `model.json` of the prepare run (see `BuildModel.java`).
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ReactorModel {
|
||||
pub version: u32,
|
||||
pub projects: Vec<ProjectModel>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProjectModel {
|
||||
/// Absolute project directory.
|
||||
pub dir: PathBuf,
|
||||
pub group_id: String,
|
||||
pub artifact_id: String,
|
||||
pub version: String,
|
||||
pub packaging: String,
|
||||
pub main: SourceSet,
|
||||
pub test: SourceSet,
|
||||
/// Executions in the compile phases that aren't javac (`group:artifact:goal@id`).
|
||||
#[serde(default)]
|
||||
pub other_compilers: Vec<String>,
|
||||
/// Test source generators the prepare run doesn't reach.
|
||||
#[serde(default)]
|
||||
pub test_generators: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub problems: Vec<String>,
|
||||
/// The Gradle project path (`:`, `:app`); `None` for Maven.
|
||||
#[serde(default)]
|
||||
pub gradle_path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SourceSet {
|
||||
pub source_roots: Vec<PathBuf>,
|
||||
pub output: PathBuf,
|
||||
pub classpath: Vec<PathBuf>,
|
||||
pub runtime_classpath: Vec<PathBuf>,
|
||||
#[serde(default)]
|
||||
pub resources: Vec<ResourceRoot>,
|
||||
pub compiler: Option<CompilerConfig>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ResourceRoot {
|
||||
pub directory: PathBuf,
|
||||
#[serde(default)]
|
||||
pub filtering: bool,
|
||||
pub target_path: Option<String>,
|
||||
#[serde(default)]
|
||||
pub includes: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub excludes: Vec<String>,
|
||||
}
|
||||
|
||||
/// maven-compiler-plugin's configuration of one source set, as its mojo was configured.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CompilerConfig {
|
||||
pub compiler_id: Option<String>,
|
||||
pub source: Option<String>,
|
||||
pub target: Option<String>,
|
||||
pub release: Option<String>,
|
||||
pub encoding: Option<String>,
|
||||
pub parameters: Option<bool>,
|
||||
pub debug: Option<bool>,
|
||||
pub debuglevel: Option<String>,
|
||||
pub proc: Option<String>,
|
||||
pub enable_preview: Option<bool>,
|
||||
pub fork: Option<bool>,
|
||||
pub executable: Option<String>,
|
||||
pub skip: Option<bool>,
|
||||
pub show_warnings: Option<bool>,
|
||||
pub show_deprecation: Option<bool>,
|
||||
pub generated_sources_directory: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
pub includes: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub excludes: Vec<String>,
|
||||
pub annotation_processors: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
pub compiler_args: Vec<String>,
|
||||
pub compiler_argument: Option<String>,
|
||||
#[serde(default)]
|
||||
pub compiler_arguments: BTreeMap<String, Option<String>>,
|
||||
pub multi_release_output: Option<bool>,
|
||||
pub processor_path: Option<Vec<PathBuf>>,
|
||||
pub processor_path_error: Option<String>,
|
||||
}
|
||||
|
||||
impl ProjectModel {
|
||||
pub fn key(&self) -> String {
|
||||
format!("{}:{}", self.group_id, self.artifact_id)
|
||||
}
|
||||
|
||||
pub fn set(&self, test: bool) -> &SourceSet {
|
||||
if test { &self.test } else { &self.main }
|
||||
}
|
||||
|
||||
/// Why the IDE can't compile this project with javac itself, if it can't.
|
||||
pub fn unsupported(&self, test: bool) -> Option<String> {
|
||||
// What the build tool couldn't resolve or read: the model would be incomplete.
|
||||
if let Some(problem) = self.problems.first() {
|
||||
return Some(format!("{}: {problem}", self.artifact_id));
|
||||
}
|
||||
if !self.other_compilers.is_empty() {
|
||||
return Some(format!("{} also compiles with {}", self.artifact_id, self.other_compilers.join(", ")));
|
||||
}
|
||||
if test && !self.test_generators.is_empty() {
|
||||
return Some(format!(
|
||||
"{} generates test sources with {}",
|
||||
self.artifact_id,
|
||||
self.test_generators.join(", ")
|
||||
));
|
||||
}
|
||||
for set in [&self.main, &self.test] {
|
||||
let Some(c) = &set.compiler else { continue };
|
||||
if c.compiler_id.as_deref().is_some_and(|id| id != "javac") {
|
||||
return Some(format!("{} compiles with {}", self.artifact_id, c.compiler_id.as_deref().unwrap()));
|
||||
}
|
||||
if c.multi_release_output == Some(true) {
|
||||
return Some(format!("{} is a multi-release jar", self.artifact_id));
|
||||
}
|
||||
if let Some(error) = &c.processor_path_error {
|
||||
return Some(format!("{}: {error}", self.artifact_id));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the IDE's build of the reactor at `top_dir` keeps its model and outputs.
|
||||
pub(super) fn reactor_dir(cache: &Path, top_dir: &str) -> PathBuf {
|
||||
let base = cache.join("java-build");
|
||||
if top_dir.is_empty() { base.join("_root") } else { base.join(top_dir) }
|
||||
}
|
||||
|
||||
/// The outputs of every project, `<out>/<groupId>.<artifactId>/classes`, as the extension
|
||||
/// redirects them (`-Dopenidea.build.output=<out>`).
|
||||
pub(super) fn output_root(cache: &Path, top_dir: &str) -> PathBuf {
|
||||
reactor_dir(cache, top_dir).join("out")
|
||||
}
|
||||
|
||||
/// What the recorded model was prepared from.
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub(super) struct PrepareRecord {
|
||||
pub fingerprint: LaunchFingerprint,
|
||||
pub model: ReactorModel,
|
||||
}
|
||||
|
||||
const MODEL_VERSION: u32 = 1;
|
||||
|
||||
/// Files the model depends on: the POM chains, settings, toolchains, the Maven launcher,
|
||||
/// and generator inputs (any `src/<set>/<dir>` that isn't Java sources or resources:
|
||||
/// `proto`, `antlr4`, `avro`…), but not the Java sources and resources themselves.
|
||||
pub(super) fn prepare_fingerprint(
|
||||
root: &Path,
|
||||
reactor: &[&maven::MavenProject],
|
||||
step: &BuildStep,
|
||||
local_repo: Option<PathBuf>,
|
||||
jar_version: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<LaunchFingerprint>> {
|
||||
let Some(mut inputs) = maven::model_inputs(root, reactor, local_repo) else { return Ok(None) };
|
||||
for project in reactor {
|
||||
let src = subdir(root, &project.dir).join("src");
|
||||
for set in fs::read_dir(&src).into_iter().flatten().flatten() {
|
||||
for dir in fs::read_dir(set.path()).into_iter().flatten().flatten() {
|
||||
let name = dir.file_name();
|
||||
if dir.path().is_dir() && !matches!(name.to_str(), Some("java" | "resources")) {
|
||||
inputs.push(dir.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for dir in step.cwd.ancestors() {
|
||||
inputs.extend([dir.join(".mvn"), dir.join("mvnw"), dir.join("mvnw.cmd")]);
|
||||
if dir == root {
|
||||
break;
|
||||
}
|
||||
}
|
||||
inputs.push(process::program_path(&step.program, &step.env, &step.cwd));
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
inputs.extend([home.join(".m2/settings.xml"), home.join(".m2/toolchains.xml")]);
|
||||
}
|
||||
if let Some(home) = step.env.get("JAVA_HOME") {
|
||||
inputs.push(Path::new(home).join("release"));
|
||||
}
|
||||
inputs.sort();
|
||||
inputs.dedup();
|
||||
let parameters = serde_json::to_string(&(MODEL_VERSION, jar_version, &step.program, &step.args, &step.env))
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
Ok(Some(LaunchFingerprint::new(parameters, fingerprint::scan_all(root, inputs, cancel)?)))
|
||||
}
|
||||
|
||||
pub(super) fn load_record(dir: &Path) -> Option<PrepareRecord> {
|
||||
let record: PrepareRecord = serde_json::from_slice(&fs::read(dir.join("prepare.json")).ok()?).ok()?;
|
||||
(record.model.version == MODEL_VERSION).then_some(record)
|
||||
}
|
||||
|
||||
pub(super) fn save_record(dir: &Path, record: &PrepareRecord) -> IdeResult<()> {
|
||||
write_json(&dir.join("prepare.json"), record)
|
||||
}
|
||||
|
||||
pub(super) fn write_json(path: &Path, value: &impl Serialize) -> IdeResult<()> {
|
||||
let parent = path.parent().ok_or_else(|| IdeError::internal("no parent folder"))?;
|
||||
fs::create_dir_all(parent)?;
|
||||
let mut file = tempfile::NamedTempFile::new_in(parent)?;
|
||||
serde_json::to_writer(file.as_file_mut(), value).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
file.persist(path).map_err(|e| IdeError::from(e.error))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the generated source roots the model lists still exist: `mvn clean` removes them.
|
||||
pub(super) fn generated_roots_exist(model: &ReactorModel) -> bool {
|
||||
model.projects.iter().all(|p| {
|
||||
[&p.main, &p.test].iter().all(|set| {
|
||||
set.source_roots.iter().all(|root| {
|
||||
root.exists() || !root.components().any(|c| c.as_os_str() == "target") || is_processor_output(set, root)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The annotation processors' output folder, which javac writes into and never reads as a root.
|
||||
pub(super) fn is_processor_output(set: &SourceSet, root: &Path) -> bool {
|
||||
set.compiler.as_ref().and_then(|c| c.generated_sources_directory.as_deref()).is_some_and(|dir| dir == root)
|
||||
}
|
||||
|
||||
/// A Maven step at the reactor root running `goals` with the IDE's extension loaded.
|
||||
pub(super) fn maven_step(
|
||||
root: &Path,
|
||||
top: &maven::MavenProject,
|
||||
jar: &Path,
|
||||
output_root: &Path,
|
||||
model_file: Option<&Path>,
|
||||
extra: &[String],
|
||||
) -> BuildStep {
|
||||
let mut step = maven_build_step(
|
||||
&top.command,
|
||||
&["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG],
|
||||
&subdir(root, &top.dir),
|
||||
);
|
||||
step.args.extend(top.options.iter().cloned());
|
||||
step.args.push(format!("-Dmaven.ext.class.path={}", jar.display()));
|
||||
step.args.push(format!("-Dopenidea.build.output={}", output_root.display()));
|
||||
if let Some(file) = model_file {
|
||||
step.args.push(format!("-Dopenidea.build.model={}", file.display()));
|
||||
}
|
||||
step.args.extend(extra.iter().cloned());
|
||||
step.env = top.env.clone();
|
||||
step
|
||||
}
|
||||
|
||||
/// The init script that gives a Gradle build the IDE's outputs and writes its model.
|
||||
const GRADLE_INIT_SCRIPT: &str = include_str!("gradle-build.init.gradle");
|
||||
|
||||
/// Writes the init script into the build's state folder, and returns its path.
|
||||
pub(super) fn gradle_init_script(dir: &Path) -> IdeResult<PathBuf> {
|
||||
fs::create_dir_all(dir)?;
|
||||
let path = dir.join("openidea-build.init.gradle");
|
||||
if fs::read_to_string(&path).ok().as_deref() != Some(GRADLE_INIT_SCRIPT) {
|
||||
fs::write(&path, GRADLE_INIT_SCRIPT)?;
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// A Gradle step at the build's root running `tasks` with the IDE's init script.
|
||||
pub(super) fn gradle_step(
|
||||
root: &Path,
|
||||
g: &crate::GradleModel,
|
||||
init: &Path,
|
||||
output_root: &Path,
|
||||
model_file: Option<&Path>,
|
||||
tasks: &[String],
|
||||
) -> BuildStep {
|
||||
let mut step = gradle_build_step(
|
||||
&g.command,
|
||||
// The init script configures the evaluated projects, which a configuration cache skips.
|
||||
&["--console=plain", "--no-configuration-cache"],
|
||||
&subdir(root, &g.dir),
|
||||
);
|
||||
step.args.extend(["--init-script".to_owned(), init.to_string_lossy().into_owned()]);
|
||||
step.args.push(format!("-Popenidea.build.output={}", output_root.display()));
|
||||
if let Some(file) = model_file {
|
||||
step.args.push(format!("-Popenidea.build.model={}", file.display()));
|
||||
}
|
||||
step.args.extend(tasks.iter().cloned());
|
||||
step.env = g.env.clone();
|
||||
step
|
||||
}
|
||||
|
||||
/// Files a Gradle build's model depends on: settings and build scripts (with what they apply),
|
||||
/// properties, the wrapper and catalogs, `buildSrc`, and generator inputs.
|
||||
pub(super) fn gradle_prepare_fingerprint(
|
||||
root: &Path,
|
||||
g: &crate::GradleModel,
|
||||
step: &BuildStep,
|
||||
jar_version: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<LaunchFingerprint> {
|
||||
let mut inputs = crate::gradle::build_files(root, g);
|
||||
let dir = subdir(root, &g.dir);
|
||||
inputs.extend([dir.join("buildSrc"), dir.join("gradle"), dir.join("gradlew"), dir.join("gradlew.bat")]);
|
||||
for project in &g.projects {
|
||||
let src = subdir(root, &project.dir).join("src");
|
||||
for set in fs::read_dir(&src).into_iter().flatten().flatten() {
|
||||
for generator in fs::read_dir(set.path()).into_iter().flatten().flatten() {
|
||||
let name = generator.file_name();
|
||||
if generator.path().is_dir() && !matches!(name.to_str(), Some("java" | "resources")) {
|
||||
inputs.push(generator.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
inputs.push(process::program_path(&step.program, &step.env, &step.cwd));
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
inputs.push(home.join(".gradle/gradle.properties"));
|
||||
inputs.push(home.join(".gradle/init.d"));
|
||||
}
|
||||
if let Some(home) = step.env.get("JAVA_HOME") {
|
||||
inputs.push(Path::new(home).join("release"));
|
||||
}
|
||||
inputs.sort();
|
||||
inputs.dedup();
|
||||
let parameters =
|
||||
serde_json::to_string(&(MODEL_VERSION, jar_version, GRADLE_INIT_SCRIPT, &step.program, &step.args, &step.env))
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
Ok(LaunchFingerprint::new(parameters, fingerprint::scan_all(root, inputs, cancel)?))
|
||||
}
|
||||
|
||||
pub(super) fn read_model(path: &Path) -> IdeResult<ReactorModel> {
|
||||
let bytes = fs::read(path).map_err(|e| IdeError::internal(format!("The build wrote no model ({e})")))?;
|
||||
serde_json::from_slice(&bytes).map_err(|e| IdeError::internal(format!("Unreadable build model: {e}")))
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
use super::*;
|
||||
use crate::BuildModel;
|
||||
use std::fs;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
|
||||
const JAR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../java/java-build/openidea-java-build.jar");
|
||||
|
||||
fn write(root: &Path, rel: &str, text: &str) {
|
||||
let path = root.join(rel);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped).
|
||||
fn tools() -> Option<(PathBuf, PathBuf)> {
|
||||
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
|
||||
let mvn = ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path())?;
|
||||
Some((home, mvn))
|
||||
}
|
||||
|
||||
const ROOT_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
|
||||
<modules><module>lib</module><module>app</module></modules>
|
||||
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
|
||||
<build><pluginManagement><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version>
|
||||
<configuration><parameters>true</parameters></configuration></plugin></plugins></pluginManagement></build></project>"#;
|
||||
const LIB_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#;
|
||||
const APP_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
|
||||
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>
|
||||
<build><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources></build></project>"#;
|
||||
|
||||
/// A `lib` ← `app` reactor built by the IDE's Java build with a real Maven and JDK.
|
||||
struct Fixture {
|
||||
_tmp: tempfile::TempDir,
|
||||
root: PathBuf,
|
||||
cache: PathBuf,
|
||||
model: BuildModel,
|
||||
/// Where the build keeps its state under the cache (`Reactor::key`).
|
||||
key: &'static str,
|
||||
service: JavaBuildService,
|
||||
events: StdMutex<Vec<BuildEvent>>,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new(files: &[(&str, &str)]) -> Option<Self> {
|
||||
let Some((home, mvn)) = tools() else {
|
||||
eprintln!("skipped: needs JAVA_HOME and mvn");
|
||||
return None;
|
||||
};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
for (rel, text) in
|
||||
[("pom.xml", ROOT_POM), ("lib/pom.xml", LIB_POM), ("app/pom.xml", APP_POM)].iter().chain(files)
|
||||
{
|
||||
write(&root, rel, text);
|
||||
}
|
||||
let cache = root.join(".cache");
|
||||
let mut model = crate::load(&root, &cache, None);
|
||||
for p in &mut model.maven.as_mut().unwrap().projects {
|
||||
p.command = mvn.to_string_lossy().into_owned();
|
||||
p.env.insert("JAVA_HOME".into(), home.to_string_lossy().into_owned());
|
||||
}
|
||||
Some(Fixture {
|
||||
_tmp: tmp,
|
||||
root,
|
||||
cache,
|
||||
model,
|
||||
key: "",
|
||||
service: JavaBuildService::default(),
|
||||
events: StdMutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The same `lib` ← `app` build with Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the
|
||||
/// search path).
|
||||
fn gradle(files: &[(&str, &str)]) -> Option<Self> {
|
||||
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir());
|
||||
let gradle = std::env::var_os("OPENIDEA_TEST_GRADLE")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()));
|
||||
let (Some(home), Some(gradle)) = (home, gradle) else {
|
||||
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
|
||||
return None;
|
||||
};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let build = [
|
||||
// A persistent Gradle daemon can keep the fixture's output pipes open on Windows.
|
||||
("gradle.properties", "org.gradle.daemon=false\n"),
|
||||
("settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n"),
|
||||
(
|
||||
"build.gradle",
|
||||
"subprojects {\n apply plugin: 'java'\n group = 't'\n tasks.withType(JavaCompile).configureEach { options.release = 11; options.encoding = 'UTF-8' }\n}\n",
|
||||
),
|
||||
("lib/build.gradle", ""),
|
||||
(
|
||||
"app/build.gradle",
|
||||
"dependencies { implementation project(':lib') }\nprocessResources { filesMatching('*.properties') { expand(version: '1') } }\n",
|
||||
),
|
||||
];
|
||||
for (rel, text) in build.iter().chain(files) {
|
||||
write(&root, rel, text);
|
||||
}
|
||||
let cache = root.join(".cache");
|
||||
let mut model = crate::load(&root, &cache, None);
|
||||
assert_eq!(model.gradle.len(), 1, "{model:?}");
|
||||
let g = &mut model.gradle[0];
|
||||
g.command = gradle.to_string_lossy().into_owned();
|
||||
g.env.insert("JAVA_HOME".into(), home.to_string_lossy().into_owned());
|
||||
Some(Fixture {
|
||||
_tmp: tmp,
|
||||
root,
|
||||
cache,
|
||||
model,
|
||||
key: "_gradle",
|
||||
service: JavaBuildService::default(),
|
||||
events: StdMutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) {
|
||||
write(&self.root, rel, text);
|
||||
}
|
||||
|
||||
fn out(&self, rel: &str) -> PathBuf {
|
||||
model::output_root(&self.cache, self.key).join(rel)
|
||||
}
|
||||
|
||||
/// Builds the launch of `app` (its tests when `test`).
|
||||
fn launch(&self, test: bool) -> LaunchOutputs {
|
||||
self.build(Target::Launch { module: &self.root.join("app"), test })
|
||||
}
|
||||
|
||||
fn build(&self, target: Target) -> LaunchOutputs {
|
||||
let jdk = |_: Option<u32>| None;
|
||||
let build = JavaBuild {
|
||||
root: &self.root,
|
||||
model: &self.model,
|
||||
cache: &self.cache,
|
||||
jar: Path::new(JAR),
|
||||
jar_version: "test",
|
||||
local_repo: None,
|
||||
service: &self.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
|
||||
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
|
||||
Ok(Built::Done(outputs)) => outputs,
|
||||
Ok(Built::Unsupported(reason)) => panic!("unsupported: {reason}"),
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The steps of the launch builds since the last call.
|
||||
fn steps(&self) -> Vec<String> {
|
||||
self.events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.drain(..)
|
||||
.filter_map(|e| match e {
|
||||
BuildEvent::Step { command, .. } => Some(command),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Builds and returns the steps it took, which must succeed.
|
||||
fn steps_of_launch(&self) -> Vec<String> {
|
||||
self.steps();
|
||||
let built = self.launch(false);
|
||||
assert_eq!(built.failure, None, "{:?}", built.messages);
|
||||
self.steps()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
(
|
||||
"lib/src/main/java/l/L.java",
|
||||
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
|
||||
),
|
||||
(
|
||||
"app/src/main/java/a/A.java",
|
||||
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
|
||||
),
|
||||
("app/src/main/resources/app.properties", "version=${project.version}\n"),
|
||||
("app/src/test/java/a/ATest.java", "package a;\npublic class ATest { String s = l.L.name(); }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// First build: Maven prepares the model, javac compiles lib then app into the IDE's outputs.
|
||||
let first = f.launch(false);
|
||||
assert_eq!(first.failure, None, "{:?}", first.messages);
|
||||
assert_eq!(first.class_paths[0], f.out("t.app/classes"));
|
||||
assert!(first.class_paths.contains(&f.out("t.lib/classes")), "{:?}", first.class_paths);
|
||||
assert!(f.out("t.app/classes/a/A.class").is_file());
|
||||
assert!(f.out("t.lib/classes/l/L.class").is_file());
|
||||
assert!(!f.root.join("app/target/classes/a/A.class").exists());
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
|
||||
let steps = f.steps();
|
||||
assert!(steps[0].contains("process-resources"), "{steps:?}");
|
||||
assert_eq!(steps[1..], ["javac lib (main, 1 file)", "javac app (main, 1 file)"]);
|
||||
|
||||
// Nothing changed: no Maven, no javac.
|
||||
assert_eq!(f.steps_of_launch(), Vec::<String>::new());
|
||||
|
||||
// A change inside a method compiles that class only, without Maven.
|
||||
f.write(
|
||||
"lib/src/main/java/l/L.java",
|
||||
"package l;\npublic class L { public static String name() { return \"lib 2\"; } }\n",
|
||||
);
|
||||
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 file)"]);
|
||||
|
||||
// A resource change is processed by Maven (it filters), and compiles nothing.
|
||||
f.write("app/src/main/resources/app.properties", "version=${project.version}\nmore=1\n");
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 1, "{steps:?}");
|
||||
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl app"), "{steps:?}");
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n");
|
||||
|
||||
// A deleted source leaves no class behind.
|
||||
f.write("app/src/main/java/a/Gone.java", "package a;\nclass Gone {}\n");
|
||||
assert_eq!(f.steps_of_launch(), ["javac app (main, 1 of 2 files)"]);
|
||||
assert!(f.out("t.app/classes/a/Gone.class").is_file());
|
||||
fs::remove_file(f.root.join("app/src/main/java/a/Gone.java")).unwrap();
|
||||
assert_eq!(f.steps_of_launch(), Vec::<String>::new());
|
||||
assert!(!f.out("t.app/classes/a/Gone.class").exists());
|
||||
|
||||
// Compile errors fail the build with positioned messages.
|
||||
f.write("app/src/main/java/a/A.java", "package a;\npublic class A { int x = \"s\"; }\n");
|
||||
let failed = f.launch(false);
|
||||
let failure = failed.failure.expect("fails");
|
||||
assert!(failure.contains("incompatible types"), "{failure}");
|
||||
let error = failed.messages.iter().find(|m| m.severity == Severity::Error).unwrap();
|
||||
assert_eq!(error.path.as_deref(), Some(f.root.join("app/src/main/java/a/A.java").as_path()));
|
||||
assert_eq!(error.range.unwrap().start, Pos::new(1, 25));
|
||||
// It compiles again next time, even unchanged.
|
||||
f.steps();
|
||||
assert!(f.launch(false).failure.is_some());
|
||||
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
|
||||
|
||||
// A test launch compiles the module's tests after its main classes.
|
||||
f.write(
|
||||
"app/src/main/java/a/A.java",
|
||||
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
|
||||
);
|
||||
let tests = f.launch(true);
|
||||
assert_eq!(tests.failure, None, "{:?}", tests.messages);
|
||||
assert_eq!(tests.class_paths[..2], [f.out("t.app/test-classes"), f.out("t.app/classes")]);
|
||||
assert!(f.out("t.app/test-classes/a/ATest.class").is_file());
|
||||
|
||||
// Recompile compiles the file even unchanged.
|
||||
f.steps();
|
||||
let file = f.root.join("app/src/main/java/a/A.java");
|
||||
assert_eq!(f.build(Target::File(&file)).failure, None);
|
||||
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
|
||||
// Build Project builds every module's main and test classes.
|
||||
f.write("lib/src/test/java/l/LTest.java", "package l;\nclass LTest { String s = L.name(); }\n");
|
||||
assert_eq!(f.build(Target::Project).failure, None);
|
||||
assert_eq!(f.steps(), ["javac lib (tests, 1 file)"]);
|
||||
assert!(f.out("t.lib/test-classes/l/LTest.class").is_file());
|
||||
|
||||
// Build Module on the root aggregator compiles every submodule under it.
|
||||
f.write("app/src/test/java/a/AggTest.java", "package a;\nclass AggTest { String s = l.L.name(); }\n");
|
||||
assert_eq!(f.build(Target::Module(&f.root)).failure, None);
|
||||
assert_eq!(f.steps(), ["javac app (tests, 1 of 2 files)"]);
|
||||
assert!(f.out("t.app/test-classes/a/AggTest.class").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recompiles_the_classes_an_api_change_reaches() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
("lib/src/main/java/l/Base.java", "package l;\npublic class Base { public int m() { return 1; } }\n"),
|
||||
("lib/src/main/java/l/Sub.java", "package l;\npublic class Sub extends Base {}\n"),
|
||||
("lib/src/main/java/l/User.java", "package l;\nclass User { int u(Sub s) { return s.m(); } }\n"),
|
||||
("lib/src/main/java/l/Const.java", "package l;\npublic class Const { public static final int X = 1; }\n"),
|
||||
("lib/src/main/java/l/ConstUser.java", "package l;\nclass ConstUser { int c() { return Const.X; } }\n"),
|
||||
("lib/src/main/java/l/Other.java", "package l;\npublic class Other { public int o() { return 1; } }\n"),
|
||||
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return new l.Other().o(); } }\n"),
|
||||
("app/src/main/java/a/B.java", "package a;\nclass B { int b() { return l.Const.X; } }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(f.steps_of_launch()[1..], ["javac lib (main, 6 files)", "javac app (main, 2 files)"]);
|
||||
|
||||
// A body change: that class only, and nothing downstream.
|
||||
f.write("lib/src/main/java/l/Other.java", "package l;\npublic class Other { public int o() { return 2; } }\n");
|
||||
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)"]);
|
||||
|
||||
// An API change reaches the classes that use the class or a subclass of it.
|
||||
f.write(
|
||||
"lib/src/main/java/l/Base.java",
|
||||
"package l;\npublic class Base { public int m() { return 1; } public int n() { return 2; } }\n",
|
||||
);
|
||||
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)", "javac lib (main, 2 of 6 files)"]);
|
||||
|
||||
// Across modules: only the classes that use it.
|
||||
f.write(
|
||||
"lib/src/main/java/l/Other.java",
|
||||
"package l;\npublic class Other { public int o() { return 2; } public void p() {} }\n",
|
||||
);
|
||||
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)", "javac app (main, 1 of 2 files)"]);
|
||||
|
||||
// A compile-time constant is copied into its uses: everything compiled against it compiles again.
|
||||
f.write("lib/src/main/java/l/Const.java", "package l;\npublic class Const { public static final int X = 2; }\n");
|
||||
assert_eq!(
|
||||
f.steps_of_launch(),
|
||||
["javac lib (main, 1 of 6 files)", "javac lib (main, 5 of 6 files)", "javac app (main, 2 files)"]
|
||||
);
|
||||
|
||||
// A removed method fails the classes that still call it.
|
||||
f.write("lib/src/main/java/l/Base.java", "package l;\npublic class Base { public int n() { return 2; } }\n");
|
||||
let failed = f.launch(false);
|
||||
assert!(failed.failure.expect("fails").contains("User.java"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_api_change_from_a_failed_build_still_reaches_other_modules() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
("lib/src/main/java/l/L.java", "package l;\npublic class L { public static int m() { return 1; } }\n"),
|
||||
("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.m(); } }\n"),
|
||||
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return l.L.m(); } }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(f.launch(false).failure, None);
|
||||
|
||||
// L compiles, then U, which still calls the removed method, fails lib before app compiles.
|
||||
f.write("lib/src/main/java/l/L.java", "package l;\npublic class L { public static int n() { return 1; } }\n");
|
||||
assert!(f.launch(false).failure.expect("lib fails").contains("U.java"));
|
||||
|
||||
// Once lib compiles, app learns that L changed, and A fails too instead of keeping a class
|
||||
// that calls a method L no longer has.
|
||||
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n(); } }\n");
|
||||
let failed = f.launch(false);
|
||||
assert!(failed.failure.expect("app fails").contains("A.java"), "{:?}", failed.messages);
|
||||
|
||||
// So does a changed constant: C compiles, then the whole set, where U fails.
|
||||
f.write("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return l.L.n() + l.C.X; } }\n");
|
||||
let c = |x: u32, y: &str| format!("package l;\npublic class C {{ public static final int X = {x};{y} }}\n");
|
||||
f.write("lib/src/main/java/l/C.java", &c(1, " public static int y() { return 0; }"));
|
||||
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n() + C.y(); } }\n");
|
||||
assert_eq!(f.launch(false).failure, None);
|
||||
f.write("lib/src/main/java/l/C.java", &c(2, ""));
|
||||
assert!(f.launch(false).failure.expect("lib fails").contains("U.java"));
|
||||
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n(); } }\n");
|
||||
f.steps();
|
||||
assert_eq!(f.launch(false).failure, None);
|
||||
let steps = f.steps();
|
||||
assert!(steps.contains(&"javac app (main, 1 file)".to_owned()), "{steps:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_what_a_class_file_declares() {
|
||||
let Some((home, _)) = tools() else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let compile = |text: &str| {
|
||||
write(tmp.path(), "p/C.java", text);
|
||||
let status = std::process::Command::new(home.join("bin/javac"))
|
||||
.args(["-d", "out", "p/C.java"])
|
||||
.current_dir(tmp.path())
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
classfile::parse(&fs::read(tmp.path().join("out/p/C.class")).unwrap()).unwrap()
|
||||
};
|
||||
let a = compile(
|
||||
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JButton> f;\n public x.Y g() { return null; }\n private int hidden() { return 1; }\n}\nclass Z {}\n"
|
||||
.replace("x.Y", "Object")
|
||||
.as_str(),
|
||||
);
|
||||
assert_eq!(a.name, "p/C");
|
||||
assert_eq!(a.super_name.as_deref(), Some("java/lang/Thread"));
|
||||
assert_eq!(a.interfaces, ["java/lang/Runnable"]);
|
||||
assert!(a.refs.contains("javax/swing/JButton"), "{:?}", a.refs);
|
||||
assert!(!a.refs.iter().any(|r| r.starts_with("java/")), "{:?}", a.refs);
|
||||
// Private members and method bodies aren't API; constants have their own fingerprint.
|
||||
let b = compile(
|
||||
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JButton> f;\n public Object g() { return \"x\"; }\n private long hidden2() { return 1; }\n}\nclass Z {}\n",
|
||||
);
|
||||
assert_eq!((a.api, a.constants), (b.api, b.constants));
|
||||
let c = compile(
|
||||
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"changed\";\n @Deprecated public List<javax.swing.JButton> f;\n public Object g() { return \"x\"; }\n}\nclass Z {}\n",
|
||||
);
|
||||
assert_eq!(a.api, c.api);
|
||||
assert_ne!(a.constants, c.constants);
|
||||
let d = compile(
|
||||
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JLabel> f;\n public Object g() { return \"x\"; }\n}\nclass Z {}\n",
|
||||
);
|
||||
assert_ne!(a.api, d.api);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follows_api_changes_through_the_log() {
|
||||
let mut state = SetState { generation: 1, ..Default::default() };
|
||||
state.log(2, ["a/A".to_owned()].into(), false);
|
||||
state.log(3, ["a/B".to_owned()].into(), false);
|
||||
assert_eq!(state.changes_since(3), Some(BTreeSet::new()));
|
||||
assert_eq!(state.changes_since(2), Some(["a/B".to_owned()].into()));
|
||||
assert_eq!(state.changes_since(1), Some(["a/A".to_owned(), "a/B".to_owned()].into()));
|
||||
// Unknown generations, and a log entry where everything changed, mean everything.
|
||||
assert_eq!(state.changes_since(0), None);
|
||||
state.log(4, BTreeSet::new(), true);
|
||||
assert_eq!(state.changes_since(3), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ant_patterns_match_like_maven() {
|
||||
assert!(ant_match("**/*.java", "a/b/C.java"));
|
||||
assert!(ant_match("**/*.java", "C.java"));
|
||||
assert!(ant_match("com/acme/**", "com/acme/x/Y.java"));
|
||||
assert!(!ant_match("com/acme/**", "com/other/Y.java"));
|
||||
assert!(ant_match("**/generated/", "x/generated/Y.java"));
|
||||
assert!(ant_match("**/*Test?.java", "a/FooTest1.java"));
|
||||
assert!(!ant_match("*.java", "a/B.java"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_options_follow_the_compiler_configuration() {
|
||||
let set = SourceSet {
|
||||
output: PathBuf::from("/o"),
|
||||
compiler: Some(CompilerConfig {
|
||||
release: Some("17".into()),
|
||||
source: Some("1.8".into()),
|
||||
encoding: Some("UTF-8".into()),
|
||||
parameters: Some(true),
|
||||
debuglevel: Some("lines,vars".into()),
|
||||
proc: Some("none".into()),
|
||||
processor_path: Some(vec![PathBuf::from("/p.jar")]),
|
||||
annotation_processors: Some(vec!["a.P".into()]),
|
||||
compiler_args: vec!["-Xlint:unchecked".into()],
|
||||
compiler_arguments: [("Akey=v".to_owned(), None)].into(),
|
||||
show_warnings: Some(false),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let args = javac_options(&set, &[PathBuf::from("/lib.jar")], Path::new("/gen"), Some(21));
|
||||
let joined = args.join(" ");
|
||||
let separator = if cfg!(windows) { ";" } else { ":" };
|
||||
assert!(joined.starts_with(&format!("-d /o -classpath /o{separator}/lib.jar -sourcepath -s /gen")), "{joined}");
|
||||
for expected in [
|
||||
"-processorpath /p.jar",
|
||||
"-processor a.P",
|
||||
"-proc:none",
|
||||
"-g:lines,vars",
|
||||
"-parameters",
|
||||
"-nowarn",
|
||||
"-encoding UTF-8",
|
||||
"--release 17",
|
||||
"-Akey=v",
|
||||
] {
|
||||
assert!(joined.contains(expected), "{expected} in {joined}");
|
||||
}
|
||||
assert!(joined.ends_with("-Xlint:unchecked"), "{joined}");
|
||||
// JDK 8 has no --release: source and target instead.
|
||||
let old = javac_options(&set, &[], Path::new("/gen"), Some(8)).join(" ");
|
||||
assert!(old.contains("-source 1.8") && !old.contains("--release"), "{old}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_gradle_projects_with_javac_and_only_what_changed() {
|
||||
let Some(f) = Fixture::gradle(&[
|
||||
(
|
||||
"lib/src/main/java/l/L.java",
|
||||
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
|
||||
),
|
||||
(
|
||||
"app/src/main/java/a/A.java",
|
||||
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
|
||||
),
|
||||
("app/src/main/resources/app.properties", "version=${version}\n"),
|
||||
("app/src/test/java/a/ATest.java", "package a;\npublic class ATest { String s = l.L.name(); }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 3, "{steps:?}");
|
||||
assert!(steps[0].contains("openideaBuildModel"), "{steps:?}");
|
||||
assert!(steps[1].starts_with("javac lib (main"), "{steps:?}");
|
||||
assert!(steps[2].starts_with("javac app (main"), "{steps:?}");
|
||||
assert!(f.out("t.lib/classes/l/L.class").is_file());
|
||||
assert!(f.out("t.app/classes/a/A.class").is_file());
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
|
||||
// Gradle's own outputs stay untouched.
|
||||
assert!(!f.root.join("app/build/classes").exists());
|
||||
|
||||
let built = f.launch(false);
|
||||
assert!(built.class_paths.iter().any(|p| p.ends_with("t.lib/classes")), "{:?}", built.class_paths);
|
||||
assert!(!built.class_paths.iter().any(|p| p.extension().is_some_and(|e| e == "jar")), "{:?}", built.class_paths);
|
||||
assert_eq!(f.steps(), Vec::<String>::new(), "nothing changed");
|
||||
|
||||
f.write(
|
||||
"app/src/main/java/a/A.java",
|
||||
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name() + 1); } }\n",
|
||||
);
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 1, "{steps:?}");
|
||||
assert!(steps[0].starts_with("javac app (main"), "{steps:?}");
|
||||
|
||||
f.write("app/src/main/resources/app.properties", "version=${version}\nname=app\n");
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 1, "{steps:?}");
|
||||
assert!(steps[0].contains(":app:processResources"), "{steps:?}");
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nname=app\n");
|
||||
|
||||
// Tests compile against the main classes.
|
||||
f.steps();
|
||||
let built = f.launch(true);
|
||||
assert_eq!(built.failure, None, "{:?}", built.messages);
|
||||
assert!(f.out("t.app/test-classes/a/ATest.class").is_file());
|
||||
|
||||
// A changed build script prepares again.
|
||||
f.write("lib/build.gradle", "// changed\n");
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(steps[0].contains("openideaBuildModel"), "{steps:?}");
|
||||
|
||||
// An error is a javac diagnostic on the source.
|
||||
f.write("lib/src/main/java/l/L.java", "package l;\npublic class L { public static String name() { return 1; } }\n");
|
||||
let built = f.launch(false);
|
||||
assert!(built.failure.is_some());
|
||||
let error = built.messages.iter().find(|m| m.severity == Severity::Error).expect("an error");
|
||||
assert_eq!(error.path.as_deref(), Some(f.root.join("lib/src/main/java/l/L.java").as_path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_gradle_projects_with_other_compilers_to_gradle() {
|
||||
let Some(f) = Fixture::gradle(&[
|
||||
("app/build.gradle", "apply plugin: 'groovy'\ndependencies { implementation project(':lib') }\n"),
|
||||
("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let jdk = |_: Option<u32>| None;
|
||||
let build = JavaBuild {
|
||||
root: &f.root,
|
||||
model: &f.model,
|
||||
cache: &f.cache,
|
||||
jar: Path::new(JAR),
|
||||
jar_version: "test",
|
||||
local_repo: None,
|
||||
service: &f.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
let target = Target::Launch { module: &f.root.join("app"), test: false };
|
||||
match build.build(target, BuildKind::Build, &CancellationToken::new(), &|_| {}) {
|
||||
Ok(Built::Unsupported(reason)) => assert!(reason.contains("GroovyCompile"), "{reason}"),
|
||||
Ok(Built::Done(outputs)) => panic!("built: {outputs:?}"),
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ pub mod application_update;
|
||||
pub mod compile;
|
||||
pub mod gradle;
|
||||
mod gradle_deps;
|
||||
pub mod jbuild;
|
||||
pub mod kotlin_bridge;
|
||||
pub mod maven;
|
||||
pub mod pom_edit;
|
||||
@@ -163,12 +164,13 @@ pub fn maven_external_roots(
|
||||
gradle::external_roots(root, owned.iter().map(String::as_str))
|
||||
}
|
||||
|
||||
/// Source, resource and build folders of the last Gradle sync, absolute.
|
||||
/// Source, resource and build folders of the last Gradle sync, with the folder of the
|
||||
/// project reporting each; all absolute.
|
||||
pub fn gradle_source_roots(
|
||||
root: &Path,
|
||||
cache_dir: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
) -> Vec<(PathBuf, gradle::ReportedRoot)> {
|
||||
) -> Vec<(PathBuf, gradle::ReportedRoot, PathBuf)> {
|
||||
let reported = gradle::linked_dirs(root, settings)
|
||||
.iter()
|
||||
.flat_map(|dir| sync::reported_gradle_projects(&gradle::cache_dir(cache_dir, dir)).as_ref().clone())
|
||||
|
||||
@@ -753,7 +753,26 @@ pub(crate) fn launch_inputs(
|
||||
projects: &[&MavenProject],
|
||||
local_repo: Option<PathBuf>,
|
||||
) -> Option<Vec<PathBuf>> {
|
||||
fn roots(el: &Element, parent: &str, dir: &Path, out: &mut Vec<PathBuf>) -> Option<()> {
|
||||
project_inputs(root, projects, local_repo, true)
|
||||
}
|
||||
|
||||
/// The POM chains (with imported BOMs) of `projects` and the files their profiles activate
|
||||
/// on: what Maven's model of them is built from, without their sources.
|
||||
pub(crate) fn model_inputs(
|
||||
root: &Path,
|
||||
projects: &[&MavenProject],
|
||||
local_repo: Option<PathBuf>,
|
||||
) -> Option<Vec<PathBuf>> {
|
||||
project_inputs(root, projects, local_repo, false)
|
||||
}
|
||||
|
||||
fn project_inputs(
|
||||
root: &Path,
|
||||
projects: &[&MavenProject],
|
||||
local_repo: Option<PathBuf>,
|
||||
sources: bool,
|
||||
) -> Option<Vec<PathBuf>> {
|
||||
fn roots(el: &Element, parent: &str, dir: &Path, sources: bool, out: &mut Vec<PathBuf>) -> Option<()> {
|
||||
let input =
|
||||
matches!(el.name.as_str(), "sourceDirectory" | "testSourceDirectory" | "sourceDir" | "testSourceDir")
|
||||
|| (matches!(parent, "sources" | "sourceDirs" | "testSources" | "testSourceDirs")
|
||||
@@ -762,6 +781,7 @@ pub(crate) fn launch_inputs(
|
||||
|| (parent == "filters" && el.name == "filter");
|
||||
// Profile activation may depend on the presence of an otherwise unrelated file.
|
||||
let activation = parent == "file" && matches!(el.name.as_str(), "exists" | "missing");
|
||||
let input = input && sources;
|
||||
if input || activation {
|
||||
// A source root under Maven's build directory is generated by the build itself.
|
||||
// Skip it without resolving the property: `<build><directory>` may be custom, and
|
||||
@@ -787,7 +807,7 @@ pub(crate) fn launch_inputs(
|
||||
}
|
||||
}
|
||||
for child in &el.children {
|
||||
roots(child, &el.name, dir, out)?;
|
||||
roots(child, &el.name, dir, sources, out)?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
@@ -796,7 +816,9 @@ pub(crate) fn launch_inputs(
|
||||
for project in projects {
|
||||
let dir = root.join(&project.dir);
|
||||
// Include all conventional language/resource roots, including nonstandard files under src.
|
||||
out.push(dir.join("src"));
|
||||
if sources {
|
||||
out.push(dir.join("src"));
|
||||
}
|
||||
let pom = root.join(&project.pom);
|
||||
resolver.context(&pom, 0);
|
||||
let mut path = pom;
|
||||
@@ -808,7 +830,7 @@ pub(crate) fn launch_inputs(
|
||||
}
|
||||
out.push(path.clone());
|
||||
let text = xml::read_text(&path)?;
|
||||
roots(&xml::parse(&text)?, "", &dir, &mut out)?;
|
||||
roots(&xml::parse(&text)?, "", &dir, sources, &mut out)?;
|
||||
let raw = resolver.pom(&path)?;
|
||||
let Some(parent) = raw.parent else { break };
|
||||
path = resolver.parent_path(path.parent()?, &parent)?;
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::io::{BufRead, BufReader, Read};
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Stream {
|
||||
@@ -28,6 +28,8 @@ pub(crate) const MAX_TEXT_BYTES: usize = 32 * 1024 * 1024;
|
||||
/// `on_line` takes its lines waits on its full pipe, as it would on a terminal, instead of
|
||||
/// the lines piling up in memory (a line is at most [`MAX_LINE_BYTES`] in [`run_bounded`]).
|
||||
const LINE_QUEUE: usize = 64;
|
||||
/// How long output may keep arriving after the child exits before the run stops reading it.
|
||||
const OUTPUT_AFTER_EXIT: Duration = Duration::from_secs(1);
|
||||
/// What [`pump_bounded`] reads from a pipe at a time.
|
||||
const PUMP_CHUNK: usize = 64 * 1024;
|
||||
|
||||
@@ -236,6 +238,10 @@ fn run_with_env_capture(
|
||||
let mut tail_bytes = 0usize;
|
||||
let mut total = 0usize;
|
||||
let mut truncated = false;
|
||||
// When the child exited. A process it left running (a Gradle daemon on Windows) can inherit
|
||||
// the pipes and keep them open long after; the run ends once they have been quiet this long.
|
||||
let mut exited: Option<Instant> = None;
|
||||
let mut pipes_held = false;
|
||||
loop {
|
||||
if cancel.is_cancelled() {
|
||||
kill_tree(&mut child);
|
||||
@@ -244,6 +250,9 @@ fn run_with_env_capture(
|
||||
match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok((_, line)) if encoding.notice.as_ref() == Some(&line) => {}
|
||||
Ok((stream, line)) => {
|
||||
if exited.is_some() {
|
||||
exited = Some(Instant::now());
|
||||
}
|
||||
on_line(stream, &line);
|
||||
if !bounded {
|
||||
// The caller parses a complete model from `text`, so keep every line.
|
||||
@@ -274,12 +283,26 @@ fn run_with_env_capture(
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => match exited {
|
||||
Some(at) if at.elapsed() >= OUTPUT_AFTER_EXIT => {
|
||||
pipes_held = true;
|
||||
break;
|
||||
}
|
||||
Some(_) => {}
|
||||
None => {
|
||||
if child.try_wait()?.is_some() {
|
||||
exited = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
for r in readers.into_iter().flatten() {
|
||||
let _ = r.join();
|
||||
// Readers still blocked on a pipe that a leftover process holds end with it, on their own.
|
||||
if !pipes_held {
|
||||
for r in readers.into_iter().flatten() {
|
||||
let _ = r.join();
|
||||
}
|
||||
}
|
||||
let status = child.wait()?;
|
||||
let mut text = head;
|
||||
@@ -392,6 +415,31 @@ mod tests {
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_process_left_holding_the_pipes_does_not_hold_the_run() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// The background child inherits stdout and stderr, as a Gradle daemon can on Windows.
|
||||
let script = "echo built; (sleep 30) & echo done >&2";
|
||||
let started = Instant::now();
|
||||
let mut lines = Vec::new();
|
||||
let out = run(
|
||||
"sh",
|
||||
&["-c".into(), script.into()],
|
||||
tmp.path(),
|
||||
&BTreeMap::new(),
|
||||
&CancellationToken::new(),
|
||||
|_, l| lines.push(l.to_owned()),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(started.elapsed() < Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
assert!(out.success);
|
||||
lines.sort();
|
||||
assert_eq!(lines, ["built", "done"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_kills_grandchildren() {
|
||||
if cfg!(windows) {
|
||||
|
||||
@@ -807,12 +807,13 @@ mod tests {
|
||||
Some(gradle::ProcessedResources { task: "processResources".into(), dir: "/p/build/resources/main".into() })
|
||||
);
|
||||
let src = |p: &str| PathBuf::from(core_src(p));
|
||||
let core = PathBuf::from(format!("{b}/modules/core"));
|
||||
assert_eq!(
|
||||
gradle::reported_source_roots(&projects),
|
||||
[
|
||||
(src("main/java"), gradle::ReportedRoot::Source),
|
||||
(src("main/resources"), gradle::ReportedRoot::Resources),
|
||||
(src("test/java"), gradle::ReportedRoot::Test),
|
||||
(src("main/java"), gradle::ReportedRoot::Source, core.clone()),
|
||||
(src("main/resources"), gradle::ReportedRoot::Resources, core.clone()),
|
||||
(src("test/java"), gradle::ReportedRoot::Test, core),
|
||||
]
|
||||
);
|
||||
let mut model = gradle::load(&root).unwrap();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-clipboard"
|
||||
description = "The OS clipboard's file list (Explorer <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB or macOS NSPasteboard, no window or message loop"
|
||||
description = "The OS clipboard's file list (file manager <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB, macOS NSPasteboard, Linux text/uri-list via GTK"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -16,8 +16,12 @@
|
||||
//! thread: AppKit and WebKit also access the general pasteboard there, and its
|
||||
//! mutable type cache cannot be protected by a mutex in this crate.
|
||||
//!
|
||||
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
|
||||
//! empty and [`set_files`] fails there.
|
||||
//! Linux keeps it as `text/uri-list` (Dolphin, Nautilus and most file
|
||||
//! managers) or GNOME's `x-special/gnome-copied-files` (`copy` or `cut`, then
|
||||
//! one URI per line), read and written through the GTK clipboard on X11 and
|
||||
//! Wayland alike; [`request_files`] reads it without blocking the main loop.
|
||||
//! Other platforms are not wired up: [`files`] is empty and [`set_files`]
|
||||
//! fails there.
|
||||
//!
|
||||
//! [`png`] reads an image (a screenshot) for the project view's Paste, which
|
||||
//! saves it as a file: `public.png` or `public.tiff` on macOS, the registered
|
||||
@@ -54,9 +58,10 @@ pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
|
||||
imp::set_text(text, owner)
|
||||
}
|
||||
|
||||
/// The clipboard's plain text, None when it holds none. macOS only (main thread);
|
||||
/// Linux reads it asynchronously through GTK in the app, Windows through the WebView.
|
||||
#[cfg(target_os = "macos")]
|
||||
/// The clipboard's plain text. None when macOS holds none, or when Windows cannot
|
||||
/// open the clipboard; empty when Windows holds none. Call on the main thread on
|
||||
/// macOS; Linux reads it asynchronously through GTK in the app.
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
pub fn text() -> Option<String> {
|
||||
imp::text()
|
||||
}
|
||||
@@ -79,6 +84,7 @@ const HEADER: usize = 20;
|
||||
|
||||
/// The absolute paths on the clipboard, empty when it holds no file list.
|
||||
/// Read failures remain errors so callers can retain an internal copy.
|
||||
/// Empty on Linux, where [`request_files`] reads it.
|
||||
pub fn files() -> std::io::Result<Vec<PathBuf>> {
|
||||
imp::files()
|
||||
}
|
||||
@@ -101,7 +107,7 @@ pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
/// line. An editor paste inserts names, not the absolute paths the file list
|
||||
/// keeps for Explorer (#1878; IDEA's text flavor is names too). A path with no
|
||||
/// file name (a root like `C:\`) keeps its whole path.
|
||||
#[cfg(any(windows, target_os = "macos", test))]
|
||||
#[cfg(any(windows, target_os = "macos", target_os = "linux", test))]
|
||||
fn names_text(paths: &[PathBuf], separator: &str) -> String {
|
||||
paths
|
||||
.iter()
|
||||
@@ -112,6 +118,82 @@ fn names_text(paths: &[PathBuf], separator: &str) -> String {
|
||||
.join(separator)
|
||||
}
|
||||
|
||||
/// The `file://` URIs in a `text/uri-list` or `x-special/gnome-copied-files`
|
||||
/// payload as local paths: comments, the `copy`/`cut` line and URIs for other
|
||||
/// hosts or schemes are skipped.
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
fn uri_list_paths(text: &str) -> Vec<PathBuf> {
|
||||
text.lines().map(str::trim).filter(|line| !line.starts_with('#')).filter_map(uri_to_path).collect()
|
||||
}
|
||||
|
||||
/// A local `file://` URI (`file:///a%20b` or `file://localhost/a%20b`) as a
|
||||
/// path; its percent-escapes are raw bytes, as GLib writes them.
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
fn uri_to_path(uri: &str) -> Option<PathBuf> {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let rest = uri.strip_prefix("file://")?;
|
||||
let path = if rest.starts_with('/') { rest } else { rest.strip_prefix("localhost")? };
|
||||
let path = path.split(['?', '#']).next()?;
|
||||
if !path.starts_with('/') {
|
||||
return None;
|
||||
}
|
||||
let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
|
||||
let bytes = path.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
let escaped =
|
||||
(bytes[i] == b'%').then(|| Some((hex(*bytes.get(i + 1)?)? << 4) | hex(*bytes.get(i + 2)?)?)).flatten();
|
||||
match escaped {
|
||||
Some(b) => {
|
||||
out.push(b);
|
||||
i += 3;
|
||||
}
|
||||
None => {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(PathBuf::from(std::ffi::OsString::from_vec(out)))
|
||||
}
|
||||
|
||||
/// `path` as a `file://` URI, every byte outside the unreserved set and `/`
|
||||
/// percent-escaped.
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
fn file_uri(path: &std::path::Path) -> String {
|
||||
use std::fmt::Write;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let mut uri = String::from("file://");
|
||||
for &b in path.as_os_str().as_bytes() {
|
||||
if b.is_ascii_alphanumeric() || b"/-._~".contains(&b) {
|
||||
uri.push(b as char);
|
||||
} else {
|
||||
let _ = write!(uri, "%{b:02X}");
|
||||
}
|
||||
}
|
||||
uri
|
||||
}
|
||||
|
||||
/// Reads the clipboard's file list without blocking: `text/uri-list` first,
|
||||
/// then GNOME's list, and calls `done` with the paths (empty without a list).
|
||||
/// Call on the main thread; `done` runs there later.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn request_files(done: impl FnOnce(Vec<PathBuf>) + 'static) {
|
||||
use gtk::gdk::{Atom, SELECTION_CLIPBOARD};
|
||||
fn paths_in(data: >k::SelectionData) -> Vec<PathBuf> {
|
||||
// A failed request has a negative length and no data.
|
||||
if data.length() <= 0 { Vec::new() } else { uri_list_paths(&String::from_utf8_lossy(&data.data())) }
|
||||
}
|
||||
gtk::Clipboard::get(&SELECTION_CLIPBOARD).request_contents(&Atom::intern(imp::URI_LIST), move |board, data| {
|
||||
let paths = paths_in(data);
|
||||
if !paths.is_empty() {
|
||||
return done(paths);
|
||||
}
|
||||
board.request_contents(&Atom::intern(imp::GNOME_COPIED), move |_, data| done(paths_in(data)));
|
||||
});
|
||||
}
|
||||
|
||||
/// `DROPFILES` for `paths`, in the wide form so names outside the ANSI code
|
||||
/// page survive. Empty paths are skipped.
|
||||
pub fn encode(paths: &[PathBuf]) -> Vec<u8> {
|
||||
@@ -174,6 +256,15 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// A `CF_UNICODETEXT` block as a string: UTF-16LE up to the first NUL. The block
|
||||
/// may be larger than the text, and a malformed one may lack the NUL.
|
||||
#[cfg(any(windows, test))]
|
||||
fn unicode_text(bytes: &[u8]) -> String {
|
||||
let units: Vec<u16> =
|
||||
bytes.chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).take_while(|&unit| unit != 0).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
}
|
||||
|
||||
/// `BI_RGB` and `BI_BITFIELDS`: uncompressed pixels, the forms screenshots take.
|
||||
#[cfg(any(windows, test))]
|
||||
const BI_RGB: u32 = 0;
|
||||
@@ -229,7 +320,7 @@ fn dib_to_png(dib: &[u8]) -> Option<Vec<u8>> {
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use super::{HEADER, decode, dib_to_png, encode, names_text};
|
||||
use super::{HEADER, decode, dib_to_png, encode, names_text, unicode_text};
|
||||
use std::ffi::c_void;
|
||||
use std::path::PathBuf;
|
||||
use std::ptr;
|
||||
@@ -313,6 +404,19 @@ mod imp {
|
||||
image
|
||||
}
|
||||
|
||||
pub fn text() -> Option<String> {
|
||||
// Empty rather than None: a None falls back to the WebView, which prompts the user.
|
||||
if unsafe { IsClipboardFormatAvailable(CF_UNICODETEXT) } == 0 {
|
||||
return Some(String::new());
|
||||
}
|
||||
if !open() {
|
||||
return None;
|
||||
}
|
||||
let text = read_block(CF_UNICODETEXT).map(|bytes| unicode_text(&bytes));
|
||||
unsafe { CloseClipboard() };
|
||||
text
|
||||
}
|
||||
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn GlobalAlloc(flags: u32, bytes: usize) -> Handle;
|
||||
@@ -728,8 +832,25 @@ mod imp {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const URI_LIST: &str = "text/uri-list";
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const GNOME_COPIED: &str = "x-special/gnome-copied-files";
|
||||
|
||||
pub fn has_files() -> bool {
|
||||
false
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).wait_for_targets().is_some_and(|targets| {
|
||||
targets.into_iter().any(|target| {
|
||||
let name = target.name();
|
||||
name == URI_LIST || name == GNOME_COPIED
|
||||
})
|
||||
})
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_image() -> bool {
|
||||
@@ -747,6 +868,33 @@ mod imp {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// Offers `paths` as `text/uri-list` (KDE and most file managers), GNOME's
|
||||
/// list (Nautilus, Thunar) and their names as text, rendered on request.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
use gtk::{TargetEntry, TargetFlags};
|
||||
let uris: Vec<String> = paths.iter().map(|p| super::file_uri(p)).collect();
|
||||
let uri_list: String = uris.iter().map(|uri| format!("{uri}\r\n")).collect();
|
||||
let gnome = format!("copy\n{}", uris.join("\n"));
|
||||
let names = super::names_text(paths, "\n");
|
||||
let entry = |name: &str, info: u32| TargetEntry::new(name, TargetFlags::empty(), info);
|
||||
let targets = [
|
||||
entry(URI_LIST, 0),
|
||||
entry(GNOME_COPIED, 1),
|
||||
entry("UTF8_STRING", 2),
|
||||
entry("text/plain;charset=utf-8", 2),
|
||||
entry("text/plain", 2),
|
||||
];
|
||||
gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).set_with_data(&targets, move |_, data, info| match info {
|
||||
0 => data.set(&data.target(), 8, uri_list.as_bytes()),
|
||||
1 => data.set(&data.target(), 8, gnome.as_bytes()),
|
||||
_ => {
|
||||
let _ = data.set_text(&names);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn set_files(_paths: &[PathBuf]) -> bool {
|
||||
false
|
||||
}
|
||||
@@ -765,10 +913,42 @@ mod tests {
|
||||
assert!(set_png(&header, 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_text_stops_at_the_nul() {
|
||||
let mut bytes: Vec<u8> = "héllo\r\n世界".encode_utf16().chain([0, 0x41]).flat_map(u16::to_le_bytes).collect();
|
||||
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
|
||||
// No terminator, and a stray odd byte, still read the whole text.
|
||||
bytes.truncate(bytes.len() - 4);
|
||||
bytes.push(7);
|
||||
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
|
||||
}
|
||||
|
||||
fn paths(list: &[&str]) -> Vec<PathBuf> {
|
||||
list.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn file_manager_uri_lists_become_paths() {
|
||||
// Dolphin: CRLF-separated `text/uri-list`, with a comment line.
|
||||
let kde = "# copied\r\nfile:///home/u/a%20b.txt\r\nfile://localhost/home/u/%E6%A1%8C%E9%9D%A2\r\n";
|
||||
assert_eq!(uri_list_paths(kde), paths(&["/home/u/a b.txt", "/home/u/桌面"]));
|
||||
// Nautilus/Thunar: `copy` or `cut`, then one URI per line.
|
||||
assert_eq!(uri_list_paths("cut\nfile:///tmp/x\nfile:///tmp/y"), paths(&["/tmp/x", "/tmp/y"]));
|
||||
// Other hosts and schemes are not local files.
|
||||
assert!(uri_list_paths("file://server/share/x\nhttps://example.com/x\nsmb:///x").is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn written_uris_read_back_as_the_same_paths() {
|
||||
let list = paths(&["/home/u/a b#1%.txt", "/home/u/桌面/项目", "/tmp/plain-name_1.~"]);
|
||||
let uris: Vec<String> = list.iter().map(|p| file_uri(p)).collect();
|
||||
assert_eq!(uris[0], "file:///home/u/a%20b%231%25.txt");
|
||||
assert_eq!(uris[2], "file:///tmp/plain-name_1.~");
|
||||
assert_eq!(uri_list_paths(&uris.join("\r\n")), list);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_written_list_reads_back_unchanged() {
|
||||
let list = paths(&["C:/work/project/a.txt", "C:/work/project/sub"]);
|
||||
|
||||
@@ -15,12 +15,16 @@ specta.workspace = true
|
||||
specta-typescript.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio-util.workspace = true
|
||||
portable-pty.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
sha2 = "0.10"
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
dirs.workspace = true
|
||||
tracing.workspace = true
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
@@ -0,0 +1,21 @@
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,39 @@
|
||||
# Bundled Windows console host
|
||||
|
||||
Unmodified files from Microsoft's MIT-licensed
|
||||
[Microsoft.Windows.Console.ConPTY 1.25.260930003](https://www.nuget.org/packages/Microsoft.Windows.Console.ConPTY/1.25.260930003).
|
||||
The system ConPTY on Windows 10 build 19045 consumes alternate-screen transitions; xterm then
|
||||
puts full-screen applications' redraws in normal scrollback. A current console host
|
||||
preserves those transitions, including while resizing and updating a running TUI.
|
||||
|
||||
The package is pinned, checked in and embedded by `ide-core`, so desktop, server,
|
||||
Run and debugger builds work offline and do not depend on another installed IDE.
|
||||
Only the target architecture is embedded, along with its MIT license. `src/pty.rs`
|
||||
extracts them atomically to a versioned user cache and preloads the DLL's absolute
|
||||
path before portable-pty initializes.
|
||||
Windows reuses that module when portable-pty loads `conpty.dll` by name. Loading
|
||||
failure is logged and falls back to the system backend. Windows builds before
|
||||
19041 also retain the system backend.
|
||||
|
||||
Source archive:
|
||||
`https://api.nuget.org/v3-flatcontainer/microsoft.windows.console.conpty/1.25.260930003/microsoft.windows.console.conpty.1.25.260930003.nupkg`
|
||||
|
||||
Archive SHA-256: `02b07b349af66d801159bdf9e440d4a1ce78bb951f37fc8609731665afdae7ee`
|
||||
|
||||
For each architecture, `conpty.dll` comes from
|
||||
`runtimes/win-<arch>/native/conpty.dll`, and `OpenConsole.exe` from
|
||||
`build/native/runtimes/<arch>/OpenConsole.exe` in that archive. Preserve the pair and
|
||||
the license when updating; update `VERSION` in `src/pty.rs` and these checksums too.
|
||||
|
||||
| File | SHA-256 |
|
||||
| --------------------- | ------------------------------------------------------------------ |
|
||||
| arm64/conpty.dll | `151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf` |
|
||||
| arm64/OpenConsole.exe | `4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f` |
|
||||
| x64/conpty.dll | `feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a` |
|
||||
| x64/OpenConsole.exe | `3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586` |
|
||||
| x86/conpty.dll | `d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93` |
|
||||
| x86/OpenConsole.exe | `e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3` |
|
||||
|
||||
Verification: `cargo test -p ide-core pty::`. `pty::checksums` checks the embedded files against the table above on every platform. The native PTY test launches a child
|
||||
console application and requires alternate-screen entry and exit to reach the
|
||||
reader; a system ConPTY that consumes them fails this check.
|
||||
Бінарний файл не відображається.
Бінарний файл не відображається.
Бінарний файл не відображається.
Бінарний файл не відображається.
Бінарний файл не відображається.
Бінарний файл не відображається.
@@ -19,12 +19,14 @@ pub mod java_runtime;
|
||||
pub mod jsonc;
|
||||
pub mod memory;
|
||||
pub mod output_encoding;
|
||||
pub mod output_rate;
|
||||
pub mod platform;
|
||||
pub mod process;
|
||||
pub mod project_dir;
|
||||
pub mod project_env;
|
||||
pub mod project_roots;
|
||||
pub mod proxy_settings;
|
||||
pub mod pty;
|
||||
pub mod real_path;
|
||||
pub mod remote_settings;
|
||||
pub mod settings;
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
//! How often the terminal and Run console pumps hand output to the UI, from
|
||||
//! Settings › Tools › Terminal › Max FPS (#5897). The frontend paints at most that
|
||||
//! often anyway; batching at half its frame interval keeps a fresh batch ready for
|
||||
//! every frame while cutting the IPC events (and their handling on the UI thread)
|
||||
//! that would only be buffered there.
|
||||
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Frames per second; 0 is Unlimited.
|
||||
static MAX_FPS: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// Applies the `terminal.maxFps` setting: `"unlimited"` or a number of frames per second.
|
||||
/// Running sessions pick it up at their next batch.
|
||||
pub fn set_max_fps(setting: &str) {
|
||||
MAX_FPS.store(setting.trim().parse::<u32>().unwrap_or(0), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The batch interval for a pump whose Unlimited interval is `unlimited`.
|
||||
pub fn batch_interval(unlimited: Duration) -> Duration {
|
||||
interval_for(MAX_FPS.load(Ordering::Relaxed), unlimited)
|
||||
}
|
||||
|
||||
/// Half the paint interval, within 4–200 ms, and never faster than the Unlimited rate.
|
||||
fn interval_for(fps: u32, unlimited: Duration) -> Duration {
|
||||
if fps == 0 {
|
||||
return unlimited;
|
||||
}
|
||||
Duration::from_millis((500 / u64::from(fps)).clamp(4, 200)).max(unlimited)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn interval_is_half_the_frame_and_clamped() {
|
||||
let terminal = Duration::from_millis(4);
|
||||
let run = Duration::from_millis(8);
|
||||
let ms = |fps, unlimited| interval_for(fps, unlimited).as_millis();
|
||||
assert_eq!(ms(0, terminal), 4, "Unlimited keeps the pump's own rate");
|
||||
assert_eq!(ms(0, run), 8);
|
||||
assert_eq!([60, 30, 15, 10, 5].map(|fps| ms(fps, terminal)), [8, 16, 33, 50, 100]);
|
||||
assert_eq!(ms(1, terminal), 200, "upper bound");
|
||||
assert_eq!(ms(1000, terminal), 4, "lower bound");
|
||||
assert_eq!(ms(1000, run), 8, "never faster than Unlimited");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_values_parse_and_unknown_means_unlimited() {
|
||||
set_max_fps("30");
|
||||
assert_eq!(batch_interval(Duration::from_millis(4)).as_millis(), 16);
|
||||
set_max_fps("unlimited");
|
||||
assert_eq!(batch_interval(Duration::from_millis(4)).as_millis(), 4);
|
||||
set_max_fps("fast");
|
||||
assert_eq!(batch_interval(Duration::from_millis(8)).as_millis(), 8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
//! The PTY backend shared by terminals, Run consoles and debugger launchers.
|
||||
|
||||
pub fn native_pty_system() -> Box<dyn portable_pty::PtySystem + Send> {
|
||||
#[cfg(windows)]
|
||||
windows::initialize();
|
||||
portable_pty::native_pty_system()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows {
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use windows_sys::Win32::Foundation::FreeLibrary;
|
||||
use windows_sys::Win32::System::LibraryLoader::{
|
||||
GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
|
||||
};
|
||||
|
||||
const VERSION: &str = "1.25.260930003";
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
const RUNTIME: (&str, &[u8], &[u8]) = (
|
||||
"x64",
|
||||
include_bytes!("../resources/conpty/x64/conpty.dll"),
|
||||
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
|
||||
);
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const RUNTIME: (&str, &[u8], &[u8]) = (
|
||||
"arm64",
|
||||
include_bytes!("../resources/conpty/arm64/conpty.dll"),
|
||||
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
|
||||
);
|
||||
#[cfg(target_arch = "x86")]
|
||||
const RUNTIME: (&str, &[u8], &[u8]) = (
|
||||
"x86",
|
||||
include_bytes!("../resources/conpty/x86/conpty.dll"),
|
||||
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
|
||||
);
|
||||
|
||||
pub(super) fn initialize() -> bool {
|
||||
static BUNDLED: OnceLock<bool> = OnceLock::new();
|
||||
*BUNDLED.get_or_init(|| {
|
||||
if !crate::platform::windows_build_number().is_some_and(|build| build >= 19041) {
|
||||
return false;
|
||||
}
|
||||
match load() {
|
||||
Ok(()) => true,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "bundled ConPTY unavailable; using the system terminal backend");
|
||||
false
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn load() -> io::Result<()> {
|
||||
let cache = dirs::cache_dir().ok_or_else(|| io::Error::other("no user cache directory"))?;
|
||||
let directory = cache.join("OpenIDEA").join("conpty").join(VERSION).join(RUNTIME.0);
|
||||
fs::create_dir_all(&directory)?;
|
||||
install(&directory.join("LICENSE.txt"), include_bytes!("../resources/conpty/LICENSE"))?;
|
||||
install(&directory.join("OpenConsole.exe"), RUNTIME.2)?;
|
||||
let library = directory.join("conpty.dll");
|
||||
install(&library, RUNTIME.1)?;
|
||||
let wide: Vec<u16> = library.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
// portable-pty 0.9 opens conpty.dll by name. Preload our verified absolute path:
|
||||
// Windows reuses this module, without adding the project directory to DLL search.
|
||||
// SAFETY: the path is terminated and the module is retained for the process lifetime.
|
||||
let module = unsafe {
|
||||
LoadLibraryExW(
|
||||
wide.as_ptr(),
|
||||
std::ptr::null_mut(),
|
||||
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32,
|
||||
)
|
||||
};
|
||||
if module.is_null() {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
for name in [c"CreatePseudoConsole", c"ResizePseudoConsole", c"ClosePseudoConsole"] {
|
||||
// SAFETY: `module` is loaded and each name is a terminated export name.
|
||||
if unsafe { GetProcAddress(module, name.as_ptr().cast()) }.is_none() {
|
||||
// SAFETY: no PTY uses this rejected module yet; release our load reference.
|
||||
unsafe { FreeLibrary(module) };
|
||||
return Err(io::Error::other("bundled ConPTY lacks the portable-pty exports"));
|
||||
}
|
||||
}
|
||||
// Keep this reference for the process lifetime, including between PTY sessions.
|
||||
tracing::info!(path = %library.display(), version = VERSION, "loaded bundled ConPTY");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn install(path: &Path, data: &[u8]) -> io::Result<()> {
|
||||
if fs::read(path).is_ok_and(|existing| existing == data) {
|
||||
return Ok(());
|
||||
}
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let pending =
|
||||
path.with_extension(format!("{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
let result = (|| {
|
||||
let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&pending)?;
|
||||
file.write_all(data)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
match fs::rename(&pending, path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(_) if fs::read(path).is_ok_and(|existing| existing == data) => Ok(()),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
})();
|
||||
let _ = fs::remove_file(pending);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn installs_atomically_and_repairs_incomplete_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("conpty.dll");
|
||||
fs::write(&path, b"partial").unwrap();
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..8 {
|
||||
let path = &path;
|
||||
scope.spawn(move || install(path, b"complete runtime").unwrap());
|
||||
}
|
||||
});
|
||||
assert_eq!(fs::read(&path).unwrap(), b"complete runtime");
|
||||
assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loads_the_bundled_backend() {
|
||||
assert!(initialize());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conpty_output_child() {
|
||||
if std::env::var_os("OPENIDEA_CONPTY_TEST_CHILD").is_none() {
|
||||
return;
|
||||
}
|
||||
use windows_sys::Win32::System::Console::{
|
||||
ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetStdHandle, STD_OUTPUT_HANDLE, SetConsoleMode,
|
||||
};
|
||||
// SAFETY: the inherited console output handle and a local writable mode word.
|
||||
unsafe {
|
||||
let output = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
let mut mode = 0;
|
||||
assert_ne!(GetConsoleMode(output, &mut mode), 0);
|
||||
assert_ne!(SetConsoleMode(output, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING), 0);
|
||||
}
|
||||
std::io::stdout()
|
||||
.write_all(b"\x1b[?1049h\x1b[2J\x1b[HWorking (3m 19s)\x1b[1;1H\x1b[2KWorking (2m 59s)\x1b[?1049l\r\nVT_DONE\r\n")
|
||||
.unwrap();
|
||||
std::io::stdout().flush().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conpty_preserves_alternate_screen_transitions() {
|
||||
use std::io::Read;
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
let pair = super::super::native_pty_system().openpty(portable_pty::PtySize::default()).unwrap();
|
||||
let mut reader = pair.master.try_clone_reader().unwrap();
|
||||
let mut writer = pair.master.take_writer().unwrap();
|
||||
let mut command = portable_pty::CommandBuilder::new(std::env::current_exe().unwrap());
|
||||
command.args(["--exact", "pty::windows::tests::conpty_output_child", "--nocapture"]);
|
||||
command.env("OPENIDEA_CONPTY_TEST_CHILD", "1");
|
||||
let mut child = pair.slave.spawn_command(command).unwrap();
|
||||
drop(pair.slave);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let reading = std::thread::spawn(move || {
|
||||
let mut bytes = [0; 4096];
|
||||
while let Ok(count) = reader.read(&mut bytes) {
|
||||
if count == 0 || tx.send(bytes[..count].to_vec()).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
let mut output = Vec::new();
|
||||
let mut cursor_replied = false;
|
||||
while Instant::now() < deadline {
|
||||
if let Ok(bytes) = rx.recv_timeout(Duration::from_millis(50)) {
|
||||
output.extend_from_slice(&bytes);
|
||||
if !cursor_replied && output.windows(4).any(|s| s == b"\x1b[6n") {
|
||||
writer.write_all(b"\x1b[1;1R").unwrap();
|
||||
cursor_replied = true;
|
||||
}
|
||||
if output.windows(7).any(|s| s == b"VT_DONE") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
drop(writer);
|
||||
drop(pair.master);
|
||||
reading.join().unwrap();
|
||||
let output = String::from_utf8_lossy(&output);
|
||||
assert!(output.contains("\x1b[?1049h"), "alternate screen entry missing: {output:?}");
|
||||
assert!(output.contains("\x1b[?1049l"), "alternate screen exit missing: {output:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The embedded runtime is the pinned NuGet package's files (`resources/conpty/README.md`).
|
||||
#[cfg(test)]
|
||||
mod checksums {
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
const FILES: [(&str, &[u8], &str); 6] = [
|
||||
(
|
||||
"arm64/conpty.dll",
|
||||
include_bytes!("../resources/conpty/arm64/conpty.dll"),
|
||||
"151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf",
|
||||
),
|
||||
(
|
||||
"arm64/OpenConsole.exe",
|
||||
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
|
||||
"4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f",
|
||||
),
|
||||
(
|
||||
"x64/conpty.dll",
|
||||
include_bytes!("../resources/conpty/x64/conpty.dll"),
|
||||
"feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a",
|
||||
),
|
||||
(
|
||||
"x64/OpenConsole.exe",
|
||||
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
|
||||
"3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586",
|
||||
),
|
||||
(
|
||||
"x86/conpty.dll",
|
||||
include_bytes!("../resources/conpty/x86/conpty.dll"),
|
||||
"d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93",
|
||||
),
|
||||
(
|
||||
"x86/OpenConsole.exe",
|
||||
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
|
||||
"e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3",
|
||||
),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn embedded_runtime_matches_the_pinned_package() {
|
||||
for (name, bytes, expected) in FILES {
|
||||
let actual: String = Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect();
|
||||
assert_eq!(actual, expected, "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -95,8 +95,6 @@ pub struct AgentSettings {
|
||||
pub show_usage_limits: bool,
|
||||
/// What the session has cost so far, as the agent reports it.
|
||||
pub show_cost: bool,
|
||||
/// A finished turn's work folds into one line under its message, leaving the reply.
|
||||
pub fold_turns: bool,
|
||||
/// Streaming text is revealed at a steady pace rather than chunk by chunk.
|
||||
pub smooth_text: bool,
|
||||
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
|
||||
@@ -145,7 +143,6 @@ impl Default for AgentSettings {
|
||||
show_work_time: true,
|
||||
show_usage_limits: true,
|
||||
show_cost: false,
|
||||
fold_turns: false,
|
||||
smooth_text: true,
|
||||
fit_window_width: false,
|
||||
thinking: ThinkingDisplay::Auto,
|
||||
@@ -420,10 +417,10 @@ impl Default for McpServerSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tools › Download sources: a mirror the installer tries when `github.com` is slow or
|
||||
/// unreachable.
|
||||
/// Tools › Download sources: mirrors the installer tries, in order, when `github.com` is slow
|
||||
/// or unreachable.
|
||||
///
|
||||
/// The mirror is a proxy prefix: the official URL is appended to it unchanged
|
||||
/// A mirror is a proxy prefix: the official URL is appended to it unchanged
|
||||
/// (`https://mirror.example/https://github.com/o/r/releases/download/…`), which is what the
|
||||
/// public GitHub proxies speak. Only `github.com` downloads are affected — those proxies
|
||||
/// hard-code that host, so Eclipse JDT LS and Open VSX keep their official addresses. Empty by
|
||||
@@ -431,8 +428,9 @@ impl Default for McpServerSettings {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ToolDownloadSettings {
|
||||
/// Proxy prefix prepended to `https://github.com/…` archive addresses only; empty keeps
|
||||
/// every download on its official host.
|
||||
/// Proxy prefixes prepended to `https://github.com/…` archive addresses only, separated by
|
||||
/// commas or whitespace and tried in order before the official host; empty keeps every
|
||||
/// download on its official host.
|
||||
pub github_mirror: String,
|
||||
}
|
||||
|
||||
@@ -826,6 +824,8 @@ pub struct AppearanceSettings {
|
||||
pub contrast_scrollbars: bool,
|
||||
/// Adjust colours for red-green vision deficiency.
|
||||
pub red_green_vision: bool,
|
||||
/// Turn off animations and transitions (also on when the OS asks for reduced motion).
|
||||
pub reduce_motion: bool,
|
||||
pub different_tool_window_background: bool,
|
||||
pub compact_mode: bool,
|
||||
/// IDEA "Use smaller indents in trees": tool window trees indent less per level.
|
||||
@@ -966,6 +966,7 @@ impl Default for AppearanceSettings {
|
||||
ui_font_fallback: String::new(),
|
||||
contrast_scrollbars: false,
|
||||
red_green_vision: false,
|
||||
reduce_motion: false,
|
||||
different_tool_window_background: false,
|
||||
compact_mode: false,
|
||||
small_tree_indents: false,
|
||||
@@ -2120,14 +2121,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn agent_meters_default_and_round_trip() {
|
||||
let old: Settings = serde_json::from_str(r#"{"agents":{"showCost":true}}"#).unwrap();
|
||||
let old: Settings = serde_json::from_str(r#"{"agents":{"showCost":true,"foldTurns":true}}"#).unwrap();
|
||||
assert!(old.agents.show_cost);
|
||||
assert!(old.agents.show_context_usage && old.agents.show_work_time && old.agents.show_usage_limits);
|
||||
assert!(!old.agents.fit_window_width);
|
||||
assert!(!old.agents.fold_turns);
|
||||
assert!(!Settings::default().agents.show_cost);
|
||||
assert!(!Settings::default().agents.fit_window_width);
|
||||
assert!(!Settings::default().agents.fold_turns);
|
||||
let mut settings = Settings::default();
|
||||
settings.agents.show_usage_limits = false;
|
||||
settings.agents.fit_window_width = true;
|
||||
|
||||
@@ -450,6 +450,21 @@ fn no_session(s: DebugSessionId) -> IdeError {
|
||||
IdeError::not_found(format!("no debug session {}", s.0))
|
||||
}
|
||||
|
||||
/// debugpy hands a subprocess (`subProcess: true`, forked or spawned) over as an `attach` whose
|
||||
/// `connect` is its own client listener: the child session is another connection to the running
|
||||
/// adapter, as VS Code makes it, not a new adapter that would take that port for a debug server.
|
||||
fn subprocess_connection(configuration: &Value, spec: &AdapterSpec) -> Option<(AdapterSpec, u16)> {
|
||||
configuration.get("subProcessId")?;
|
||||
let connect = configuration.get("connect")?;
|
||||
let port = u16::try_from(connect.get("port")?.as_u64()?).ok()?;
|
||||
let mut spec = spec.clone();
|
||||
if let Some(host) = connect.get("host").and_then(Value::as_str) {
|
||||
let loopback = host == "localhost" || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback());
|
||||
spec.server_host = (!loopback).then(|| host.to_owned());
|
||||
}
|
||||
Some((spec, port))
|
||||
}
|
||||
|
||||
/// The name of a child session: the adapter's, or the parent's when it gives none. js-debug
|
||||
/// names a browser page's session after the page the browser starts on, before the URL
|
||||
/// loads (`about:blank`, or nothing in a new profile), which says nothing about what is debugged.
|
||||
@@ -1032,6 +1047,13 @@ impl DebugManager {
|
||||
if let Some(obj) = configuration.as_object_mut() {
|
||||
obj.entry("request").or_insert_with(|| request.clone().into());
|
||||
}
|
||||
let (spec, port) = match parent.port {
|
||||
Some(port) => (parent.spec.clone(), Some(port)),
|
||||
None => match subprocess_connection(&configuration, &parent.spec) {
|
||||
Some((spec, port)) => (spec, Some(port)),
|
||||
None => (parent.spec.clone(), None),
|
||||
},
|
||||
};
|
||||
self.start_session(
|
||||
DebugSessionId::next(),
|
||||
parent.owner.clone(),
|
||||
@@ -1040,8 +1062,8 @@ impl DebugManager {
|
||||
Some(parent.id),
|
||||
request,
|
||||
configuration,
|
||||
parent.spec.clone(),
|
||||
parent.port,
|
||||
spec,
|
||||
port,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -1017,6 +1017,13 @@ fn on_reverse_request(mgr: &Arc<DebugManager>, s: &Arc<Session>, seq: i64, comma
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` as a terminal sends it when typed: Enter is CR. A Unix terminal turns CR into the
|
||||
/// newline a line read waits for, but Windows' ConPTY reads LF as Ctrl+J, so a program blocked
|
||||
/// in `input()` never sees its line end (#6041).
|
||||
fn as_typed(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
if text.contains('\n') { text.replace("\r\n", "\r").replace('\n', "\r").into() } else { text.into() }
|
||||
}
|
||||
|
||||
/// A `runInTerminal` program and the pseudo-terminal it runs in.
|
||||
pub(crate) struct ProgramTerminal {
|
||||
writer: Arc<ide_core::input::InputWriter>,
|
||||
@@ -1030,7 +1037,7 @@ pub(crate) struct ProgramTerminal {
|
||||
|
||||
impl ProgramTerminal {
|
||||
pub(crate) fn write(&mut self, text: &str) -> std::io::Result<()> {
|
||||
self.writer.write(text.as_bytes())
|
||||
self.writer.write(as_typed(text).as_bytes())
|
||||
}
|
||||
|
||||
/// The program's process id while it runs.
|
||||
@@ -1061,7 +1068,8 @@ fn reap_on_exit(mut child: Box<dyn portable_pty::Child + Send + Sync>, exited: A
|
||||
/// starts a launcher that gives the program its terminal, and the program reads input only from
|
||||
/// a terminal), forwards its output to the console, and keeps the terminal for typed input.
|
||||
pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, String> {
|
||||
use portable_pty::{CommandBuilder, PtySize, native_pty_system};
|
||||
use ide_core::pty::native_pty_system;
|
||||
use portable_pty::{CommandBuilder, PtySize};
|
||||
let argv: Vec<String> = args
|
||||
.get("args")
|
||||
.and_then(Value::as_array)
|
||||
@@ -1385,6 +1393,13 @@ fn parse_jdwp_port(line: &str) -> Option<u16> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn typed_input_ends_lines_with_enter() {
|
||||
assert_eq!(super::as_typed("42\n"), "42\r");
|
||||
assert_eq!(super::as_typed("a\r\nb\n"), "a\rb\r");
|
||||
assert_eq!(super::as_typed("no newline"), "no newline");
|
||||
}
|
||||
|
||||
use super::{Suspension, kotlin_jvm_args, parse_jdwp_port};
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -122,6 +122,8 @@ struct Script {
|
||||
run_in_terminal: Option<Vec<String>>,
|
||||
/// Send a `startDebugging` reverse request (child session) when a non-child `launch` arrives.
|
||||
start_debugging: bool,
|
||||
/// The child's `startDebugging` arguments instead of a js-debug style `launch`.
|
||||
child_request: Option<Value>,
|
||||
ignore_configuration_done: bool,
|
||||
source_path: Option<String>,
|
||||
/// Report this process id in the adapter's `process` event (the program being debugged).
|
||||
@@ -201,6 +203,7 @@ impl Default for Script {
|
||||
Self {
|
||||
run_in_terminal: None,
|
||||
start_debugging: false,
|
||||
child_request: None,
|
||||
ignore_configuration_done: false,
|
||||
source_path: None,
|
||||
debuggee_pid: None,
|
||||
@@ -365,10 +368,11 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
);
|
||||
}
|
||||
if script.start_debugging && msg["arguments"]["isChild"] != true {
|
||||
send!(
|
||||
let arguments = script.child_request.clone().unwrap_or_else(
|
||||
// Like js-debug, the child's configuration repeats the launch's `type`.
|
||||
json!({"type": "request", "command": "startDebugging", "arguments": {"request": "launch", "configuration": {"name": "child", "isChild": true, "type": msg["arguments"]["type"]}}})
|
||||
|| json!({"request": "launch", "configuration": {"name": "child", "isChild": true, "type": msg["arguments"]["type"]}}),
|
||||
);
|
||||
send!(json!({"type": "request", "command": "startDebugging", "arguments": arguments}));
|
||||
}
|
||||
if script.pending_startup != Some(false) {
|
||||
tokio::time::sleep(script.initialized_delay).await;
|
||||
@@ -1193,6 +1197,46 @@ async fn child_of(h: &Harness, parent: DebugSessionId) -> DebugSessionId {
|
||||
panic!("no child session of {parent:?}");
|
||||
}
|
||||
|
||||
/// debugpy's subprocess (`subProcess: true`): an `attach` whose `connect` is the running adapter's
|
||||
/// client listener, so the child session connects there instead of starting another adapter.
|
||||
#[tokio::test]
|
||||
async fn a_debugpy_subprocess_connects_to_the_running_adapter() {
|
||||
/// Each launch's reused port and remote host.
|
||||
type Launches = Arc<Mutex<Vec<(Option<u16>, Option<String>)>>>;
|
||||
struct CaptureLauncher {
|
||||
inner: FakeLauncher,
|
||||
launches: Launches,
|
||||
}
|
||||
impl AdapterLauncher for CaptureLauncher {
|
||||
fn launch(&self, spec: AdapterSpec, reuse: Option<u16>) -> LaunchFuture {
|
||||
self.launches.lock().push((reuse, spec.server_host.clone()));
|
||||
self.inner.launch(spec, reuse)
|
||||
}
|
||||
}
|
||||
let child = |host: &str| {
|
||||
json!({"request": "attach", "configuration": {"name": "Subprocess 42", "isChild": true, "subProcessId": 42,
|
||||
"connect": {"host": host, "port": 51234}}})
|
||||
};
|
||||
for (host, server_host) in [("127.0.0.1", None), ("10.0.0.5", Some("10.0.0.5".to_owned()))] {
|
||||
let launches: Launches = Arc::default();
|
||||
let script = Script { start_debugging: true, child_request: Some(child(host)), ..Script::default() };
|
||||
let launcher =
|
||||
CaptureLauncher { inner: FakeLauncher { log: Arc::default(), script }, launches: launches.clone() };
|
||||
let manager =
|
||||
DebugManager::with_launcher(Arc::new(LanguageRegistry::from_configs(Vec::new())), Arc::new(launcher));
|
||||
let (owner, _) = recording_owner("main");
|
||||
let parent = manager.start(config(), owner).await.unwrap();
|
||||
for _ in 0..200 {
|
||||
if launches.lock().len() == 2 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(*launches.lock(), [(None, None), (Some(51234), server_host)], "{host}");
|
||||
manager.stop(parent).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_browser_page_session_has_the_page_capability() {
|
||||
let h = harness(Script { start_debugging: true, ..Script::default() });
|
||||
|
||||
@@ -135,7 +135,7 @@ impl Context {
|
||||
}
|
||||
|
||||
macro_rules! sqlx_pool {
|
||||
($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr $(, $after_init:ident)?) => {
|
||||
($manager:ident, $handle:ident, $options:ty, $connection:ty, $initialize:ident, $unfinished:expr) => {
|
||||
pub struct $manager {
|
||||
options: $options,
|
||||
init: Arc<Vec<String>>,
|
||||
@@ -164,41 +164,28 @@ macro_rules! sqlx_pool {
|
||||
}
|
||||
}
|
||||
|
||||
impl $manager {
|
||||
async fn initialize(&self, mut conn: $connection) -> Result<$handle, sqlx::Error> {
|
||||
let context = Context::new($initialize(&self.options, &mut conn, &self.init).await?);
|
||||
Ok($handle {
|
||||
conn: Some(conn),
|
||||
context,
|
||||
options: self.options.clone(),
|
||||
init: self.init.clone(),
|
||||
timeout: self.timeout,
|
||||
in_transaction: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ManageConnection for $manager {
|
||||
type Connection = $handle;
|
||||
type Error = sqlx::Error;
|
||||
|
||||
async fn connect(&self) -> Result<Self::Connection, Self::Error> {
|
||||
tokio::time::timeout(self.timeout, async {
|
||||
let mut conn = self.options.connect().await?;
|
||||
let context_sql = |value: Option<String>| {
|
||||
value.map(|v| {
|
||||
if $driver == DbDriver::Postgres {
|
||||
format!("SET search_path TO {v}")
|
||||
} else {
|
||||
crate::sql::use_schema($driver, &v).expect("switchable driver")
|
||||
}
|
||||
})
|
||||
};
|
||||
for sql in self.init.iter() {
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut conn).await?;
|
||||
}
|
||||
$(if !self.init.is_empty() {
|
||||
self.options.$after_init(&mut conn).await?;
|
||||
})?
|
||||
let row = sqlx::raw_sql(sqlx::AssertSqlSafe($query.to_owned())).fetch_one(&mut conn).await?;
|
||||
let context = Context::new(context_sql(row.try_get(0)?));
|
||||
Ok($handle {
|
||||
conn: Some(conn),
|
||||
context,
|
||||
options: self.options.clone(),
|
||||
init: self.init.clone(),
|
||||
timeout: self.timeout,
|
||||
in_transaction: false,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|_| sqlx::Error::PoolTimedOut)?
|
||||
tokio::time::timeout(self.timeout, async { self.initialize(self.options.connect().await?).await })
|
||||
.await
|
||||
.map_err(|_| sqlx::Error::PoolTimedOut)?
|
||||
}
|
||||
|
||||
async fn is_valid(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> {
|
||||
@@ -206,16 +193,24 @@ macro_rules! sqlx_pool {
|
||||
}
|
||||
|
||||
fn has_broken(&self, conn: &mut Self::Connection) -> bool {
|
||||
conn.conn.is_none()
|
||||
conn.conn.is_none() || ($unfinished)(conn)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum PgReadOnly {
|
||||
Off,
|
||||
Session,
|
||||
Transaction,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PostgresOptions {
|
||||
connection: PgConnectOptions,
|
||||
read_only: bool,
|
||||
read_only: PgReadOnly,
|
||||
local_settings: Arc<[String]>,
|
||||
}
|
||||
|
||||
const PG_READ_ONLY_HINT: &str = "Read-only requires the pooler to track default_transaction_read_only for each client. \
|
||||
@@ -230,7 +225,7 @@ impl PostgresOptions {
|
||||
}
|
||||
|
||||
async fn verify_read_only(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
|
||||
if self.read_only && !pg_setting_on(conn, "SHOW default_transaction_read_only").await? {
|
||||
if self.read_only == PgReadOnly::Session && !pg_setting_on(conn, "SHOW default_transaction_read_only").await? {
|
||||
return Err(sqlx::Error::Configuration(
|
||||
format!(
|
||||
"PostgreSQL did not enable the requested default_transaction_read_only setting. \
|
||||
@@ -244,7 +239,7 @@ impl PostgresOptions {
|
||||
|
||||
async fn verify_startup_script(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
|
||||
self.verify_read_only(conn).await?;
|
||||
if self.read_only && !pg_setting_on(conn, "SHOW transaction_read_only").await? {
|
||||
if self.read_only == PgReadOnly::Session && !pg_setting_on(conn, "SHOW transaction_read_only").await? {
|
||||
return Err(sqlx::Error::Configuration(
|
||||
"The startup script left a writable transaction open on a read-only PostgreSQL source.".into(),
|
||||
));
|
||||
@@ -285,19 +280,53 @@ fn postgres_connect_error(error: sqlx::Error, read_only: bool) -> IdeError {
|
||||
error
|
||||
}
|
||||
|
||||
sqlx_pool!(
|
||||
PgManager,
|
||||
PgHandle,
|
||||
PostgresOptions,
|
||||
PgConnection,
|
||||
DbDriver::Postgres,
|
||||
"SHOW search_path",
|
||||
verify_startup_script
|
||||
);
|
||||
sqlx_pool!(MysqlManager, MysqlHandle, MySqlConnectOptions, MySqlConnection, DbDriver::Mysql, "SELECT DATABASE()");
|
||||
async fn initialize_postgres(
|
||||
options: &PostgresOptions,
|
||||
conn: &mut PgConnection,
|
||||
init: &[String],
|
||||
) -> Result<Option<String>, sqlx::Error> {
|
||||
let guarded = options.read_only == PgReadOnly::Transaction;
|
||||
if guarded {
|
||||
sqlx::raw_sql(pg_read_only::BEGIN).execute(&mut *conn).await?;
|
||||
}
|
||||
for sql in init {
|
||||
if guarded {
|
||||
pg_read_only::check_single(conn, sql).await?;
|
||||
}
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut *conn).await?;
|
||||
}
|
||||
if !guarded && !init.is_empty() {
|
||||
options.verify_startup_script(conn).await?;
|
||||
}
|
||||
let row = sqlx::raw_sql("SHOW search_path").fetch_one(&mut *conn).await?;
|
||||
let path: Option<String> = row.try_get(0)?;
|
||||
if guarded {
|
||||
sqlx::raw_sql("COMMIT").execute(conn).await?;
|
||||
return Ok(path);
|
||||
}
|
||||
Ok(path.map(|v| format!("SET search_path TO {v}")))
|
||||
}
|
||||
|
||||
async fn initialize_mysql(
|
||||
_: &MySqlConnectOptions,
|
||||
conn: &mut MySqlConnection,
|
||||
init: &[String],
|
||||
) -> Result<Option<String>, sqlx::Error> {
|
||||
for sql in init {
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut *conn).await?;
|
||||
}
|
||||
let row = sqlx::raw_sql("SELECT DATABASE()").fetch_one(conn).await?;
|
||||
Ok(row.try_get::<Option<String>, _>(0)?.and_then(|v| crate::sql::use_schema(DbDriver::Mysql, &v)))
|
||||
}
|
||||
|
||||
sqlx_pool!(PgManager, PgHandle, PostgresOptions, PgConnection, initialize_postgres, |c: &PgHandle| c.options.read_only
|
||||
== PgReadOnly::Transaction
|
||||
&& c.in_transaction);
|
||||
sqlx_pool!(MysqlManager, MysqlHandle, MySqlConnectOptions, MySqlConnection, initialize_mysql, |_: &MysqlHandle| false);
|
||||
|
||||
pub struct ServerPool<M: ManageConnection> {
|
||||
inner: Bb8Pool<M>,
|
||||
transaction_read_only: bool,
|
||||
closed: AtomicBool,
|
||||
}
|
||||
|
||||
@@ -774,7 +803,9 @@ macro_rules! backend_id {
|
||||
}
|
||||
|
||||
mod cursor;
|
||||
mod pg_read_only;
|
||||
pub(crate) use cursor::{Cursors, Key as CursorKey};
|
||||
pub(crate) use pg_read_only::validate as validate_pg_read_only;
|
||||
|
||||
/// Whether the pages of `sql`'s result can be read by a cursor (see [`cursor`]): a query that
|
||||
/// leaves the session as it was.
|
||||
@@ -947,6 +978,10 @@ impl Setup {
|
||||
}
|
||||
|
||||
impl Pool {
|
||||
pub(crate) fn transaction_read_only(&self) -> bool {
|
||||
matches!(self, Pool::Postgres(p) if p.transaction_read_only)
|
||||
}
|
||||
|
||||
pub fn driver(&self) -> DbDriver {
|
||||
match self {
|
||||
Pool::Sqlite(_) => DbDriver::Sqlite,
|
||||
@@ -1058,27 +1093,68 @@ impl Pool {
|
||||
if let Some(p) = password {
|
||||
opts = opts.password(p);
|
||||
}
|
||||
if !setup.params.is_empty() {
|
||||
opts = opts.options(setup.params);
|
||||
}
|
||||
if let Some(n) = setup.statement_cache {
|
||||
opts = opts.statement_cache_capacity(n);
|
||||
}
|
||||
let options = PostgresOptions { connection: opts, read_only: source.read_only };
|
||||
let mut manager = PgManager { options, init: init.clone(), timeout };
|
||||
// Open once directly so authentication failures retain their database error.
|
||||
let first = match manager.connect().await {
|
||||
Err(e) if source.ssl == DbSslMode::Prefer && tls_failed(&e) => {
|
||||
tracing::info!("TLS handshake failed, connecting without TLS (SSL mode Prefer): {e}");
|
||||
manager.options.connection = manager.options.connection.clone().ssl_mode(PgSslMode::Disable);
|
||||
manager.connect().await
|
||||
}
|
||||
first => first,
|
||||
// Remove only the option supplied by the Read-only checkbox on a retry.
|
||||
let fallback = source.read_only.then(|| {
|
||||
let opts = opts.clone().statement_cache_capacity(0);
|
||||
if setup.params.len() == 1 { opts } else { opts.options(setup.params.iter().skip(1).cloned()) }
|
||||
});
|
||||
if !setup.params.is_empty() {
|
||||
opts = opts.options(setup.params);
|
||||
}
|
||||
.map_err(|e| postgres_connect_error(e, source.read_only))?;
|
||||
let mode = if source.read_only { PgReadOnly::Session } else { PgReadOnly::Off };
|
||||
let mut manager = PgManager {
|
||||
options: PostgresOptions { connection: opts, read_only: mode, local_settings: Arc::default() },
|
||||
init: init.clone(),
|
||||
timeout,
|
||||
};
|
||||
let mut fallback = fallback;
|
||||
let mut try_plain = source.ssl == DbSslMode::Prefer;
|
||||
let first = loop {
|
||||
let mut login_failed = false;
|
||||
let result = tokio::time::timeout(timeout, async {
|
||||
let mut conn =
|
||||
manager.options.connection.connect().await.inspect_err(|_| login_failed = true)?;
|
||||
manager.options.verify_read_only(&mut conn).await?;
|
||||
manager.initialize(conn).await
|
||||
})
|
||||
.await
|
||||
.unwrap_or(Err(sqlx::Error::PoolTimedOut));
|
||||
match result {
|
||||
Err(e) if login_failed && try_plain && tls_failed(&e) => {
|
||||
tracing::info!("TLS handshake failed, connecting without TLS (SSL mode Prefer): {e}");
|
||||
try_plain = false;
|
||||
manager.options.connection =
|
||||
manager.options.connection.clone().ssl_mode(PgSslMode::Disable);
|
||||
fallback = fallback.map(|opts| opts.ssl_mode(PgSslMode::Disable));
|
||||
}
|
||||
Err(e)
|
||||
if login_failed
|
||||
&& fallback.is_some()
|
||||
&& e.as_database_error().is_some_and(|db| {
|
||||
postgres_read_only_hint(true, db.code().as_deref(), db.message()).is_some()
|
||||
}) =>
|
||||
{
|
||||
manager.options.connection =
|
||||
fallback.take().expect("read-only startup option was supplied");
|
||||
manager.options.read_only = PgReadOnly::Transaction;
|
||||
try_plain = false;
|
||||
let (startup, settings) = pg_read_only::startup(&init).map_err(IdeError::invalid)?;
|
||||
manager.init = Arc::new(startup);
|
||||
manager.options.local_settings = settings.into();
|
||||
tracing::info!(
|
||||
"PostgreSQL endpoint rejected read-only startup; using read-only transactions"
|
||||
);
|
||||
}
|
||||
result => break result.map_err(|e| postgres_connect_error(e, source.read_only))?,
|
||||
}
|
||||
};
|
||||
let transaction_read_only = manager.options.read_only == PgReadOnly::Transaction;
|
||||
let pool = Bb8Pool::builder().max_size(MAX).connection_timeout(timeout).build_unchecked(manager);
|
||||
let _ = pool.add(first);
|
||||
Ok(Pool::Postgres(ServerPool { inner: pool, closed: AtomicBool::new(false) }))
|
||||
Ok(Pool::Postgres(ServerPool { inner: pool, transaction_read_only, closed: AtomicBool::new(false) }))
|
||||
}
|
||||
DbDriver::Mysql => {
|
||||
let mut opts = MySqlConnectOptions::new()
|
||||
@@ -1139,7 +1215,11 @@ impl Pool {
|
||||
let first = first.map_err(db_err)?;
|
||||
let pool = Bb8Pool::builder().max_size(MAX).connection_timeout(timeout).build_unchecked(manager);
|
||||
let _ = pool.add(first);
|
||||
Ok(Pool::Mysql(ServerPool { inner: pool, closed: AtomicBool::new(false) }))
|
||||
Ok(Pool::Mysql(ServerPool {
|
||||
inner: pool,
|
||||
transaction_read_only: false,
|
||||
closed: AtomicBool::new(false),
|
||||
}))
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
use tiberius::Config;
|
||||
@@ -1204,6 +1284,29 @@ impl Pool {
|
||||
matches!(self, Pool::Sqlite(_) | Pool::Postgres(_) | Pool::Mysql(_))
|
||||
}
|
||||
|
||||
async fn cancel_query(&self, sql: String) {
|
||||
if let Pool::Postgres(p) = self
|
||||
&& p.transaction_read_only
|
||||
{
|
||||
// The target owns its backend until cancellation finishes; all regular pool slots may be busy.
|
||||
let control = async {
|
||||
let mut c = p.inner.dedicated_connection().await.map_err(db_err)?;
|
||||
c.start_read_only().await?;
|
||||
Ok::<_, IdeError>(c)
|
||||
};
|
||||
// Never queue a late cancel after giving up the backend whose PID it names.
|
||||
if let Ok(Ok(mut conn)) = tokio::time::timeout(Duration::from_secs(2), control).await {
|
||||
let _ = sqlx::raw_sql(sqlx::AssertSqlSafe(format!("{sql}; ROLLBACK"))).execute(&mut *conn).await;
|
||||
} else {
|
||||
tracing::debug!(
|
||||
"No PostgreSQL backend available to signal cancellation; discarding the client connection"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
let _ = self.rows(&sql, 1).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// 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>>>> {
|
||||
if let Pool::Jdbc(p) = self {
|
||||
@@ -1217,8 +1320,13 @@ impl Pool {
|
||||
}
|
||||
let mut conn = Held::acquire(self).await?;
|
||||
conn.apply_context(None).await?;
|
||||
let fetched = conn.fetch_rows(sql, max).await;
|
||||
Ok(fetched?.1)
|
||||
let owned = conn.begin_read_only().await?;
|
||||
let result = async {
|
||||
conn.check_protected_statement(sql).await?;
|
||||
conn.fetch_rows(sql, max).await
|
||||
}
|
||||
.await;
|
||||
Ok(conn.finish_read_only(owned, result).await?.1)
|
||||
}
|
||||
|
||||
/// Runs one statement and keeps at most `max_rows` rows. Cancelling stops
|
||||
@@ -1260,6 +1368,9 @@ 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> {
|
||||
if self.transaction_read_only() {
|
||||
return Err(IdeError::invalid("Cannot submit table changes on a read-only PostgreSQL source"));
|
||||
}
|
||||
match self {
|
||||
Pool::Jdbc(_) => Err(IdeError::invalid("Custom JDBC table editing is unsupported")),
|
||||
Pool::Clickhouse(_) => Err(crate::clickhouse::transaction_error()),
|
||||
@@ -1426,6 +1537,15 @@ impl Held {
|
||||
Held::Oracle(_) => DbDriver::Oracle,
|
||||
_ => return Ok(()),
|
||||
};
|
||||
if let Held::Postgres(c) = self
|
||||
&& c.options.read_only == PgReadOnly::Transaction
|
||||
{
|
||||
let wanted = schema
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| crate::sql::quote_ident(driver, s))
|
||||
.or_else(|| c.context.default.clone());
|
||||
return c.select_path(wanted).await;
|
||||
}
|
||||
let context = self.context().expect("switchable connection");
|
||||
let wanted = context.wanted(driver, schema);
|
||||
if context.known && context.current == wanted {
|
||||
@@ -1467,6 +1587,7 @@ impl Held {
|
||||
}
|
||||
|
||||
async fn fetch_rows(&mut self, sql: &str, max: usize) -> IdeResult<Fetched> {
|
||||
self.require_read_only_transaction()?;
|
||||
self.before_statement(sql);
|
||||
let result = match self {
|
||||
Held::Sqlite(c) => fetch!(&mut **c, sql, max, Cells::Text),
|
||||
@@ -1484,6 +1605,31 @@ impl Held {
|
||||
|
||||
/// Runs a statement without results (`BEGIN`, `COMMIT`, `ROLLBACK`).
|
||||
pub async fn command(&mut self, sql: &str) -> IdeResult<()> {
|
||||
let owned = self.begin_read_only().await?;
|
||||
let result = async {
|
||||
self.check_protected_statement(sql).await?;
|
||||
self.run_command(sql).await
|
||||
}
|
||||
.await;
|
||||
self.finish_read_only(owned, result).await
|
||||
}
|
||||
|
||||
pub(crate) async fn begin_manual(&mut self, driver: DbDriver) -> IdeResult<()> {
|
||||
if matches!(self, Self::Postgres(c) if c.options.read_only == PgReadOnly::Transaction) {
|
||||
self.begin_read_only().await?;
|
||||
return Ok(());
|
||||
}
|
||||
self.run_command(begin_statement(driver)).await
|
||||
}
|
||||
|
||||
pub(crate) async fn finish_manual(&mut self, commit: bool) -> IdeResult<()> {
|
||||
if matches!(self, Self::Postgres(c) if c.options.read_only == PgReadOnly::Transaction) {
|
||||
return self.end_read_only(commit).await;
|
||||
}
|
||||
self.run_command(if commit { "COMMIT" } else { "ROLLBACK" }).await
|
||||
}
|
||||
|
||||
async fn run_command(&mut self, sql: &str) -> IdeResult<()> {
|
||||
self.before_statement(sql);
|
||||
let result = self.raw_command(sql).await;
|
||||
if result.is_ok() {
|
||||
@@ -1493,6 +1639,7 @@ impl Held {
|
||||
}
|
||||
|
||||
async fn raw_command(&mut self, sql: &str) -> IdeResult<()> {
|
||||
self.require_read_only_transaction()?;
|
||||
match self {
|
||||
Held::SqlServer(c) => mssql_command(c, sql).await,
|
||||
Held::Clickhouse(_) => Err(crate::clickhouse::transaction_error()),
|
||||
@@ -1575,6 +1722,31 @@ impl Held {
|
||||
if let Held::Snowflake(c, schema) = self {
|
||||
return c.execute_in(schema.as_deref(), sql, skip, max_rows, cancel).await;
|
||||
}
|
||||
let owned = self.begin_read_only().await?;
|
||||
let result = async {
|
||||
self.check_protected_statement(sql).await?;
|
||||
self.run_statement(pool, sql, skip, max_rows, cancel).await
|
||||
}
|
||||
.await;
|
||||
if cancel.is_cancelled()
|
||||
&& let Held::Postgres(c) = self
|
||||
&& c.options.read_only == PgReadOnly::Transaction
|
||||
{
|
||||
c.conn.take();
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
self.finish_read_only(owned, result).await
|
||||
}
|
||||
|
||||
async fn run_statement(
|
||||
&mut self,
|
||||
pool: &Pool,
|
||||
sql: &str,
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
self.require_read_only_transaction()?;
|
||||
self.before_statement(sql);
|
||||
let started = Instant::now();
|
||||
// `$id`: the query naming the server process, `$kill`: how another connection stops it.
|
||||
@@ -1590,7 +1762,7 @@ impl Held {
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
if let Some(b) = backend {
|
||||
let _ = pool.rows(&$kill(b), 1).await;
|
||||
pool.cancel_query($kill(b)).await;
|
||||
}
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
|
||||
@@ -95,6 +95,7 @@ impl Cursors {
|
||||
skip: usize,
|
||||
max: usize,
|
||||
cancel: &CancellationToken,
|
||||
protected: bool,
|
||||
) -> Option<IdeResult<Fetched>> {
|
||||
let (id, reads) = {
|
||||
let mut registry = self.registry.lock();
|
||||
@@ -110,7 +111,7 @@ impl Cursors {
|
||||
self.finish(id, &fetched);
|
||||
Some(Ok(fetched))
|
||||
}
|
||||
Some(Err(e)) if e.kind == ErrorKind::Cancelled => {
|
||||
Some(Err(e)) if protected || e.kind == ErrorKind::Cancelled => {
|
||||
self.close(id);
|
||||
Some(Err(e))
|
||||
}
|
||||
@@ -196,6 +197,19 @@ impl Cursors {
|
||||
/// nobody asks for [`IDLE`], or it is released (its channel closes).
|
||||
async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Receiver<Read>) {
|
||||
let Some(first) = reads.recv().await else { return held.discard().await };
|
||||
let prepare = async {
|
||||
let owned = held.begin_read_only().await?;
|
||||
held.check_protected_statement(&sql).await?;
|
||||
Ok(owned)
|
||||
}
|
||||
.await;
|
||||
let owned = match prepare {
|
||||
Ok(owned) => owned,
|
||||
Err(error) => {
|
||||
let _ = first.reply.send(Err(error));
|
||||
return;
|
||||
}
|
||||
};
|
||||
// `$id`: the query naming the server process, `$kill`: how another connection stops it.
|
||||
// Evaluates to whether the connection can go back to its pool (the stream was read to
|
||||
// its end); otherwise it is closed rather than left to be drained.
|
||||
@@ -217,7 +231,7 @@ async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Re
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
if let Some(b) = backend {
|
||||
let _ = pool.rows(&$kill(b), 1).await;
|
||||
pool.cancel_query($kill(b)).await;
|
||||
}
|
||||
let _ = reply.send(Err(IdeError::cancelled()));
|
||||
break;
|
||||
@@ -236,13 +250,13 @@ async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Re
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = reply.send(Err(e));
|
||||
reusable = true;
|
||||
reusable = !owned;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(stream);
|
||||
if let Some((reply, mut fetched)) = last {
|
||||
if let Some((_, fetched)) = &mut last {
|
||||
if fetched.0.is_empty() && looks_like_query(&sql) {
|
||||
fetched.0 = (&mut **$conn)
|
||||
.prepare(sqlx::AssertSqlSafe(sql.clone()).into_sql_str())
|
||||
@@ -250,12 +264,11 @@ async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Re
|
||||
.map(|s| statement_columns(&s))
|
||||
.unwrap_or_default();
|
||||
}
|
||||
let _ = reply.send(Ok(fetched));
|
||||
}
|
||||
reusable
|
||||
(reusable, last)
|
||||
}};
|
||||
}
|
||||
let reusable = match &mut held {
|
||||
let (reusable, last) = match &mut held {
|
||||
Held::Sqlite(c) => serve!(c, None::<&str>, |_: String| String::new()),
|
||||
Held::Postgres(c) => {
|
||||
serve!(&mut ***c, Some("SELECT pg_backend_pid()"), |b: String| format!("SELECT pg_cancel_backend({b})"))
|
||||
@@ -263,7 +276,9 @@ async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Re
|
||||
Held::Mysql(c) => serve!(&mut ***c, Some("SELECT CONNECTION_ID()"), |b: String| format!("KILL QUERY {b}")),
|
||||
_ => unreachable!("only the sqlx drivers keep cursors"),
|
||||
};
|
||||
if !reusable {
|
||||
if let Some((reply, fetched)) = last {
|
||||
let _ = reply.send(held.finish_read_only(owned, Ok(fetched)).await);
|
||||
} else if !reusable {
|
||||
held.discard().await;
|
||||
}
|
||||
}
|
||||
@@ -452,7 +467,7 @@ mod tests {
|
||||
});
|
||||
let resumed = tokio::spawn({
|
||||
let (cursors, key) = (cursors.clone(), key.clone());
|
||||
async move { cursors.resume(&key, 1, 1, &CancellationToken::new()).await.is_some() }
|
||||
async move { cursors.resume(&key, 1, 1, &CancellationToken::new(), false).await.is_some() }
|
||||
});
|
||||
in_read.notified().await;
|
||||
cursors.release(&key);
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
//! PostgreSQL transaction-pool connections whose endpoint rejects the read-only startup option.
|
||||
|
||||
use super::{Context, Held, PgConnection, PgHandle, PgReadOnly, db_err};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use sqlx::{Executor, SqlSafeStr};
|
||||
|
||||
// Take the first snapshot before user SQL, fixing the transaction characteristics on this backend.
|
||||
pub(super) const BEGIN: &str = "BEGIN READ ONLY; SELECT 1";
|
||||
|
||||
fn leading_word<'a>(input: &mut &'a str) -> &'a str {
|
||||
loop {
|
||||
*input = input.trim_start_matches([' ', '\t', '\r', '\n', '\x0c', '\x0b', ';']);
|
||||
if let Some(comment) = input.strip_prefix("--") {
|
||||
*input = &comment[comment.find(['\r', '\n']).unwrap_or(comment.len())..];
|
||||
} else if let Some(mut comment) = input.strip_prefix("/*") {
|
||||
let mut depth = 1usize;
|
||||
while depth > 0 {
|
||||
let Some(at) = comment.find(['/', '*']) else { return "" };
|
||||
comment = &comment[at..];
|
||||
if let Some(rest) = comment.strip_prefix("/*") {
|
||||
depth += 1;
|
||||
comment = rest;
|
||||
} else if let Some(rest) = comment.strip_prefix("*/") {
|
||||
depth -= 1;
|
||||
comment = rest;
|
||||
} else {
|
||||
comment = &comment[1..];
|
||||
}
|
||||
}
|
||||
*input = comment;
|
||||
} else {
|
||||
let end = input.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$')).unwrap_or(input.len());
|
||||
let (word, rest) = input.split_at(end);
|
||||
*input = rest;
|
||||
return word;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn control(mut sql: &str) -> Option<&'static str> {
|
||||
let first = leading_word(&mut sql);
|
||||
for name in ["BEGIN", "COMMIT", "END", "ROLLBACK", "ABORT"] {
|
||||
if first.eq_ignore_ascii_case(name) {
|
||||
return Some(name);
|
||||
}
|
||||
}
|
||||
let second = leading_word(&mut sql);
|
||||
if second.eq_ignore_ascii_case("TRANSACTION") {
|
||||
return [("START", "START TRANSACTION"), ("PREPARE", "PREPARE TRANSACTION"), ("SET", "SET TRANSACTION")]
|
||||
.into_iter()
|
||||
.find_map(|(verb, name)| first.eq_ignore_ascii_case(verb).then_some(name));
|
||||
}
|
||||
(first.eq_ignore_ascii_case("SET")
|
||||
&& second.eq_ignore_ascii_case("SESSION")
|
||||
&& leading_word(&mut sql).eq_ignore_ascii_case("CHARACTERISTICS"))
|
||||
.then_some("SET SESSION CHARACTERISTICS")
|
||||
}
|
||||
|
||||
pub(crate) fn validate(sql: &str) -> Result<(), String> {
|
||||
if sql.contains('\0') {
|
||||
return Err("PostgreSQL statements cannot contain a null byte".into());
|
||||
}
|
||||
let blocked = control(sql).or_else(|| {
|
||||
sql.contains(';')
|
||||
.then(|| crate::split::split(sql, crate::DbDriver::Postgres))
|
||||
.and_then(|statements| statements.iter().find_map(|s| control(&s.text)))
|
||||
});
|
||||
if let Some(name) = blocked {
|
||||
return Err(format!("{name} is unavailable while OpenIDEA manages the read-only transaction"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A startup SET must follow the client to its next backend without changing the next client's session.
|
||||
pub(super) fn startup(statements: &[String]) -> Result<(Vec<String>, Vec<String>), String> {
|
||||
let mut init = Vec::with_capacity(statements.len());
|
||||
let mut settings = Vec::new();
|
||||
for sql in statements {
|
||||
validate(sql)?;
|
||||
let mut rest = sql.as_str();
|
||||
let verb = leading_word(&mut rest);
|
||||
if verb.eq_ignore_ascii_case("RESET") || verb.eq_ignore_ascii_case("DISCARD") {
|
||||
return Err(format!("{verb} in a startup script cannot be preserved across pooled read-only transactions"));
|
||||
}
|
||||
if verb.eq_ignore_ascii_case("SET") {
|
||||
let after_set = rest;
|
||||
let kind = leading_word(&mut rest);
|
||||
if !kind.eq_ignore_ascii_case("LOCAL") && !kind.eq_ignore_ascii_case("CONSTRAINTS") {
|
||||
let mut after_session = rest;
|
||||
let local = if kind.eq_ignore_ascii_case("SESSION")
|
||||
&& !leading_word(&mut after_session).eq_ignore_ascii_case("AUTHORIZATION")
|
||||
{
|
||||
rest
|
||||
} else {
|
||||
after_set
|
||||
};
|
||||
let sql = format!("SET LOCAL {local}");
|
||||
settings.push(sql.clone());
|
||||
init.push(sql);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
init.push(sql.clone());
|
||||
}
|
||||
Ok((init, settings))
|
||||
}
|
||||
|
||||
// Keep the text result format of raw_sql. For SQL containing a delimiter, PostgreSQL's Parse
|
||||
// validates that the text denotes a single command, including under the server's quoting rules.
|
||||
pub(super) async fn check_single(conn: &mut PgConnection, sql: &str) -> Result<(), sqlx::Error> {
|
||||
if sql.contains(';') {
|
||||
conn.prepare(sqlx::AssertSqlSafe(sql.to_owned()).into_sql_str()).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl PgHandle {
|
||||
pub(super) async fn start_read_only(&mut self) -> IdeResult<()> {
|
||||
self.in_transaction = true;
|
||||
let result = async {
|
||||
sqlx::raw_sql(BEGIN).execute(&mut **self).await.map_err(db_err)?;
|
||||
let settings = self.options.local_settings.clone();
|
||||
for sql in settings.iter() {
|
||||
check_single(self, sql).await.map_err(db_err)?;
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut **self).await.map_err(db_err)?;
|
||||
}
|
||||
self.apply_local_path().await
|
||||
}
|
||||
.await;
|
||||
if result.is_err() {
|
||||
self.conn.take();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn apply_local_path(&mut self) -> IdeResult<()> {
|
||||
if let Some(path) = &self.context.current {
|
||||
let path = path.clone();
|
||||
sqlx::query("SELECT pg_catalog.set_config('search_path', $1, true)")
|
||||
.bind(path)
|
||||
.execute(&mut **self)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn select_path(&mut self, wanted: Option<String>) -> IdeResult<()> {
|
||||
if !self.context.known || self.context.current != wanted {
|
||||
self.context.current = wanted;
|
||||
if self.in_transaction {
|
||||
self.apply_local_path().await?;
|
||||
}
|
||||
self.context.known = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Held {
|
||||
pub(super) fn require_read_only_transaction(&self) -> IdeResult<()> {
|
||||
if matches!(self, Self::Postgres(c) if c.options.read_only == PgReadOnly::Transaction && (!c.in_transaction || c.conn.is_none()))
|
||||
{
|
||||
return Err(IdeError::internal("PostgreSQL read-only transaction has not started"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn guarded_postgres(&mut self) -> Option<&mut PgHandle> {
|
||||
match self {
|
||||
Self::Postgres(c) if c.options.read_only == PgReadOnly::Transaction => Some(c),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true when this operation owns the transaction and must finish it.
|
||||
pub(super) async fn begin_read_only(&mut self) -> IdeResult<bool> {
|
||||
if let Some(c) = self.guarded_postgres()
|
||||
&& !c.in_transaction
|
||||
{
|
||||
c.start_read_only().await?;
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
pub(super) async fn check_protected_statement(&mut self, sql: &str) -> IdeResult<()> {
|
||||
self.require_read_only_transaction()?;
|
||||
if let Some(c) = self.guarded_postgres() {
|
||||
validate(sql).map_err(IdeError::invalid)?;
|
||||
check_single(c, sql).await.map_err(db_err)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn end_read_only(&mut self, commit: bool) -> IdeResult<()> {
|
||||
if let Some(c) = self.guarded_postgres() {
|
||||
if c.conn.is_none() {
|
||||
return Err(IdeError::invalid("The read-only PostgreSQL transaction lost its connection"));
|
||||
}
|
||||
let end = if commit { "COMMIT" } else { "ROLLBACK" };
|
||||
if let Err(error) = sqlx::raw_sql(end).execute(&mut **c).await {
|
||||
c.conn.take();
|
||||
return Err(db_err(error));
|
||||
}
|
||||
c.in_transaction = false;
|
||||
c.context = Context::new(c.context.default.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn finish_read_only<T>(&mut self, owned: bool, result: IdeResult<T>) -> IdeResult<T> {
|
||||
if owned && let Err(error) = self.end_read_only(result.is_ok()).await {
|
||||
return Err(result.err().unwrap_or(error));
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::validate;
|
||||
|
||||
#[test]
|
||||
fn names_transaction_control_and_accepts_quoted_text() {
|
||||
for name in [
|
||||
"BEGIN",
|
||||
"COMMIT",
|
||||
"END",
|
||||
"ROLLBACK",
|
||||
"ABORT",
|
||||
"START TRANSACTION",
|
||||
"PREPARE TRANSACTION",
|
||||
"SET TRANSACTION",
|
||||
"SET SESSION CHARACTERISTICS",
|
||||
] {
|
||||
let statement = name.to_lowercase().replace(' ', " /* note */ ");
|
||||
let sql = format!(" -- preceding comment\n /* outer /* nested */ block */ {statement}");
|
||||
assert!(validate(&sql).unwrap_err().contains(name), "{sql}");
|
||||
}
|
||||
assert!(validate("SELECT 1; COMMIT").unwrap_err().contains("COMMIT"));
|
||||
for sql in
|
||||
["SELECT 'a; COMMIT'", "SELECT $$;ROLLBACK$$", "SELECT 1 /* END */", "SET LOCAL search_path TO public"]
|
||||
{
|
||||
assert!(validate(sql).is_ok(), "{sql}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -178,6 +178,18 @@ pub struct TableDetails {
|
||||
pub triggers: Vec<TriggerInfo>,
|
||||
}
|
||||
|
||||
/// One object privilege on a table: `grantee` may run `privilege` (`SELECT`, …), granted
|
||||
/// by `grantor` (unknown on MySQL), and may grant it on when `grantable`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbTableGrant")]
|
||||
pub struct TableGrant {
|
||||
pub grantee: String,
|
||||
pub grantor: Option<String>,
|
||||
pub privilege: String,
|
||||
pub grantable: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbCompletionColumn")]
|
||||
@@ -394,7 +406,7 @@ pub(crate) fn keep_alive(pool: &Arc<Pool>, every: Duration) {
|
||||
async fn end_session(session: &Session) {
|
||||
let held = session.lock().await.take();
|
||||
if let Some(mut conn) = held
|
||||
&& (conn.command("ROLLBACK").await.is_err() || conn.restore_default().await.is_err())
|
||||
&& (conn.finish_manual(false).await.is_err() || conn.restore_default().await.is_err())
|
||||
{
|
||||
conn.discard().await;
|
||||
}
|
||||
@@ -658,8 +670,7 @@ impl DbManager {
|
||||
let config = self.sources()?.into_iter().find(|s| s.id == id).and_then(|s| s.ssh).map(|s| s.config);
|
||||
if let Some(c) = config.filter(|c| !c.trim().is_empty()) {
|
||||
let save = self.ssh.config(&c).map(|c| c.save_secret).unwrap_or(save);
|
||||
self.ssh.set_secret(&c, secret, save);
|
||||
return Ok(());
|
||||
return self.ssh.set_secret(&c, secret, save);
|
||||
}
|
||||
self.remember(self.saved_for(id), secrets::ssh_key(id), secret, save).await
|
||||
}
|
||||
@@ -760,7 +771,9 @@ impl DbManager {
|
||||
} else {
|
||||
if let Some(s) = ssh_secret {
|
||||
let save = self.ssh.config(config)?.save_secret;
|
||||
self.ssh.set_secret(config, Some(s), save);
|
||||
if let Err(e) = self.ssh.set_secret(config, Some(s), save) {
|
||||
tracing::warn!("could not save the SSH credential: {}", e.message);
|
||||
}
|
||||
}
|
||||
self.ssh.session(config).await?
|
||||
})
|
||||
@@ -836,11 +849,18 @@ impl DbManager {
|
||||
_ => pool.rows(version, 1).await,
|
||||
};
|
||||
pool.close().await;
|
||||
let strict =
|
||||
source.external_tunnel.is_some() || matches!(source.driver, DbDriver::Clickhouse | DbDriver::Snowflake);
|
||||
let strict = pool.transaction_read_only()
|
||||
|| source.external_tunnel.is_some()
|
||||
|| matches!(source.driver, DbDriver::Clickhouse | DbDriver::Snowflake);
|
||||
let rows = if strict { result? } else { result.unwrap_or_default() };
|
||||
let v = rows.into_iter().next().and_then(|r| r.into_iter().next().flatten());
|
||||
Ok(v.unwrap_or_else(|| "Connected".into()))
|
||||
let mut message = v.unwrap_or_else(|| "Connected".into());
|
||||
if pool.transaction_read_only() {
|
||||
message.push_str(
|
||||
"\nRead-only queries use BEGIN READ ONLY because this endpoint rejected the startup setting.",
|
||||
);
|
||||
}
|
||||
Ok(message)
|
||||
}
|
||||
|
||||
/// Runs `job` with the client tool at `executable` against target `id`, connected like the
|
||||
@@ -1156,6 +1176,28 @@ impl DbManager {
|
||||
Ok(TableDetails { columns, indexes, foreign_keys, triggers })
|
||||
}
|
||||
|
||||
/// The object privileges granted on `table`; empty, without a query, on the engines
|
||||
/// [`sql::table_grants`] doesn't cover.
|
||||
pub async fn table_grants(&self, id: &str, schema: &str, table: &str) -> IdeResult<Vec<TableGrant>> {
|
||||
let pool = self.pool(id).await?;
|
||||
let Some(q) = sql::table_grants(pool.driver(), schema, table) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
Ok(pool
|
||||
.rows(&q, MAX_META_ROWS)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
let grantee = it.next().flatten()?;
|
||||
let grantor = it.next().flatten().filter(|g| !g.is_empty());
|
||||
let privilege = it.next().flatten()?.to_ascii_uppercase();
|
||||
let grantable = flag(&it.next().flatten());
|
||||
Some(TableGrant { grantee, grantor, privilege, grantable })
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The routines and sequences of `schema`.
|
||||
pub async fn schema_objects(&self, id: &str, schema: &str) -> IdeResult<SchemaObjects> {
|
||||
let pool = self.pool(id).await?;
|
||||
@@ -1454,6 +1496,22 @@ impl DbManager {
|
||||
self.execute_from(id, statement, 0, max_rows, cancel, None).await
|
||||
}
|
||||
|
||||
/// Refuses transaction control anywhere in a guarded console script before running its first statement.
|
||||
pub async fn validate_script(&self, id: &str, statements: &[split::SqlStatement]) -> IdeResult<()> {
|
||||
if statements.len() > 1
|
||||
&& self.source(id).is_ok_and(|s| s.driver == DbDriver::Postgres && s.read_only)
|
||||
&& self.pool(id).await?.transaction_read_only()
|
||||
{
|
||||
for statement in statements {
|
||||
if let Err(error) = conn::validate_pg_read_only(&statement.text) {
|
||||
self.finish_transaction(id, false).await?;
|
||||
return Err(IdeError::invalid(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`execute`](Self::execute), reading past the first `skip` rows without keeping
|
||||
/// them: a later page of a result, where only that page is decoded and returned.
|
||||
/// `schema` is a query console's active context: the connection that runs the
|
||||
@@ -1589,16 +1647,23 @@ impl DbManager {
|
||||
return p.query_in_schema(statement, skip, max_rows, cancel, schema).await;
|
||||
}
|
||||
let session = self.sessions.lock().get(id).cloned();
|
||||
if !conn::cursor_statement(statement) {
|
||||
let protected = pool.transaction_read_only();
|
||||
let cursor = protected || conn::cursor_statement(statement);
|
||||
if !cursor || (protected && skip == 0 && paging) {
|
||||
// A cursor's open statement could keep this one waiting (a lock), and would show data from before it.
|
||||
self.cursors.release_target(id);
|
||||
}
|
||||
if paging && session.is_none() && skip > 0 && pool.keeps_cursors() && conn::cursor_statement(statement) {
|
||||
if paging && session.is_none() && (skip > 0 || protected) && pool.keeps_cursors() && cursor {
|
||||
let key = conn::CursorKey::new(id, statement, schema);
|
||||
let started = std::time::Instant::now();
|
||||
let page = match self.cursors.resume(&key, skip, max_rows, cancel).await {
|
||||
let page = match self.cursors.resume(&key, skip, max_rows, cancel, protected).await {
|
||||
Some(page) => page,
|
||||
None => {
|
||||
if protected && skip > 0 {
|
||||
return Err(IdeError::invalid(
|
||||
"This read-only result is no longer open at this page. Run the query again.",
|
||||
));
|
||||
}
|
||||
let mut held = Held::acquire(&pool).await?;
|
||||
held.apply_context(schema).await?;
|
||||
self.cursors.start(held, pool.clone(), key, skip, max_rows, cancel).await
|
||||
@@ -1626,10 +1691,32 @@ impl DbManager {
|
||||
return Err(IdeError::invalid("ClickHouse manual transactions are unsupported"));
|
||||
}
|
||||
let mut held = session.lock().await;
|
||||
if pool.transaction_read_only() {
|
||||
// Own the session during awaits so a dropped request cannot return an unfinished transaction.
|
||||
let mut conn = match held.take() {
|
||||
Some(conn) => conn,
|
||||
None => {
|
||||
let mut conn = Held::acquire(&pool).await?;
|
||||
conn.begin_manual(pool.driver()).await?;
|
||||
conn
|
||||
}
|
||||
};
|
||||
let result = async {
|
||||
conn.apply_context(schema).await?;
|
||||
conn.execute_from(&pool, statement, skip, max_rows, cancel).await
|
||||
}
|
||||
.await;
|
||||
if result.is_ok() {
|
||||
*held = Some(conn);
|
||||
} else if cancel.is_cancelled() || conn.finish_manual(false).await.is_err() {
|
||||
conn.discard().await;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if held.is_none() {
|
||||
let mut conn = Held::acquire(&pool).await?;
|
||||
conn.apply_context(schema).await?;
|
||||
conn.command(conn::begin_statement(pool.driver())).await?;
|
||||
conn.begin_manual(pool.driver()).await?;
|
||||
*held = Some(conn);
|
||||
}
|
||||
let conn = held.as_mut().expect("opened above");
|
||||
@@ -1675,7 +1762,7 @@ impl DbManager {
|
||||
let Some(session) = session else { return Ok(()) };
|
||||
let mut held = session.lock().await;
|
||||
let Some(mut conn) = held.take() else { return Ok(()) };
|
||||
if let Err(e) = conn.command(if commit { "COMMIT" } else { "ROLLBACK" }).await {
|
||||
if let Err(e) = conn.finish_manual(commit).await {
|
||||
// Discarding a Snowflake connection doesn't end its session, which the data source's
|
||||
// other targets share: the transaction stays open, so it stays held to be ended again.
|
||||
if matches!(conn, conn::Held::Snowflake(..)) {
|
||||
|
||||
@@ -673,6 +673,28 @@ pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// `grantee, grantor, privilege, grantable` rows of `table`'s object privileges, for the
|
||||
/// engines whose catalog keeps them per table: PostgreSQL's ACL (its implicit owner
|
||||
/// privileges when `relacl` is null) and MySQL's `TABLE_PRIVILEGES` (no grantor). `None`
|
||||
/// for the other engines, which then run no query.
|
||||
pub fn table_grants(driver: DbDriver, schema: &str, table: &str) -> Option<String> {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
match driver {
|
||||
DbDriver::Postgres => Some(format!(
|
||||
"SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END, \
|
||||
pg_get_userbyid(a.grantor), a.privilege_type, CASE WHEN a.is_grantable THEN 'YES' ELSE 'NO' END \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
CROSS JOIN LATERAL aclexplode(coalesce(c.relacl, acldefault('r', c.relowner))) a \
|
||||
WHERE n.nspname = {s} AND c.relname = {t} ORDER BY 1, 2"
|
||||
)),
|
||||
DbDriver::Mysql => Some(format!(
|
||||
"SELECT grantee, NULL, privilege_type, is_grantable FROM information_schema.table_privileges \
|
||||
WHERE table_schema = {s} AND table_name = {t} ORDER BY 1"
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `before`, `insert` of SQLite's `CREATE TRIGGER name BEFORE INSERT ON …` (its catalog keeps only the text).
|
||||
pub fn sqlite_trigger_event(sql: &str) -> (String, String) {
|
||||
let upper = sql.to_ascii_uppercase();
|
||||
|
||||
@@ -322,3 +322,39 @@ async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> Id
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn table_grants_list_table_privileges() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
for stmt in [
|
||||
"DROP DATABASE IF EXISTS oi_grants",
|
||||
"DROP USER IF EXISTS 'oi_grant_reader'@'%', 'oi_grant_writer'@'%'",
|
||||
"CREATE USER 'oi_grant_reader'@'%', 'oi_grant_writer'@'%'",
|
||||
"CREATE DATABASE oi_grants",
|
||||
"CREATE TABLE oi_grants.shared (id INT)",
|
||||
"CREATE TABLE oi_grants.private (id INT)",
|
||||
"GRANT SELECT ON oi_grants.shared TO 'oi_grant_reader'@'%'",
|
||||
"GRANT INSERT, UPDATE ON oi_grants.shared TO 'oi_grant_writer'@'%' WITH GRANT OPTION",
|
||||
] {
|
||||
db.execute("m", stmt, 10, &c).await?;
|
||||
}
|
||||
let grants = db.table_grants("m", "oi_grants", "shared").await?;
|
||||
let mut rows: Vec<_> =
|
||||
grants.iter().map(|g| (g.grantee.as_str(), g.privilege.as_str(), g.grantable, g.grantor.clone())).collect();
|
||||
rows.sort();
|
||||
assert_eq!(
|
||||
rows,
|
||||
[
|
||||
("'oi_grant_reader'@'%'", "SELECT", false, None),
|
||||
("'oi_grant_writer'@'%'", "INSERT", true, None),
|
||||
("'oi_grant_writer'@'%'", "UPDATE", true, None),
|
||||
]
|
||||
);
|
||||
assert!(db.table_grants("m", "oi_grants", "private").await?.is_empty());
|
||||
for stmt in ["DROP DATABASE oi_grants", "DROP USER 'oi_grant_reader'@'%', 'oi_grant_writer'@'%'"] {
|
||||
db.execute("m", stmt, 10, &c).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -5,11 +5,174 @@ use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{DataSource, DbDriver, DbManager};
|
||||
|
||||
fn server() -> Option<(String, u16, String, String)> {
|
||||
let v = std::env::var("OPENIDEA_TEST_POSTGRES").ok()?;
|
||||
endpoint("OPENIDEA_TEST_POSTGRES")
|
||||
}
|
||||
|
||||
fn endpoint(variable: &str) -> Option<(String, u16, String, String)> {
|
||||
let v = std::env::var(variable).ok()?;
|
||||
let mut it = v.splitn(4, ':');
|
||||
Some((it.next()?.into(), it.next()?.parse().ok()?, it.next()?.into(), it.next().unwrap_or("").into()))
|
||||
}
|
||||
|
||||
/// A disposable PgBouncer transaction pool which rejects default_transaction_read_only at startup
|
||||
/// (`OPENIDEA_TEST_PGBOUNCER`, same format). PgBouncer 1.24 rejects it; 1.26 tracks it per client,
|
||||
/// which keeps the startup option in use and fails the fallback assertion below.
|
||||
#[tokio::test]
|
||||
async fn transaction_pooler_runs_read_only_work_on_the_assigned_backend() -> IdeResult<()> {
|
||||
let Some((host, port, user, password)) = endpoint("OPENIDEA_TEST_PGBOUNCER") else { return Ok(()) };
|
||||
let dir = tempfile::tempdir()?;
|
||||
let root = dir.path();
|
||||
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let db = DbManager::new(root.into(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
let mut source = DataSource {
|
||||
id: "ro".into(),
|
||||
name: "Pooler".into(),
|
||||
driver: DbDriver::Postgres,
|
||||
host,
|
||||
port: Some(port),
|
||||
user,
|
||||
read_only: true,
|
||||
..Default::default()
|
||||
};
|
||||
let normal = DataSource { id: "rw".into(), read_only: false, ..source.clone() };
|
||||
source.options.startup_script =
|
||||
"SET search_path = pg_catalog, public; SET statement_timeout = '17s'; SELECT 1".into();
|
||||
db.save_sources(vec![source.clone(), normal]).await?;
|
||||
for id in ["rw", "ro"] {
|
||||
db.set_password(id, Some(password.clone()), false).await?;
|
||||
}
|
||||
let message = db.test(&source, Some(password.clone()), None).await?;
|
||||
assert!(message.contains("PostgreSQL") && message.contains("BEGIN READ ONLY"), "{message}");
|
||||
let c = CancellationToken::new();
|
||||
let table = format!("public.oi_pooler_{}", uuid::Uuid::new_v4().simple());
|
||||
let write = format!("INSERT INTO {table} VALUES (1)");
|
||||
pooler_modes(&db, &table, &write, &c).await?;
|
||||
pooler_rotation(&db, &c).await?;
|
||||
pooler_manual(&db, &write, &c).await?;
|
||||
pooler_paging(&db, &c).await?;
|
||||
pooler_cancellation(&db, &c).await?;
|
||||
source.options.time_zone = "Europe/Paris".into();
|
||||
source.options.startup_script = "SELECT 'read;only'".into();
|
||||
let configured = ide_db::Pool::connect(&source, Some(&password), None).await?;
|
||||
assert_eq!(configured.rows("SHOW TimeZone", 1).await?, [[Some("Europe/Paris".into())]]);
|
||||
configured.close().await;
|
||||
source.options.startup_script = "SELECT 1/0; COMMIT".into();
|
||||
let error = db.test(&source, Some(password), None).await.unwrap_err();
|
||||
assert!(error.message.contains("COMMIT"), "{}", error.message);
|
||||
db.execute("rw", &format!("DROP TABLE {table}"), 1, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pooler_modes(db: &DbManager, table: &str, write: &str, c: &CancellationToken) -> IdeResult<()> {
|
||||
let mode = "SHOW transaction_read_only";
|
||||
assert_eq!(db.execute("ro", mode, 1, c).await?.rows, [[Some("on".into())]]);
|
||||
assert_eq!(db.execute("rw", mode, 1, c).await?.rows, [[Some("off".into())]]);
|
||||
db.execute("rw", &format!("CREATE TABLE {table} (n int)"), 1, c).await?;
|
||||
assert!(db.execute("ro", write, 1, c).await.unwrap_err().message.contains("25006"));
|
||||
assert_eq!(db.pool("ro").await?.rows(mode, 1).await?, [[Some("on".into())]]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pooler_rotation(db: &DbManager, c: &CancellationToken) -> IdeResult<()> {
|
||||
let status = "SELECT pg_backend_pid(), current_setting('transaction_read_only'), current_setting('search_path'), current_setting('statement_timeout')";
|
||||
let pool = db.pool("ro").await?;
|
||||
let mut client = ide_db::Held::acquire(&pool).await?;
|
||||
let first_pid = client.execute(&pool, status, 1, c).await?.rows[0][0].clone();
|
||||
let writable = db.pool("rw").await?;
|
||||
let mut blockers = Vec::new();
|
||||
let mut previous_backend = loop {
|
||||
let mut other = ide_db::Held::acquire(&writable).await?;
|
||||
other.command("BEGIN").await?;
|
||||
let pid = other.execute(&writable, status, 1, c).await?.rows[0][0].clone();
|
||||
if pid == first_pid {
|
||||
break other;
|
||||
}
|
||||
blockers.push(other);
|
||||
assert!(blockers.len() < 4, "the fixture must offer the original backend");
|
||||
};
|
||||
for mut other in blockers {
|
||||
other.command("ROLLBACK").await?;
|
||||
}
|
||||
let rerouted = client.execute(&pool, status, 1, c).await?;
|
||||
assert_ne!(rerouted.rows[0][0], first_pid);
|
||||
assert_eq!(rerouted.rows[0][1..], [Some("on".into()), Some("pg_catalog, public".into()), Some("17s".into())]);
|
||||
let ordinary = previous_backend.execute(&writable, status, 1, c).await?;
|
||||
assert_ne!(ordinary.rows[0][2].as_deref(), Some("pg_catalog, public"));
|
||||
assert_ne!(ordinary.rows[0][3].as_deref(), Some("17s"));
|
||||
previous_backend.command("ROLLBACK").await?;
|
||||
drop(client);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pooler_manual(db: &DbManager, write: &str, c: &CancellationToken) -> IdeResult<()> {
|
||||
let mode = "SHOW transaction_read_only";
|
||||
db.set_manual_commit("ro", true).await?;
|
||||
for commit in [true, false] {
|
||||
assert_eq!(db.execute("ro", mode, 1, c).await?.rows, [[Some("on".into())]]);
|
||||
db.finish_transaction("ro", commit).await?;
|
||||
}
|
||||
db.execute("ro", write, 1, c).await.unwrap_err();
|
||||
assert_eq!(db.execute("ro", mode, 1, c).await?.rows, [[Some("on".into())]]);
|
||||
let timestamp = "SELECT transaction_timestamp()";
|
||||
for batch in [false, true] {
|
||||
let before = db.execute("ro", timestamp, 1, c).await?.rows;
|
||||
let error = if batch {
|
||||
let script = ide_db::split::split("SELECT 1/0; COMMIT", DbDriver::Postgres);
|
||||
db.validate_script("ro", &script).await.unwrap_err()
|
||||
} else {
|
||||
db.execute("ro", "COMMIT", 1, c).await.unwrap_err()
|
||||
};
|
||||
assert!(error.message.contains("COMMIT"), "{}", error.message);
|
||||
assert_ne!(db.execute("ro", timestamp, 1, c).await?.rows, before);
|
||||
}
|
||||
db.set_manual_commit("ro", false).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pooler_paging(db: &DbManager, c: &CancellationToken) -> IdeResult<()> {
|
||||
let query = "SELECT current_setting('transaction_read_only'), pg_backend_pid(), transaction_timestamp(), n FROM generate_series(1, 12) n";
|
||||
let first = db.execute_from("ro", query, 0, 2, c, None).await?;
|
||||
let page = db.execute_from("ro", query, 2, 2, c, None).await?;
|
||||
let next = db.execute_from("ro", query, 4, 2, c, None).await?;
|
||||
assert_eq!(page.rows[0][0].as_deref(), Some("on"));
|
||||
assert_eq!(page.rows[0][..3], first.rows[0][..3]);
|
||||
assert_eq!(next.rows[0][..3], page.rows[0][..3]);
|
||||
assert_eq!(next.rows[0][3].as_deref(), Some("5"));
|
||||
db.release_result("ro", query, None);
|
||||
let expired = db.execute_from("ro", query, 6, 2, c, None).await.unwrap_err();
|
||||
assert!(expired.message.contains("Run the query again"), "{}", expired.message);
|
||||
let chosen = db.execute_from("ro", "SELECT current_schema()", 0, 1, c, Some("public")).await?;
|
||||
assert_eq!(chosen.rows, [[Some("public".into())]]);
|
||||
assert_eq!(db.execute("ro", "SELECT current_schema()", 1, c).await?.rows, [[Some("pg_catalog".into())]]);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pooler_cancellation(db: &DbManager, c: &CancellationToken) -> IdeResult<()> {
|
||||
let writable = db.pool("rw").await?;
|
||||
let mode = "SHOW transaction_read_only";
|
||||
let stop = CancellationToken::new();
|
||||
let slow = "SELECT pg_sleep(10) AS oi_pooler_cancel";
|
||||
let (outcome, observed) = tokio::join!(db.execute("ro", slow, 1, &stop), async {
|
||||
for _ in 0..40 {
|
||||
let live = writable.rows("SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND query = 'SELECT pg_sleep(10) AS oi_pooler_cancel'", 1).await.unwrap();
|
||||
if live[0][0].as_deref() == Some("1") {
|
||||
stop.cancel();
|
||||
return true;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
stop.cancel();
|
||||
false
|
||||
});
|
||||
assert!(observed, "the slow statement reached PostgreSQL before cancellation");
|
||||
assert_eq!(outcome.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert_eq!(db.execute("ro", mode, 1, c).await?.rows, [[Some("on".into())]]);
|
||||
let active = writable.rows("SELECT count(*) FROM pg_stat_activity WHERE state <> 'idle' AND query = 'SELECT pg_sleep(10) AS oi_pooler_cancel'", 1).await?;
|
||||
assert_eq!(active, [[Some("0".into())]]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn manager(tmp: &tempfile::TempDir) -> Option<DbManager> {
|
||||
let (host, port, user, password) = server()?;
|
||||
let root = tmp.path().to_path_buf();
|
||||
@@ -572,3 +735,47 @@ async fn external_startup_does_not_block_another_source_and_disconnect_cancels_i
|
||||
assert!(matches!(result, Err(error) if error.kind == ide_core::error::ErrorKind::Cancelled));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn table_grants_expand_the_acl_per_grantee() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
for stmt in [
|
||||
"DROP SCHEMA IF EXISTS oi_grants CASCADE",
|
||||
"DROP ROLE IF EXISTS oi_grant_reader",
|
||||
"DROP ROLE IF EXISTS oi_grant_writer",
|
||||
"CREATE ROLE oi_grant_reader",
|
||||
"CREATE ROLE oi_grant_writer",
|
||||
"CREATE SCHEMA oi_grants",
|
||||
"CREATE TABLE oi_grants.shared (id INT)",
|
||||
"CREATE TABLE oi_grants.private (id INT)",
|
||||
"GRANT SELECT ON oi_grants.shared TO oi_grant_reader, PUBLIC",
|
||||
"GRANT INSERT, UPDATE ON oi_grants.shared TO oi_grant_writer WITH GRANT OPTION",
|
||||
] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
}
|
||||
let owner = db.execute("p", "SELECT current_user", 1, &c).await?.rows[0][0].clone().unwrap();
|
||||
let grants = db.table_grants("p", "oi_grants", "shared").await?;
|
||||
let of = |grantee: &str| {
|
||||
let mut v: Vec<_> = grants
|
||||
.iter()
|
||||
.filter(|g| g.grantee == grantee)
|
||||
.map(|g| (g.privilege.as_str(), g.grantable, g.grantor.as_deref() == Some(owner.as_str())))
|
||||
.collect();
|
||||
v.sort();
|
||||
v
|
||||
};
|
||||
assert_eq!(of("oi_grant_reader"), [("SELECT", false, true)], "{grants:?}");
|
||||
assert_eq!(of("PUBLIC"), [("SELECT", false, true)], "{grants:?}");
|
||||
assert_eq!(of("oi_grant_writer"), [("INSERT", true, true), ("UPDATE", true, true)], "{grants:?}");
|
||||
assert!(of(&owner).contains(&("TRUNCATE", false, true)), "{grants:?}");
|
||||
// No ACL yet: the owner's implicit privileges.
|
||||
let private = db.table_grants("p", "oi_grants", "private").await?;
|
||||
assert!(private.iter().all(|g| g.grantee == owner), "{private:?}");
|
||||
assert!(private.iter().any(|g| g.privilege == "SELECT"), "{private:?}");
|
||||
for stmt in ["DROP SCHEMA oi_grants CASCADE", "DROP ROLE oi_grant_reader", "DROP ROLE oi_grant_writer"] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MANIFEST_FILE: &str = "plugin.toml";
|
||||
/// The plugin API (engine) version this host implements.
|
||||
pub const ENGINE_VERSION: &str = "1.16.0";
|
||||
pub const ENGINE_VERSION: &str = "1.17.0";
|
||||
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
|
||||
pub const LEGACY_API: &str = "0.1";
|
||||
/// Marketplace categories, in the order they are shown.
|
||||
|
||||
@@ -27,17 +27,21 @@ pub fn data_dir(identifier: &str) -> Result<PathBuf, String> {
|
||||
}
|
||||
|
||||
/// `$OPENIDEA_LOG_DIR/<identifier>` when set, else `~/Library/Logs/<identifier>` on macOS and
|
||||
/// `<local data>/<identifier>/logs` elsewhere (Tauri's `app_log_dir`).
|
||||
/// `logs` in the local data directory elsewhere (Tauri's `app_log_dir`), so a custom location
|
||||
/// from Settings › System Settings › Caches moves the logs too.
|
||||
pub fn log_dir(identifier: &str) -> Result<PathBuf, String> {
|
||||
let os = if cfg!(target_os = "macos") {
|
||||
dirs::home_dir().map(|home| home.join("Library/Logs").join(identifier))
|
||||
} else {
|
||||
dirs::data_local_dir().map(|dir| dir.join(identifier).join("logs"))
|
||||
};
|
||||
match std::env::var_os(LOG_ENV).filter(|v| !v.is_empty()) {
|
||||
Some(var) => resolve_env(LOG_ENV, Some(var), None, identifier),
|
||||
None => os.ok_or_else(|| "cannot find the log directory".into()),
|
||||
if let Some(var) = std::env::var_os(LOG_ENV).filter(|v| !v.is_empty()) {
|
||||
return resolve_env(LOG_ENV, Some(var), None, identifier);
|
||||
}
|
||||
if cfg!(target_os = "macos") {
|
||||
return dirs::home_dir()
|
||||
.map(|home| home.join("Library/Logs").join(identifier))
|
||||
.ok_or_else(|| "cannot find the log directory".into());
|
||||
}
|
||||
startup_local_data_dir(identifier)
|
||||
.or_else(|_| local_data_dir(identifier))
|
||||
.map(|dir| dir.join("logs"))
|
||||
.map_err(|_| "cannot find the log directory".into())
|
||||
}
|
||||
|
||||
/// The directory under `$<env>` when set (absolute, not created here), else under the OS directory.
|
||||
@@ -217,6 +221,74 @@ fn apply_custom_migration_in(path: &Path, local: &Path) {
|
||||
}
|
||||
}
|
||||
|
||||
/// WebView2's profile (localStorage, IndexedDB, cookies) inside the directory the windows
|
||||
/// are given, which on Windows is the local data directory.
|
||||
pub const WEBVIEW_PROFILE: &str = "EBWebView";
|
||||
|
||||
/// Browser caches in a WebView2 profile: rebuilt on demand, so not copied across volumes.
|
||||
const WEBVIEW_CACHES: [&str; 6] = ["Cache", "Code Cache", "GPUCache", "DawnCache", "GrShaderCache", "ShaderCache"];
|
||||
|
||||
/// Brings WebView2's profile into `local` before the first window opens: from a scheduled
|
||||
/// move's source (Settings › System Settings › Caches), else from the default directory, where
|
||||
/// windows kept it before they followed a custom location. Runs synchronously, as a window
|
||||
/// started meanwhile would create an empty profile; a profile already in `local` is never
|
||||
/// merged into or replaced, and a failed move leaves the old one in place.
|
||||
pub fn adopt_webview_profile(identifier: &str, local: &Path) {
|
||||
let scheduled = migration_path(identifier)
|
||||
.and_then(|path| fs::read(path).ok())
|
||||
.and_then(|bytes| serde_json::from_slice::<CustomMigration>(&bytes).ok())
|
||||
.filter(|job| job.to == local)
|
||||
.map(|job| job.from);
|
||||
adopt_webview_profile_from(scheduled.into_iter().chain(local_data_dir(identifier).ok()), local);
|
||||
}
|
||||
|
||||
fn adopt_webview_profile_from(sources: impl IntoIterator<Item = PathBuf>, local: &Path) {
|
||||
let target = local.join(WEBVIEW_PROFILE);
|
||||
if target.try_exists().unwrap_or(true) {
|
||||
return;
|
||||
}
|
||||
let Some(source) = sources
|
||||
.into_iter()
|
||||
.filter(|dir| dir != local)
|
||||
.map(|dir| dir.join(WEBVIEW_PROFILE))
|
||||
.find(|profile| fs::symlink_metadata(profile).is_ok_and(|m| m.is_dir()))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let result = fs::create_dir_all(local).and_then(|()| match rename_missing(&source, &target) {
|
||||
Err(error) if rename_failure(&error) == RenameFailure::Copy => {
|
||||
let staging = local.join(format!(".migration-{}", uuid::Uuid::new_v4()));
|
||||
let copied = copy_profile(&source, &staging).and_then(|()| rename_missing(&staging, &target));
|
||||
if staging.exists() {
|
||||
let _ = remove_entry(&staging);
|
||||
}
|
||||
copied.and_then(|()| remove_entry(&source))
|
||||
}
|
||||
other => other,
|
||||
});
|
||||
match result {
|
||||
Ok(()) => tracing::info!(?source, ?target, "moved the WebView profile to the local data directory"),
|
||||
Err(error) => tracing::warn!(?source, ?target, %error, "cannot move the WebView profile; starting a new one"),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`copy_tree`] without the profile's browser caches.
|
||||
fn copy_profile(source: &Path, target: &Path) -> io::Result<()> {
|
||||
let metadata = fs::symlink_metadata(source)?;
|
||||
if !metadata.is_dir() {
|
||||
return copy_tree(source, target);
|
||||
}
|
||||
fs::create_dir(target)?;
|
||||
for entry in fs::read_dir(source)? {
|
||||
let entry = entry?;
|
||||
if WEBVIEW_CACHES.iter().any(|name| entry.file_name() == *name) {
|
||||
continue;
|
||||
}
|
||||
copy_profile(&entry.path(), &target.join(entry.file_name()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Entries of a local-data tree that move to a newly chosen directory.
|
||||
/// Non-relocatable tool installs (virtual environments with absolute interpreter
|
||||
/// paths) stay behind and are reinstalled on demand, as in `migrate_entries`;
|
||||
@@ -552,6 +624,46 @@ fn relative_wrapper(text: &str, source: &Path) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_webview_profile_moves_into_a_custom_local_directory_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (default, custom) = (tmp.path().join("default"), tmp.path().join("custom"));
|
||||
let storage = default.join(WEBVIEW_PROFILE).join("Default/Local Storage");
|
||||
fs::create_dir_all(&storage).unwrap();
|
||||
fs::write(storage.join("leveldb"), "history").unwrap();
|
||||
adopt_webview_profile_from([default.clone()], &custom);
|
||||
let moved = custom.join(WEBVIEW_PROFILE).join("Default/Local Storage/leveldb");
|
||||
assert_eq!(fs::read_to_string(&moved).unwrap(), "history");
|
||||
assert!(!default.join(WEBVIEW_PROFILE).exists());
|
||||
// A profile already in place is never replaced by an older one.
|
||||
fs::create_dir_all(default.join(WEBVIEW_PROFILE)).unwrap();
|
||||
adopt_webview_profile_from([default.clone()], &custom);
|
||||
assert!(default.join(WEBVIEW_PROFILE).exists());
|
||||
assert_eq!(fs::read_to_string(&moved).unwrap(), "history");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_directory_keeps_its_own_profile() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let profile = tmp.path().join(WEBVIEW_PROFILE);
|
||||
fs::create_dir_all(&profile).unwrap();
|
||||
adopt_webview_profile_from([tmp.path().to_path_buf()], tmp.path());
|
||||
assert!(profile.is_dir());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copied_profile_leaves_the_browser_caches_behind() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let source = tmp.path().join("source");
|
||||
fs::create_dir_all(source.join("Default/Cache/Cache_Data")).unwrap();
|
||||
fs::create_dir_all(source.join("Default/IndexedDB")).unwrap();
|
||||
fs::write(source.join("Default/Cache/Cache_Data/f_1"), "x").unwrap();
|
||||
fs::write(source.join("Default/IndexedDB/db"), "kept").unwrap();
|
||||
copy_profile(&source, &tmp.path().join("copy")).unwrap();
|
||||
assert_eq!(fs::read_to_string(tmp.path().join("copy/Default/IndexedDB/db")).unwrap(), "kept");
|
||||
assert!(!tmp.path().join("copy/Default/Cache").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_data_and_log_dirs_follow_the_os_unless_their_variable_is_set() {
|
||||
let os = Some(PathBuf::from("/os"));
|
||||
|
||||
@@ -283,6 +283,47 @@ fn minimal_edits(text: &str, edits: Vec<TextEdit>) -> Vec<TextEdit> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The edits on the lines of `range`. Some servers (Intelephense, #6055) answer a range request
|
||||
/// with edits across the whole file; Reformat Code with a selection changes only the selected
|
||||
/// lines. An edit that reaches past them and keeps its line count is split into one per line.
|
||||
fn within_lines(text: &str, edits: Vec<TextEdit>, range: Range) -> Vec<TextEdit> {
|
||||
let from = Pos::new(range.start.line, 0);
|
||||
// A selection ending at a line start leaves that line out.
|
||||
let to = if range.end.col == 0 && range.end.line > range.start.line {
|
||||
range.end
|
||||
} else {
|
||||
Pos::new(range.end.line + 1, 0)
|
||||
};
|
||||
let doc = ide_text::Document::new(text);
|
||||
edits
|
||||
.into_iter()
|
||||
.flat_map(|e| if e.range.start >= from && e.range.end <= to { vec![e] } else { per_line(&doc, e) })
|
||||
.filter(|e| e.range.start >= from && e.range.end <= to)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `edit` as one edit per line when it replaces as many lines as it inserts, else nothing.
|
||||
fn per_line(doc: &ide_text::Document, edit: TextEdit) -> Vec<TextEdit> {
|
||||
let Range { start, end } = edit.range;
|
||||
let lines: Vec<&str> = edit.new_text.split('\n').collect();
|
||||
if lines.len() as u32 != end.line - start.line + 1 {
|
||||
return Vec::new();
|
||||
}
|
||||
let width = |line: u32| doc.line(line).map_or(0, |l| l.encode_utf16().count() as u32);
|
||||
lines
|
||||
.into_iter()
|
||||
.zip(start.line..=end.line)
|
||||
.map(|(new_text, line)| TextEdit {
|
||||
range: Range::new(
|
||||
Pos::new(line, if line == start.line { start.col } else { 0 }),
|
||||
Pos::new(line, if line == end.line { end.col } else { width(line) }),
|
||||
),
|
||||
new_text: new_text.to_owned(),
|
||||
})
|
||||
.filter(|e| doc.slice(doc.pos_to_offset(e.range.start), doc.pos_to_offset(e.range.end)) != e.new_text)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub async fn format(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -514,9 +555,15 @@ async fn provider_edits(
|
||||
None => project.lsp.format_text(&snap.path, &snap.language, &snap.text, options).await?,
|
||||
};
|
||||
let text = snap.text;
|
||||
return tokio::task::spawn_blocking(move || Some(minimal_edits(&text, edits)))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()));
|
||||
return tokio::task::spawn_blocking(move || {
|
||||
let edits = minimal_edits(&text, edits);
|
||||
Some(match range {
|
||||
Some(range) => within_lines(&text, edits, range),
|
||||
None => edits,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()));
|
||||
};
|
||||
let tool_settings = settings.languages.formatter(selected);
|
||||
// Black takes over from the language server in its projects, so Format on save runs it too.
|
||||
@@ -1050,6 +1097,26 @@ mod tests {
|
||||
|
||||
const ALIGN: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: true };
|
||||
|
||||
#[test]
|
||||
fn range_formatting_changes_only_the_selected_lines() {
|
||||
// Intelephense answers a range request for lines 2-3 with edits across the file (#6055).
|
||||
let text = "<?php\nf(\"a\");\n$x = 1;\n$y = 2;\nf(\"b\");\n";
|
||||
let formatted = "<?php\nf('a');\n$x = 1;\n$y = 2;\nf('b');\n";
|
||||
let whole = vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(5, 0)), new_text: formatted.into() }];
|
||||
let edits = minimal_edits(text, whole);
|
||||
let selected = Range::new(Pos::new(2, 0), Pos::new(3, 8));
|
||||
assert_eq!(
|
||||
after(text, &within_lines(text, edits.clone(), selected)),
|
||||
"<?php\nf(\"a\");\n$x = 1;\n$y = 2;\nf(\"b\");\n"
|
||||
);
|
||||
// Selected up to the start of line 4: line 4 stays as it is.
|
||||
let to_line_start = Range::new(Pos::new(2, 3), Pos::new(3, 0));
|
||||
assert_eq!(
|
||||
after(text, &within_lines(text, edits, to_line_start)),
|
||||
"<?php\nf(\"a\");\n$x = 1;\n$y = 2;\nf(\"b\");\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_file_edit_becomes_one_edit_per_changed_region() {
|
||||
let text = "a\n b\nc\nd\n e\n";
|
||||
|
||||
@@ -118,6 +118,8 @@ pub struct Host {
|
||||
pub(crate) heap_windows: Mutex<HashMap<ide_heap::HeapSnapshotId, String>>,
|
||||
pub(crate) heap_requests: ops::heap::HeapRequests,
|
||||
pub(crate) rebase_editors: Arc<ops::vcs::RebaseEditors>,
|
||||
/// The IDE's Java build: resident javac processes shared by every window's launches.
|
||||
pub(crate) java_build: Arc<ide_build::jbuild::JavaBuildService>,
|
||||
/// SSH connections of Settings › SSH Configurations.
|
||||
pub ssh: Arc<ide_ssh::SshManager>,
|
||||
/// SFTP deployment, remote file editing and runs on run targets.
|
||||
@@ -144,11 +146,31 @@ pub struct Host {
|
||||
requests: requests::Requests,
|
||||
project_requests: RwLock<HashMap<String, Vec<RequestId>>>,
|
||||
/// Shutdowns of projects closed with [`Host::close_project_detached`].
|
||||
closing: parking_lot::Mutex<Vec<std::thread::JoinHandle<()>>>,
|
||||
closing: parking_lot::Mutex<Vec<DetachedClose>>,
|
||||
/// One open at a time per window (see [`Host::opening`]).
|
||||
open_locks: parking_lot::Mutex<HashMap<String, Arc<parking_lot::Mutex<()>>>>,
|
||||
}
|
||||
|
||||
struct DetachedClose {
|
||||
root: Option<std::path::PathBuf>,
|
||||
handle: std::thread::JoinHandle<()>,
|
||||
}
|
||||
|
||||
struct ShutdownWork {
|
||||
notebooks: Vec<Arc<notebook::NotebookService>>,
|
||||
bridges: Vec<Arc<kotlin_bridge::KotlinBridge>>,
|
||||
lsp: Option<Arc<ide_lsp::LspManager>>,
|
||||
debug: Option<(Arc<ide_dap::DebugManager>, String, Option<std::path::PathBuf>)>,
|
||||
agents: Vec<Arc<ide_agent::AgentManager>>,
|
||||
terminals: Option<ide_terminal::DetachedTerminals>,
|
||||
processes: Option<ide_run::DetachedProcessKills>,
|
||||
retired: Option<Arc<Project>>,
|
||||
}
|
||||
|
||||
fn roots_overlap(a: &std::path::Path, b: &std::path::Path) -> bool {
|
||||
a == b || a.starts_with(b) || b.starts_with(a)
|
||||
}
|
||||
|
||||
/// How long exit waits for project shutdown before giving up.
|
||||
const EXIT_SHUTDOWN_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
|
||||
@@ -190,6 +212,8 @@ impl Host {
|
||||
let sink_for: SinkFactory = diagnostics_store::recording_sink_factory(diagnostics.clone(), sink_for);
|
||||
let global_settings = SettingsStore::load(&config_dir, None);
|
||||
let ssh = Arc::new(ide_ssh::SshManager::new(data_dir.join("ssh-passwords.json")));
|
||||
let migration = ssh.clone();
|
||||
runtime.spawn_blocking(move || migration.start_password_migration());
|
||||
ssh.set_configs(global_settings.effective().ssh.configs);
|
||||
let host = Self {
|
||||
plugin_host: RwLock::default(),
|
||||
@@ -225,6 +249,7 @@ impl Host {
|
||||
heap_windows: Mutex::default(),
|
||||
heap_requests: Default::default(),
|
||||
rebase_editors: Default::default(),
|
||||
java_build: Default::default(),
|
||||
languages,
|
||||
syntax,
|
||||
config_dir,
|
||||
@@ -331,7 +356,7 @@ impl Host {
|
||||
/// [`Self::close_project_detached`] there.
|
||||
pub fn close_project(&self, window: &str) {
|
||||
if let Some(shutdown) = self.begin_close(window) {
|
||||
self.wait_blocking(shutdown);
|
||||
self.wait_blocking(shutdown.handle);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -341,15 +366,15 @@ impl Host {
|
||||
pub fn close_project_detached(&self, window: &str) {
|
||||
if let Some(shutdown) = self.begin_close(window) {
|
||||
let mut closing = self.closing.lock();
|
||||
closing.retain(|handle| !handle.is_finished());
|
||||
closing.retain(|entry| !entry.handle.is_finished());
|
||||
closing.push(shutdown);
|
||||
}
|
||||
}
|
||||
|
||||
/// Detaches the project from `window` and stops what it started, synchronously,
|
||||
/// so the window can open another project at once. Returns the thread that
|
||||
/// finishes shutting down its workers.
|
||||
fn begin_close(&self, window: &str) -> Option<std::thread::JoinHandle<()>> {
|
||||
/// Detaches the project from `window` synchronously so the caller (including the UI
|
||||
/// event-loop thread) never blocks on disk I/O or process shutdown, and returns the
|
||||
/// background handle that stops its workers, agents, terminals and processes.
|
||||
fn begin_close(&self, window: &str) -> Option<DetachedClose> {
|
||||
self.mcp_reports.forget_window(window);
|
||||
self.mcp_requests.forget_window(window);
|
||||
self.mcp_agent_runs.forget_window(window);
|
||||
@@ -396,78 +421,115 @@ impl Host {
|
||||
phpstan.stop();
|
||||
}
|
||||
project.documents.clear_workspace_edit_history();
|
||||
project.agents.shutdown();
|
||||
project.agents.detach_sinks();
|
||||
project.flutter.stop();
|
||||
project.devtools.stop();
|
||||
project.widget_preview.stop();
|
||||
project.notebooks.stop_admission();
|
||||
// What the closing window started goes with it — the builds and searches it
|
||||
// asked for, its runs, its shells and its debug sessions — and its language
|
||||
// servers shut down.
|
||||
self.processes.kill_project(&project.root);
|
||||
self.terminals.kill_key(self.owner_window(window));
|
||||
Some(self.spawn_project_shutdown(
|
||||
vec![project.notebooks.clone()],
|
||||
project.kotlin_bridge.iter().cloned().collect(),
|
||||
Some(project.lsp.clone()),
|
||||
// Detach runs and terminals synchronously so a new project opened in the same window
|
||||
// never collides with them, then terminate them and shut down agents on the background thread.
|
||||
let processes = self.processes.detach_project_kills(&project.root);
|
||||
let terminals = self.terminals.detach_key(self.owner_window(window));
|
||||
let root = (!project.light).then(|| project.root.clone());
|
||||
let handle = self.spawn_project_shutdown(ShutdownWork {
|
||||
notebooks: vec![project.notebooks.clone()],
|
||||
bridges: project.kotlin_bridge.iter().cloned().collect(),
|
||||
lsp: Some(project.lsp.clone()),
|
||||
// Debug sessions under the root belong to windows: a project served without one starts none.
|
||||
Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
|
||||
Some(project),
|
||||
))
|
||||
debug: Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
|
||||
agents: vec![project.agents.clone()],
|
||||
terminals: Some(terminals),
|
||||
processes: Some(processes),
|
||||
retired: Some(project),
|
||||
});
|
||||
Some(DetachedClose { root, handle })
|
||||
}
|
||||
|
||||
/// Project/window destruction must finish owned kernel cleanup, not enqueue
|
||||
/// Project/window destruction must finish owned kernel and agent cleanup, not enqueue
|
||||
/// work which can be lost as the desktop runtime exits: the returned thread is
|
||||
/// joined by the closer or, for a detached close, before exit.
|
||||
fn spawn_project_shutdown(
|
||||
&self,
|
||||
notebooks: Vec<Arc<notebook::NotebookService>>,
|
||||
bridges: Vec<Arc<kotlin_bridge::KotlinBridge>>,
|
||||
lsp: Option<Arc<ide_lsp::LspManager>>,
|
||||
debug: Option<(Arc<ide_dap::DebugManager>, String, Option<std::path::PathBuf>)>,
|
||||
retired: Option<Arc<Project>>,
|
||||
) -> std::thread::JoinHandle<()> {
|
||||
for bridge in &bridges {
|
||||
fn spawn_project_shutdown(&self, work: ShutdownWork) -> std::thread::JoinHandle<()> {
|
||||
for bridge in &work.bridges {
|
||||
bridge.stop();
|
||||
}
|
||||
for service in ¬ebooks {
|
||||
for service in &work.notebooks {
|
||||
service.stop_admission();
|
||||
}
|
||||
let runtime = self.runtime.clone();
|
||||
std::thread::spawn(move || {
|
||||
if let Some(processes) = work.processes {
|
||||
processes.kill();
|
||||
}
|
||||
if let Some(terminals) = work.terminals {
|
||||
terminals.terminate();
|
||||
}
|
||||
let agents = (!work.agents.is_empty()).then(|| {
|
||||
let agents = work.agents;
|
||||
std::thread::spawn(move || {
|
||||
for manager in agents {
|
||||
manager.shutdown();
|
||||
}
|
||||
})
|
||||
});
|
||||
// Dropping the project stops its file watcher and index worker, which first finish the
|
||||
// batch they are applying (many file events while a build writes its output), so it
|
||||
// isn't done on the closing caller's thread (the UI thread for a window close).
|
||||
let retired = retired.map(|project| std::thread::spawn(move || drop(project)));
|
||||
let retired = work.retired.map(|project| std::thread::spawn(move || drop(project)));
|
||||
runtime.block_on(async move {
|
||||
for bridge in bridges {
|
||||
for bridge in work.bridges {
|
||||
bridge.shutdown().await;
|
||||
}
|
||||
for service in notebooks {
|
||||
for service in work.notebooks {
|
||||
service.shutdown().await;
|
||||
}
|
||||
if let Some(lsp) = lsp {
|
||||
if let Some(lsp) = work.lsp {
|
||||
lsp.shutdown_all().await;
|
||||
}
|
||||
if let Some((debug, key, root)) = debug {
|
||||
if let Some((debug, key, root)) = work.debug {
|
||||
debug.stop_key(&key).await;
|
||||
if let Some(root) = root {
|
||||
debug.stop_under(&root).await;
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(agents) = agents {
|
||||
let _ = agents.join();
|
||||
}
|
||||
if let Some(retired) = retired {
|
||||
let _ = retired.join();
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Waits for detached closes, so a project opened next never races the
|
||||
/// language servers of one still shutting down (e.g. over a shared workspace).
|
||||
/// Waits for every detached close to finish.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn wait_detached_closes(&self) {
|
||||
let pending: Vec<_> = self.closing.lock().drain(..).collect();
|
||||
for shutdown in pending {
|
||||
self.wait_blocking(shutdown);
|
||||
self.wait_blocking(shutdown.handle);
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits only for detached closes whose root overlaps `root`, so opening an unrelated project
|
||||
/// never blocks on another project's background shutdown.
|
||||
pub(crate) fn wait_detached_closes_for(&self, root: &std::path::Path) {
|
||||
let matching = {
|
||||
let mut closing = self.closing.lock();
|
||||
closing.retain(|entry| !entry.handle.is_finished());
|
||||
let mut wait = Vec::new();
|
||||
let mut keep = Vec::new();
|
||||
for entry in closing.drain(..) {
|
||||
if entry.root.as_deref().is_some_and(|other| roots_overlap(other, root)) {
|
||||
wait.push(entry.handle);
|
||||
} else {
|
||||
keep.push(entry);
|
||||
}
|
||||
}
|
||||
*closing = keep;
|
||||
wait
|
||||
};
|
||||
for handle in matching {
|
||||
self.wait_blocking(handle);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -493,18 +555,23 @@ impl Host {
|
||||
|
||||
/// Called before the desktop runtime exits, including update/restart exits, on
|
||||
/// the event-loop thread: waits for detached closes and the open projects'
|
||||
/// kernels, but no longer than [`EXIT_SHUTDOWN_WAIT`], so a runtime worker
|
||||
/// kernels and agents, but no longer than [`EXIT_SHUTDOWN_WAIT`], so a runtime worker
|
||||
/// stuck on the event loop cannot keep the process from exiting.
|
||||
pub fn shutdown_notebooks_on_exit(&self) {
|
||||
let projects = self.projects();
|
||||
let mut pending: Vec<_> = self.closing.lock().drain(..).collect();
|
||||
pending.push(self.spawn_project_shutdown(
|
||||
projects.iter().map(|project| project.notebooks.clone()).collect(),
|
||||
projects.iter().filter_map(|project| project.kotlin_bridge.clone()).collect(),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
));
|
||||
let mut pending: Vec<_> = self.closing.lock().drain(..).map(|entry| entry.handle).collect();
|
||||
if !projects.is_empty() {
|
||||
pending.push(self.spawn_project_shutdown(ShutdownWork {
|
||||
notebooks: projects.iter().map(|project| project.notebooks.clone()).collect(),
|
||||
bridges: projects.iter().filter_map(|project| project.kotlin_bridge.clone()).collect(),
|
||||
lsp: None,
|
||||
debug: None,
|
||||
agents: projects.iter().map(|project| project.agents.clone()).collect(),
|
||||
terminals: None,
|
||||
processes: None,
|
||||
retired: None,
|
||||
}));
|
||||
}
|
||||
let deadline = std::time::Instant::now() + EXIT_SHUTDOWN_WAIT;
|
||||
while pending.iter().any(|handle| !handle.is_finished()) {
|
||||
if std::time::Instant::now() >= deadline {
|
||||
|
||||
@@ -513,6 +513,7 @@ async fn resolve_jvm_application(
|
||||
call.window(),
|
||||
std::path::PathBuf::from(&module),
|
||||
test == Some(true),
|
||||
false,
|
||||
policy,
|
||||
&cancel,
|
||||
None,
|
||||
|
||||
@@ -9,6 +9,7 @@ use crate::{Host, Project};
|
||||
use ide_command::command;
|
||||
|
||||
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
|
||||
use ide_build::jbuild::Target;
|
||||
use ide_build::maven::completion::{PomCompletion, PomCompletionOption};
|
||||
use ide_build::maven::sources;
|
||||
use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions};
|
||||
@@ -970,16 +971,44 @@ pub async fn build_run(
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let (root, cache, sink) = (project.root.clone(), project.build_cache_dir(), project.sink.clone());
|
||||
let file = file.map(|f| ide_core::project_roots::resolve(&root, &f));
|
||||
let settings = project.settings.effective();
|
||||
let detected = project.detected_roots.read().clone();
|
||||
let config_dir = host.config_dir.clone();
|
||||
let token = host.begin_project_request(window, request);
|
||||
let launch_project = project.clone();
|
||||
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
|
||||
let result = blocking(move || {
|
||||
let single = cmake.is_none() && ide_workspace::workspace::Workspace::load(&root)?.is_none();
|
||||
// A Maven or Gradle project builds with the IDE's Java build (#4078), unless its
|
||||
// settings ask for the build tool, or it can't.
|
||||
if single {
|
||||
let model = with_profiles(load(&root, &cache, &settings), &cache);
|
||||
let served = match file.as_deref() {
|
||||
Some(module) => super::java::served_by_service(&root, &model, &settings, module),
|
||||
None => super::java::project_served_by_service(&model, &settings),
|
||||
};
|
||||
if served {
|
||||
let service = super::java::ServiceBuild {
|
||||
service: &service,
|
||||
data_dir: &data_dir,
|
||||
root: &root,
|
||||
cache: &cache,
|
||||
settings: &settings,
|
||||
model: &model,
|
||||
};
|
||||
let target = match file.as_deref() {
|
||||
Some(file) => Target::Module(file),
|
||||
None => Target::Project,
|
||||
};
|
||||
if let Some(result) = service_build_result(&service, target, kind, &clear, &sink, &token, &on_event)? {
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Fast path (#2476): an unchanged single-project Maven build skips
|
||||
// Maven entirely. Previous diagnostics stay: nothing changed, so they
|
||||
// are still accurate.
|
||||
let single = cmake.is_none() && ide_workspace::workspace::Workspace::load(&root)?.is_none();
|
||||
if single && kind == BuildKind::Build {
|
||||
let model = with_profiles(load(&root, &cache, &settings), &cache);
|
||||
if compile::menu_up_to_date(&cache, &root, &model, file.as_deref(), &token) {
|
||||
@@ -1102,13 +1131,59 @@ pub async fn build_run(
|
||||
let outcome = result?;
|
||||
// Maven generated sources (protobuf, gRPC) stay invisible to jdtls until the
|
||||
// folders the build wrote are attached. An up-to-date build skips Maven and
|
||||
// still needs this: the classes can already be on disk.
|
||||
if outcome.system == ide_build::compile::BuildSystem::Maven {
|
||||
// still needs this: the classes can already be on disk. The IDE's Java build
|
||||
// generates them with Maven too.
|
||||
if matches!(outcome.system, ide_build::compile::BuildSystem::Maven | ide_build::compile::BuildSystem::Javac) {
|
||||
project.lsp.sync_maven_generated_sources(&project.root).await;
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// A menu build by the IDE's Java build, as the Build window shows it; `None` when Maven builds.
|
||||
/// Diagnostics of `clear` are cleared once the service builds; its messages are published.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn service_build_result(
|
||||
service: &super::java::ServiceBuild,
|
||||
target: Target,
|
||||
kind: BuildKind,
|
||||
clear: &[std::path::PathBuf],
|
||||
sink: &ide_core::SharedSink,
|
||||
token: &CancellationToken,
|
||||
on_event: &Channel<BuildEvent>,
|
||||
) -> IdeResult<Option<BuildResult>> {
|
||||
let started = std::time::Instant::now();
|
||||
let title = std::sync::Mutex::new(String::new());
|
||||
let forward = |event: BuildEvent| {
|
||||
if let BuildEvent::Started { title: t, .. } = &event {
|
||||
*title.lock().unwrap() = t.clone();
|
||||
}
|
||||
let _ = on_event.send(event);
|
||||
};
|
||||
let built = service.build(target, kind, token, &forward)?;
|
||||
let Some(outputs) = built else { return Ok(None) };
|
||||
for path in clear {
|
||||
sink.emit(IdeEvent::Diagnostics {
|
||||
path: path.clone().into(),
|
||||
source: compile::DIAGNOSTICS_SOURCE.into(),
|
||||
items: Vec::new(),
|
||||
});
|
||||
}
|
||||
for (path, items) in compile::diagnostics(&outputs.messages) {
|
||||
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items });
|
||||
}
|
||||
let count =
|
||||
|severity: ide_core::Severity| outputs.messages.iter().filter(|m| m.severity == severity).count() as u32;
|
||||
Ok(Some(BuildResult {
|
||||
system: compile::BuildSystem::Javac,
|
||||
title: title.into_inner().unwrap(),
|
||||
success: outputs.failure.is_none(),
|
||||
errors: count(ide_core::Severity::Error),
|
||||
warnings: count(ide_core::Severity::Warning),
|
||||
duration_ms: started.elapsed().as_secs_f64() * 1000.0,
|
||||
messages: outputs.messages,
|
||||
}))
|
||||
}
|
||||
|
||||
fn plan_compile_file(
|
||||
root: &Path,
|
||||
cache: &Path,
|
||||
@@ -1167,7 +1242,26 @@ pub async fn build_compile_file(
|
||||
};
|
||||
let sink = project.sink.clone();
|
||||
let token = host.begin_project_request(window, request);
|
||||
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
|
||||
let result = blocking(move || {
|
||||
{
|
||||
let model = with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache);
|
||||
if super::java::served_by_service(&scope.root, &model, &scope.settings, &file) {
|
||||
let service = super::java::ServiceBuild {
|
||||
service: &service,
|
||||
data_dir: &data_dir,
|
||||
root: &scope.root,
|
||||
cache: &scope.cache,
|
||||
settings: &scope.settings,
|
||||
model: &model,
|
||||
};
|
||||
let target = Target::File(&file);
|
||||
let kind = BuildKind::Build;
|
||||
if let Some(result) = service_build_result(&service, target, kind, &clear, &sink, &token, &on_event)? {
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
for path in clear {
|
||||
sink.emit(IdeEvent::Diagnostics {
|
||||
path: path.into(),
|
||||
@@ -1190,7 +1284,7 @@ pub async fn build_compile_file(
|
||||
.await;
|
||||
host.end_request(request);
|
||||
let outcome = result?;
|
||||
if outcome.system == ide_build::compile::BuildSystem::Maven {
|
||||
if matches!(outcome.system, ide_build::compile::BuildSystem::Maven | ide_build::compile::BuildSystem::Javac) {
|
||||
project.lsp.sync_maven_generated_sources(&scope_root).await;
|
||||
}
|
||||
Ok(outcome)
|
||||
|
||||
@@ -9,7 +9,7 @@ use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
|
||||
use ide_db::split::SqlStatement;
|
||||
use ide_db::{
|
||||
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbVisibilityChange, HistoryEntry, PlanNode,
|
||||
QueryResult, SchemaObjects, SortKey, TableDetails, TableInfo, TablePage,
|
||||
QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -293,6 +293,19 @@ pub async fn db_table_details(
|
||||
db.table_details(&id, &schema, &table).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_table_grants(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
schema: String,
|
||||
table: String,
|
||||
) -> IdeResult<Vec<TableGrant>> {
|
||||
// Who may read or change `table` (PostgreSQL and MySQL; empty elsewhere).
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.table_grants(&id, &schema, &table).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_ddl(host: &Host, window: &str, id: String, schema: String, table: String) -> IdeResult<String> {
|
||||
// The DDL of table or view `table` (Go to DDL, Generate DDL).
|
||||
@@ -481,6 +494,7 @@ async fn execute_statements(
|
||||
let db = host.project(window)?.db.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = async {
|
||||
db.validate_script(id, &statements).await?;
|
||||
for (index, statement) in statements.into_iter().enumerate() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -690,6 +704,7 @@ ide_command::domain!(
|
||||
db_sources,
|
||||
db_statements,
|
||||
db_table_details,
|
||||
db_table_grants,
|
||||
db_table_page,
|
||||
db_tables,
|
||||
db_test,
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//! HTTP Client commands shared by the desktop shell's IPC commands and the remote server: a remote
|
||||
//! window sends its requests from the project host and keeps their history there.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeResult, IpcPath, Location, RequestId};
|
||||
use ide_http::{HistoryEntry, HttpExchange};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::blocking;
|
||||
|
||||
/// The root of the window's project, when one is open.
|
||||
fn root(host: &Host, window: &str) -> Option<PathBuf> {
|
||||
host.project(window).ok().map(|p| p.root.clone())
|
||||
}
|
||||
|
||||
/// Environment names from the `http-client(.private).env.json` files that apply to `path`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn http_environments(host: &Host, window: &str, path: Option<IpcPath>) -> IdeResult<Vec<String>> {
|
||||
let root = root(host, window);
|
||||
blocking(move || ide_http::environments(path.as_deref(), root.as_deref())).await
|
||||
}
|
||||
|
||||
/// Sends request `index` of `text` (the editor buffer of `path`) and records
|
||||
/// the exchange in the response history. Cancel with `cancel_request(request)`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn http_execute(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
path: Option<IpcPath>,
|
||||
text: String,
|
||||
index: u32,
|
||||
env: Option<String>,
|
||||
) -> IdeResult<HttpExchange> {
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let input = ide_http::RunInput {
|
||||
text: &text,
|
||||
index,
|
||||
file: path.as_deref(),
|
||||
root: Some(&project.root),
|
||||
env: env.as_deref(),
|
||||
};
|
||||
let result = ide_http::run(input, &cancel).await;
|
||||
host.end_request(request);
|
||||
let exchange = result?;
|
||||
let history = project.http_history.clone();
|
||||
let saved = exchange.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
if let Err(e) = history.add(&saved) {
|
||||
tracing::warn!("http history: {}", e.message);
|
||||
}
|
||||
});
|
||||
Ok(exchange)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn http_history(host: &Host, window: &str) -> IdeResult<Vec<HistoryEntry>> {
|
||||
Ok(host.project(window)?.http_history.list())
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn http_history_get(host: &Host, window: &str, id: String) -> IdeResult<HttpExchange> {
|
||||
host.project(window)?.http_history.get(&id)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn http_history_clear(host: &Host, window: &str) -> IdeResult<()> {
|
||||
host.project(window)?.http_history.clear()
|
||||
}
|
||||
|
||||
/// Convert to cURL and Copy: request `index` of `text` (the editor buffer of `path`), with
|
||||
/// the variables of `env` substituted, as a cURL command.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn http_curl(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: Option<IpcPath>,
|
||||
text: String,
|
||||
index: u32,
|
||||
env: Option<String>,
|
||||
) -> IdeResult<String> {
|
||||
let root = root(host, window);
|
||||
blocking(move || {
|
||||
ide_http::curl(&ide_http::RunInput {
|
||||
text: &text,
|
||||
index,
|
||||
file: path.as_deref(),
|
||||
root: root.as_deref(),
|
||||
env: env.as_deref(),
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The environment file for the request file `path` (`is_private`: the private one): the nearest
|
||||
/// existing one, else a new one next to it.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn http_environment_file(host: &Host, window: &str, path: IpcPath, is_private: bool) -> IdeResult<IpcPath> {
|
||||
let root = root(host, window);
|
||||
blocking(move || ide_http::env::environment_file(&path, root.as_deref(), is_private).map(IpcPath::from)).await
|
||||
}
|
||||
|
||||
/// Where `{{name}}` is defined in the environment files that apply to request file `path`
|
||||
/// (Navigate › Declaration on a variable), private file first.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn http_variable_definitions(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: IpcPath,
|
||||
name: String,
|
||||
) -> IdeResult<Vec<Location>> {
|
||||
let root = root(host, window);
|
||||
blocking(move || Ok(ide_http::env::variable_definitions(&path, root.as_deref(), &name))).await
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
http: http_curl,
|
||||
http_environment_file,
|
||||
http_environments,
|
||||
http_execute,
|
||||
http_history,
|
||||
http_history_clear,
|
||||
http_history_get,
|
||||
http_variable_definitions,
|
||||
);
|
||||
@@ -9,6 +9,7 @@ use super::build::{load, with_profiles, workspace};
|
||||
use cache::LaunchEvents;
|
||||
use ide_build::BuildModel;
|
||||
use ide_build::compile::{self, BuildEvent};
|
||||
use ide_build::jbuild::{Built, JavaBuild, JavaBuildService, LaunchOutputs, Target};
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
|
||||
@@ -22,12 +23,16 @@ use std::path::{Path, PathBuf};
|
||||
/// A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
|
||||
/// The build streams its console, messages and progress on `on_event` while it runs; a launch
|
||||
/// whose build another launch's build joins receives that build's events.
|
||||
/// A Maven module is built by the IDE's Java build, except for a `debug` launch the language
|
||||
/// server serves: java-debug's HotSwap reloads the classes the language server compiles.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
pub async fn java_resolve_launch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
module: PathBuf,
|
||||
test: bool,
|
||||
debug: bool,
|
||||
policy: BuildPolicy,
|
||||
request: RequestId,
|
||||
on_event: Channel<BuildEvent>,
|
||||
@@ -39,16 +44,18 @@ pub async fn java_resolve_launch(
|
||||
let events: LaunchEvents = std::sync::Arc::new(move |event| {
|
||||
let _ = on_event.send(event);
|
||||
});
|
||||
let result = resolve_launch(host, window, module, test, policy, &cancel, Some(events)).await;
|
||||
let result = resolve_launch(host, window, module, test, debug, policy, &cancel, Some(events)).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn resolve_launch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
module: PathBuf,
|
||||
test: bool,
|
||||
debug: bool,
|
||||
policy: BuildPolicy,
|
||||
cancel: &CancellationToken,
|
||||
events: Option<LaunchEvents>,
|
||||
@@ -73,13 +80,12 @@ pub(crate) async fn resolve_launch(
|
||||
}
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let launches = project.java_launches.for_cache(&scope.cache);
|
||||
let waiting = launches.waiting.add(module.clone(), test, policy, events.clone());
|
||||
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
|
||||
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
|
||||
let build = policy != BuildPolicy::NoBuild;
|
||||
let full = policy == BuildPolicy::Rebuild;
|
||||
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, external, mut delegated, is_maven) = {
|
||||
let (model, external, mut delegated, is_maven, non_java, served) = {
|
||||
let scope = scope.clone();
|
||||
let launches = launches.clone();
|
||||
let module = module.clone();
|
||||
@@ -89,6 +95,7 @@ pub(crate) async fn resolve_launch(
|
||||
let model = load_launch_model(&scope);
|
||||
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
|
||||
let is_maven = is_maven_module(root, &model, &module);
|
||||
let served = served_by_service(root, &model, &scope.settings, &module);
|
||||
let delegated = build
|
||||
&& delegates_to_external_build(
|
||||
is_maven,
|
||||
@@ -98,11 +105,65 @@ pub(crate) async fn resolve_launch(
|
||||
prefer_maven,
|
||||
);
|
||||
let external = non_java || delegated;
|
||||
(model, external, delegated, is_maven)
|
||||
(std::sync::Arc::new(model), external, delegated, is_maven, non_java, served)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
};
|
||||
// A Maven or Gradle module is built by the IDE's Java build ([`served_by_service`]), unless
|
||||
// the launch debugs with java-debug, whose HotSwap reloads what jdtls compiles (ecj's
|
||||
// classes differ from javac's: lambda names). jdtls keeps building for its diagnostics
|
||||
// either way.
|
||||
if served && !non_java && !debug {
|
||||
let built = {
|
||||
let (service, data_dir, scope, model, module, cancel, events) = (
|
||||
host.java_build.clone(),
|
||||
host.local_data_dir.clone(),
|
||||
scope.clone(),
|
||||
model.clone(),
|
||||
module.clone(),
|
||||
cancel.clone(),
|
||||
events.clone(),
|
||||
);
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let on_event = |event: BuildEvent| {
|
||||
if let Some(events) = &events {
|
||||
events(event);
|
||||
}
|
||||
};
|
||||
let kind = build.then_some(build_kind);
|
||||
build_with_service(&service, &data_dir, &scope, &model, &module, test, kind, &cancel, &on_event)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??
|
||||
};
|
||||
if let Some(outputs) = built {
|
||||
progress("Resolving the classpath");
|
||||
let mut info = project.lsp.java_launch(&module, test, false, false, false, cancel).await?;
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let cancel = cancel.clone();
|
||||
return tokio::task::spawn_blocking(move || {
|
||||
// javac's verdict replaces JDT's, as a Maven build's does.
|
||||
if build {
|
||||
apply_external_build_result(&mut info, outputs.failure, true);
|
||||
}
|
||||
info.class_paths = outputs.class_paths.iter().map(|p| p.to_string_lossy().into_owned()).collect();
|
||||
apply_library_classpath(&mut info, &scope.root, &scope.settings.project_structure.libraries, test);
|
||||
finish_launch(&mut info, &scope.root, &module, &scope.settings, &model, &data_dir);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
tracing::info!(
|
||||
total_ms = started.elapsed().as_millis(),
|
||||
"Java launch resolved with the IDE's Java build"
|
||||
);
|
||||
Ok(info)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
}
|
||||
}
|
||||
let waiting = launches.waiting.add(module.clone(), test, policy, events.clone());
|
||||
let mut external_build =
|
||||
if delegated { Some(project.lsp.java_external_build(&module, cancel).await?) } else { None };
|
||||
if build && !delegated {
|
||||
@@ -124,7 +185,6 @@ pub(crate) async fn resolve_launch(
|
||||
drop_processor_recreate_errors(&mut info);
|
||||
}
|
||||
}
|
||||
let model = std::sync::Arc::new(model);
|
||||
let members = if delegated {
|
||||
build_members(&project, &scope, &model, &module, test, &waiting, cancel).await?
|
||||
} else {
|
||||
@@ -217,6 +277,104 @@ pub(crate) async fn resolve_launch(
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Builds the launch of a Maven module with the IDE's Java build (#4078): javac in a resident
|
||||
/// process with the configuration Maven gives the compiler, into outputs in the project cache
|
||||
/// that neither the language server nor a terminal `mvn` writes. `None` when the module needs
|
||||
/// Maven's own build (another compiler, a multi-release jar, a Java module…), which then runs.
|
||||
/// Without `kind` (no build before launch), the outputs of its last build, if any.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build_with_service(
|
||||
service: &JavaBuildService,
|
||||
data_dir: &Path,
|
||||
scope: &workspace::Scope,
|
||||
model: &BuildModel,
|
||||
module: &Path,
|
||||
test: bool,
|
||||
kind: Option<compile::BuildKind>,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
) -> IdeResult<Option<LaunchOutputs>> {
|
||||
let service =
|
||||
ServiceBuild { service, data_dir, root: &scope.root, cache: &scope.cache, settings: &scope.settings, model };
|
||||
match kind {
|
||||
Some(kind) => service.build(Target::Launch { module, test }, kind, cancel, on_event),
|
||||
// No build: the outputs of the last one, when there was one.
|
||||
None => Ok(service
|
||||
.with(module, |build| build.recorded_launch(module, test))
|
||||
.flatten()
|
||||
.map(|class_paths| LaunchOutputs { class_paths, ..Default::default() })),
|
||||
}
|
||||
}
|
||||
|
||||
/// A build of the IDE's Java build service in one project (or workspace member).
|
||||
pub(crate) struct ServiceBuild<'a> {
|
||||
pub service: &'a JavaBuildService,
|
||||
pub data_dir: &'a Path,
|
||||
pub root: &'a Path,
|
||||
pub cache: &'a Path,
|
||||
pub settings: &'a Settings,
|
||||
pub model: &'a BuildModel,
|
||||
}
|
||||
|
||||
impl ServiceBuild<'_> {
|
||||
/// Runs `f` with the build, its JDKs resolved for `module`; `None` when the build jar
|
||||
/// can't be installed.
|
||||
fn with<R>(&self, module: &Path, f: impl FnOnce(&JavaBuild) -> R) -> Option<R> {
|
||||
let jar = ide_sdk::java::java_build_jar(self.data_dir)?;
|
||||
let (root, settings) = (self.root, self.settings);
|
||||
let jdk = |release: Option<u32>| {
|
||||
ide_sdk::apply::module_jdk(root, module, settings)
|
||||
.or_else(|| ide_sdk::java::pick_jdk(&ide_sdk::java::installed_jdks(), release).cloned())
|
||||
.map(|jdk| jdk.home)
|
||||
};
|
||||
let version = ide_sdk::java::java_build_version();
|
||||
let build = JavaBuild {
|
||||
root,
|
||||
model: self.model,
|
||||
cache: self.cache,
|
||||
jar: &jar,
|
||||
jar_version: &version,
|
||||
local_repo: ide_sdk::apply::maven_local_repository(root, settings),
|
||||
service: self.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
Some(f(&build))
|
||||
}
|
||||
|
||||
/// Builds `target`; `None` when the build tool has to (the service doesn't build it, or failed).
|
||||
pub fn build(
|
||||
&self,
|
||||
target: Target,
|
||||
kind: compile::BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
) -> IdeResult<Option<LaunchOutputs>> {
|
||||
let module = match target {
|
||||
Target::Launch { module, .. } | Target::Module(module) | Target::File(module) => module,
|
||||
Target::Project => self.root,
|
||||
};
|
||||
let Some(built) = self.with(module, |build| build.build(target, kind, cancel, on_event)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
match built {
|
||||
Ok(Built::Done(outputs)) => Ok(Some(outputs)),
|
||||
Ok(Built::Unsupported(reason)) => {
|
||||
tracing::info!(module = %module.display(), reason, "Building with the build tool");
|
||||
Ok(None)
|
||||
}
|
||||
Err(e) if e.kind == ErrorKind::Cancelled => Err(e),
|
||||
Err(e) => {
|
||||
tracing::warn!(module = %module.display(), "The IDE's Java build failed: {}", e.message);
|
||||
on_event(BuildEvent::Output {
|
||||
text: format!("The IDE's Java build failed, so the build tool builds it: {}\n", e.message),
|
||||
stderr: true,
|
||||
});
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_launch_model(scope: &workspace::Scope) -> BuildModel {
|
||||
with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache)
|
||||
}
|
||||
@@ -225,6 +383,39 @@ fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
|
||||
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
|
||||
}
|
||||
|
||||
/// Whether the IDE's Java build builds the module holding `path` (#4078): a Maven module unless
|
||||
/// Settings › Maven › Delegate IDE build/run actions to Maven asks for Maven; a Gradle module
|
||||
/// when Settings › Gradle › Build and run using asks for the IDE.
|
||||
pub(crate) fn served_by_service(root: &Path, model: &BuildModel, settings: &Settings, path: &Path) -> bool {
|
||||
let maven = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| (root.join(&p.dir), true)));
|
||||
let gradle = model.gradle.iter().flat_map(|g| g.projects.iter().map(|p| (root.join(&p.dir), false)));
|
||||
// The deepest module holding it; Maven's when both build the folder.
|
||||
let module = maven
|
||||
.chain(gradle)
|
||||
.filter(|(dir, _)| path.starts_with(dir))
|
||||
.max_by_key(|(dir, maven)| (dir.components().count(), *maven));
|
||||
match module {
|
||||
Some((_, true)) => !settings.languages.java.maven.delegate_build,
|
||||
Some((_, false)) => gradle_served(settings),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the IDE's Java build builds the whole project: it has Maven or Gradle builds, and
|
||||
/// builds them all.
|
||||
pub(crate) fn project_served_by_service(model: &BuildModel, settings: &Settings) -> bool {
|
||||
let maven = model.maven.as_ref().map(|_| !settings.languages.java.maven.delegate_build);
|
||||
let gradle = (!model.gradle.is_empty()).then(|| gradle_served(settings));
|
||||
match (maven, gradle) {
|
||||
(None, None) => false,
|
||||
(maven, gradle) => maven.unwrap_or(true) && gradle.unwrap_or(true),
|
||||
}
|
||||
}
|
||||
|
||||
fn gradle_served(settings: &Settings) -> bool {
|
||||
settings.languages.java.gradle.run_using == ide_core::settings::GradleRunUsing::Ide
|
||||
}
|
||||
|
||||
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
|
||||
/// build tool compiles it, and the classpath comes from that server, else from Maven.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -241,8 +432,9 @@ async fn resolve_launch_without_jdtls(
|
||||
let started = std::time::Instant::now();
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, built) = {
|
||||
let (model, built, by_service) = {
|
||||
let (scope, module, cancel, events) = (scope.clone(), module.clone(), cancel.clone(), events.clone());
|
||||
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = load_launch_model(&scope);
|
||||
let on_event = |event: BuildEvent| {
|
||||
@@ -250,12 +442,33 @@ async fn resolve_launch_without_jdtls(
|
||||
events(event);
|
||||
}
|
||||
};
|
||||
let built = if policy == BuildPolicy::NoBuild {
|
||||
None
|
||||
} else {
|
||||
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event))
|
||||
};
|
||||
(model, built)
|
||||
if policy == BuildPolicy::NoBuild {
|
||||
return (model, None, false);
|
||||
}
|
||||
if served_by_service(&scope.root, &model, &scope.settings, &module)
|
||||
&& !compile::launch_has_non_java_sources(&scope.root, &model, &module, test)
|
||||
{
|
||||
match build_with_service(
|
||||
&service,
|
||||
&data_dir,
|
||||
&scope,
|
||||
&model,
|
||||
&module,
|
||||
test,
|
||||
Some(kind),
|
||||
&cancel,
|
||||
&on_event,
|
||||
) {
|
||||
Ok(Some(outputs)) => {
|
||||
let built = compile::LaunchBuild { class_dirs: outputs.class_paths, failure: outputs.failure };
|
||||
return (model, Some(Ok(built)), true);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => return (model, Some(Err(e)), false),
|
||||
}
|
||||
}
|
||||
let built = compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event);
|
||||
(model, Some(built), false)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
@@ -294,6 +507,12 @@ async fn resolve_launch_without_jdtls(
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
|
||||
match from_server {
|
||||
// The IDE's Java build gave the whole classpath; the server adds its JDK.
|
||||
Some(server) if by_service => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
info.java_home = server.jdk_home.map(Into::into);
|
||||
}
|
||||
None if by_service => {}
|
||||
Some(server) => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
info.module_paths = server.classpath.module_paths;
|
||||
@@ -683,7 +902,8 @@ pub async fn java_build_workspace(
|
||||
|
||||
/// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
|
||||
/// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
|
||||
/// classpath has one; from the engine's repository, else downloaded once from Maven Central), and,
|
||||
/// classpath has one, or has JUnit 4 alone; from the engine's repository, else downloaded once from
|
||||
/// Maven Central), and,
|
||||
/// for a Maven module, what its Surefire configuration gives the forked test JVM.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn java_junit_runner(
|
||||
@@ -707,13 +927,13 @@ pub async fn java_junit_runner(
|
||||
let runner = ide_sdk::java::junit_runner_jar(&data_dir)
|
||||
.ok_or_else(|| IdeError::internal("Cannot install the JUnit runner"))?;
|
||||
let launcher = match ide_sdk::java::junit_launcher(&class_paths) {
|
||||
ide_sdk::java::JunitLauncher::OnClasspath => None,
|
||||
ide_sdk::java::JunitLauncher::OnClasspath | ide_sdk::java::JunitLauncher::Junit4 => None,
|
||||
ide_sdk::java::JunitLauncher::Found(path) => Some(path),
|
||||
ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?),
|
||||
ide_sdk::java::JunitLauncher::NoPlatform => {
|
||||
return Err(IdeError::unavailable(
|
||||
"No JUnit Platform (junit-platform-engine) on the test classpath. To run these tests through \
|
||||
Maven, set Settings › Build Tools › Maven › Run tests using to Maven.",
|
||||
"Neither JUnit 5 (junit-platform-engine) nor JUnit 4 is on the test classpath. To run these tests \
|
||||
through Maven, set Settings › Build Tools › Maven › Run tests using to Maven.",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -19,6 +19,7 @@ pub mod flutter;
|
||||
pub mod fs;
|
||||
pub mod heap;
|
||||
pub mod history;
|
||||
pub mod http;
|
||||
pub mod java;
|
||||
pub mod jvm_icons;
|
||||
pub mod lsp;
|
||||
@@ -92,6 +93,7 @@ ide_command::domains!(
|
||||
fs: crate::ops::fs,
|
||||
heap: crate::ops::heap,
|
||||
history: crate::ops::history,
|
||||
http: crate::ops::http,
|
||||
java: crate::ops::java,
|
||||
jvm_icons: crate::ops::jvm_icons,
|
||||
lsp: crate::ops::lsp,
|
||||
|
||||
@@ -122,6 +122,9 @@ pub fn settings_set(
|
||||
if key == "mcpServer" || key.starts_with("mcpServer.") {
|
||||
host.mcp.apply(host);
|
||||
}
|
||||
if key == "terminal" || key.starts_with("terminal.") {
|
||||
super::term::apply_output_rate(host, window);
|
||||
}
|
||||
let sink = host.window_sink(window);
|
||||
sink.emit(IdeEvent::SettingsChanged { key });
|
||||
if let Some(root) = applied.roots_changed {
|
||||
|
||||
@@ -319,6 +319,7 @@ pub async fn run_start(
|
||||
on_output: Channel<OutputChunk>,
|
||||
request: Option<ide_core::RequestId>,
|
||||
) -> IdeResult<RunInfo> {
|
||||
super::term::apply_output_rate(host, window);
|
||||
let on_output: Emit<OutputChunk> = Arc::new(move |chunk| {
|
||||
let _ = on_output.send(chunk);
|
||||
});
|
||||
|
||||
@@ -4,8 +4,10 @@
|
||||
//! given belong to the server's [`ide_ssh::SshManager`], not the desktop's.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::IdeResult;
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::remote_settings::SshConfiguration;
|
||||
use ide_core::{IdeError, IdeEvent, IdeResult};
|
||||
use ide_ssh::secrets::LegacyPasswordAction;
|
||||
|
||||
/// Test Connection: connects with `config` as edited (not necessarily saved).
|
||||
#[command(trust = always)]
|
||||
@@ -15,8 +17,23 @@ pub async fn ssh_test(host: &Host, config: SshConfiguration, secret: Option<Stri
|
||||
|
||||
/// Remembers the password / passphrase of configuration `id` (`None` forgets it).
|
||||
#[command(trust = always)]
|
||||
pub fn ssh_set_secret(host: &Host, id: String, secret: Option<String>, save: bool) {
|
||||
host.ssh.set_secret(&id, secret, save);
|
||||
pub fn ssh_set_secret(host: &Host, window: &str, id: String, secret: Option<String>, save: bool) {
|
||||
if let Err(e) = host.ssh.set_secret(&id, secret, save) {
|
||||
host.window_sink(window).emit(IdeEvent::Notify {
|
||||
level: NotifyLevel::Warning,
|
||||
title: "Could not save credential".into(),
|
||||
body: Some(e.message),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// `Some` means legacy credentials remain in plaintext on this host.
|
||||
#[command(trust = always)]
|
||||
pub async fn ssh_legacy_passwords(host: &Host, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
|
||||
let ssh = host.ssh.clone();
|
||||
tokio::task::spawn_blocking(move || ssh.resolve_legacy_passwords(action))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Whether a password is saved under `key` (an FTP deployment server's).
|
||||
@@ -52,6 +69,7 @@ ide_command::domain!(
|
||||
ssh:
|
||||
ssh_connected,
|
||||
ssh_disconnect,
|
||||
ssh_legacy_passwords,
|
||||
ssh_needs_secret,
|
||||
ssh_password_saved,
|
||||
ssh_set_secret,
|
||||
|
||||
@@ -29,6 +29,7 @@ pub async fn term_spawn(
|
||||
mut options: TerminalOptions,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<TerminalInfo> {
|
||||
apply_output_rate(host, window);
|
||||
if !host.project(window).is_ok_and(|p| p.is_trusted()) {
|
||||
// Project terminal settings can otherwise start a command as soon as a tab restores.
|
||||
let global = host.global_settings.effective().terminal;
|
||||
@@ -61,6 +62,17 @@ pub async fn term_spawn(
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
/// Settings › Tools › Terminal › Max FPS also paces the terminal and Run console output
|
||||
/// pumps (#5897): applied from the window's effective settings when a session starts and
|
||||
/// when the setting changes. The rate is process-wide; the last window to apply it wins.
|
||||
pub(crate) fn apply_output_rate(host: &Host, window: &str) {
|
||||
let terminal = match host.project(window) {
|
||||
Ok(project) => project.settings.effective().terminal,
|
||||
Err(_) => host.global_settings.effective().terminal,
|
||||
};
|
||||
ide_core::output_rate::set_max_fps(&terminal.max_fps);
|
||||
}
|
||||
|
||||
/// Tools › Start SSH Session: a login shell on SSH configuration `id`, opened by the
|
||||
/// built-in client with the configuration's saved password, key or agent.
|
||||
pub async fn spawn_ssh(
|
||||
|
||||
@@ -4826,7 +4826,18 @@ impl PluginApi {
|
||||
if let Some(icon) = file.as_ref().and_then(|f| f.icon.as_ref()) {
|
||||
ide_extension::validate_item_id(icon, "file icon id").map_err(HostError::Invalid)?;
|
||||
}
|
||||
items.retain(|d| decoration_style(&d.style));
|
||||
for colors in items.iter_mut().filter_map(|d| d.colors.as_mut()) {
|
||||
for color in [&mut colors.foreground, &mut colors.background].into_iter().flatten() {
|
||||
*color = decoration_color(color).ok_or_else(|| {
|
||||
HostError::Invalid(format!("decoration color '{color}' is not #rrggbb or #rrggbbaa"))
|
||||
})?;
|
||||
}
|
||||
}
|
||||
items
|
||||
.iter_mut()
|
||||
.for_each(|d| d.colors = d.colors.take().filter(|c| c.foreground.is_some() || c.background.is_some()));
|
||||
// An item with its own colors (API 1.17) may leave the style empty.
|
||||
items.retain(|d| decoration_style(&d.style) || (d.style.is_empty() && d.colors.is_some()));
|
||||
if items.iter().any(|d| d.range.start > d.range.end) {
|
||||
return Err(HostError::Invalid("reversed decoration range".into()));
|
||||
}
|
||||
@@ -4924,6 +4935,13 @@ impl PluginApi {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
/// A `set-styled` color as the editor renders it: `#rrggbb` or `#rrggbbaa`, lower case.
|
||||
fn decoration_color(color: &str) -> Option<String> {
|
||||
let hex = color.strip_prefix('#')?;
|
||||
((hex.len() == 6 || hex.len() == 8) && hex.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
.then(|| format!("#{}", hex.to_ascii_lowercase()))
|
||||
}
|
||||
|
||||
fn decoration_style(style: &str) -> bool {
|
||||
matches!(
|
||||
style,
|
||||
@@ -5058,9 +5076,38 @@ mod workbench_tests {
|
||||
hover: None,
|
||||
after: Some("after".into()),
|
||||
markdown_hover: None,
|
||||
colors: None,
|
||||
};
|
||||
api.decorations(Some(&path), "set", vec![item("highlight"), item("unknown")]).unwrap();
|
||||
assert_eq!(api.shared.decoration_sets()["test"][0].items.len(), 1);
|
||||
// Styled items (API 1.17): colors are validated and normalized; an empty style needs colors.
|
||||
let colored = |style: &str, foreground: Option<&str>, background: Option<&str>| ide_plugin::Decoration {
|
||||
colors: Some(ide_plugin::DecorationColors {
|
||||
foreground: foreground.map(Into::into),
|
||||
background: background.map(Into::into),
|
||||
}),
|
||||
..item(style)
|
||||
};
|
||||
api.decorations(
|
||||
Some(&path),
|
||||
"styled",
|
||||
vec![
|
||||
colored("", Some("#1A1A1A"), Some("#FFEB3BFF")),
|
||||
colored("highlight", None, Some("#00e5ff")),
|
||||
colored("", None, None),
|
||||
item(""),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
let styled = api.shared.decoration_sets()["test"].iter().find(|s| s.set_id == "styled").unwrap().items.clone();
|
||||
assert_eq!(styled.len(), 2);
|
||||
let first = styled[0].colors.as_ref().unwrap();
|
||||
assert_eq!((first.foreground.as_deref(), first.background.as_deref()), (Some("#1a1a1a"), Some("#ffeb3bff")));
|
||||
for bad in ["red", "#fff", "#12345g", "rgb(0,0,0)", "#1234567", "#ffffff; x: y"] {
|
||||
let err = api.decorations(Some(&path), "styled", vec![colored("", Some(bad), None)]).unwrap_err();
|
||||
assert!(matches!(err, HostError::Invalid(ref m) if m.contains("#rrggbb")), "{bad}: {err}");
|
||||
}
|
||||
api.decorations(None, "styled", vec![]).unwrap();
|
||||
// Decorations follow the file: a path outside the open project is accepted too.
|
||||
api.decorations(Some(&root.join("../outside.txt")), "set", vec![]).unwrap();
|
||||
assert_eq!(api.shared.decoration_sets()["test"].len(), 2);
|
||||
|
||||
@@ -385,6 +385,9 @@ impl PluginHost {
|
||||
}
|
||||
);
|
||||
let fetched = self.fetch_market_package(&candidate.url, &entry, &archive);
|
||||
if let Some(mirror) = &candidate.mirror {
|
||||
mirror::report(mirror, fetched.is_ok());
|
||||
}
|
||||
if let Err(e) = &fetched {
|
||||
tracing::warn!("plugins: {} from {} failed: {}", entry.id, candidate.url, e.message);
|
||||
}
|
||||
|
||||
@@ -125,8 +125,8 @@ impl Host {
|
||||
// A window takes the root over from the MCP server's background project, whose
|
||||
// shutdown the wait below sits out; none opens until this open is over.
|
||||
let _claim = (!crate::mcp::BackgroundProjects::is_key(window)).then(|| self.mcp_background.claim(self, &root));
|
||||
self.close_project(window);
|
||||
self.wait_detached_closes();
|
||||
self.close_project_detached(window);
|
||||
self.wait_detached_closes_for(&root);
|
||||
let sink: SharedSink = (self.sink_for)(window);
|
||||
// Before anything the project starts: its children get the project's environment.
|
||||
let trusted = Arc::new(AtomicBool::new(self.trust.window_trusted(&root)?));
|
||||
@@ -867,8 +867,10 @@ impl Host {
|
||||
}
|
||||
return Ok(current);
|
||||
}
|
||||
self.close_project(window);
|
||||
self.wait_detached_closes();
|
||||
self.close_project_detached(window);
|
||||
if let Some(dir) = watch_dir {
|
||||
self.wait_detached_closes_for(dir);
|
||||
}
|
||||
let sink: SharedSink = (self.sink_for)(window);
|
||||
let settings = Arc::new(SettingsStore::load(&self.config_dir, None));
|
||||
let effective = settings.effective();
|
||||
@@ -2004,7 +2006,7 @@ fn with_gradle_roots(
|
||||
use ide_build::gradle::ReportedRoot;
|
||||
use ide_workspace::roots::RootKind;
|
||||
let mut out: Vec<SourceFolder> = Vec::new();
|
||||
for (dir, kind) in ide_build::gradle_source_roots(root, build_cache, settings) {
|
||||
for (dir, kind, project) in ide_build::gradle_source_roots(root, build_cache, settings) {
|
||||
if !dir.is_dir() {
|
||||
continue;
|
||||
}
|
||||
@@ -2017,7 +2019,16 @@ fn with_gradle_roots(
|
||||
ReportedRoot::Excluded => RootKind::Excluded,
|
||||
};
|
||||
if !out.iter().any(|f| f.path == path) {
|
||||
out.push(SourceFolder { path, kind, detected_from: Some("Gradle".into()) });
|
||||
// `<module>/Gradle`, like the `<module>/build.gradle` static detection reports, so the
|
||||
// UI still finds the module after a sync. Projects outside the root stay `Gradle`:
|
||||
// the UI reads the folder as project-relative.
|
||||
let detected_from = match project.strip_prefix(root) {
|
||||
Ok(rel) if !rel.as_os_str().is_empty() => {
|
||||
format!("{}/Gradle", ide_workspace::roots::normalize(&rel.to_string_lossy()))
|
||||
}
|
||||
_ => "Gradle".into(),
|
||||
};
|
||||
out.push(SourceFolder { path, kind, detected_from: Some(detected_from) });
|
||||
}
|
||||
}
|
||||
out.extend(detected.iter().filter(|d| !out.iter().any(|o| o.path == d.path)).cloned().collect::<Vec<_>>());
|
||||
@@ -2397,6 +2408,48 @@ mod gradle_roots_tests {
|
||||
use super::*;
|
||||
use ide_workspace::RootKind;
|
||||
|
||||
#[test]
|
||||
fn gradle_sync_roots_keep_the_module_they_belong_to() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let cache = root.join(".cache");
|
||||
for d in [root.join("src/main/java"), root.join("lib/src/main/java"), root.join("lib/build"), cache.clone()] {
|
||||
std::fs::create_dir_all(d).unwrap();
|
||||
}
|
||||
std::fs::write(root.join("build.gradle"), "").unwrap();
|
||||
let s = |p: PathBuf| p.to_string_lossy().into_owned();
|
||||
let json = serde_json::json!({ "hash": "", "at_ms": 1.0, "error": null, "tasks": [], "projects": [
|
||||
{ "path": ":", "dir": s(root.clone()), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(root.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":lib", "dir": s(root.join("lib")), "buildDir": s(root.join("lib/build")), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(root.join("lib/src/main/java"))], "res": [] } ] },
|
||||
]});
|
||||
std::fs::write(cache.join("gradle.json"), json.to_string()).unwrap();
|
||||
// What static detection reports for this layout before the first sync.
|
||||
let detected = [
|
||||
SourceFolder {
|
||||
path: "src/main/java".into(),
|
||||
kind: RootKind::Source,
|
||||
detected_from: Some("build.gradle".into()),
|
||||
},
|
||||
SourceFolder {
|
||||
path: "lib/src/main/java".into(),
|
||||
kind: RootKind::Source,
|
||||
detected_from: Some("lib/build.gradle".into()),
|
||||
},
|
||||
];
|
||||
let out = with_gradle_roots(&root, &cache, &Default::default(), &detected);
|
||||
let got: Vec<_> = out.iter().map(|f| (f.path.as_str(), f.detected_from.as_deref())).collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
("src/main/java", Some("Gradle")),
|
||||
("lib/src/main/java", Some("lib/Gradle")),
|
||||
("lib/build", Some("lib/Gradle")),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradle_sync_roots_win_and_reach_outside_the_project() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -2420,14 +2473,15 @@ mod gradle_roots_tests {
|
||||
std::fs::write(root.join("build.gradle"), "").unwrap();
|
||||
let out = with_gradle_roots(&root, &cache, &Default::default(), &[guessed, other.clone()]);
|
||||
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
|
||||
let got: Vec<(String, RootKind)> = out.iter().map(|f| (f.path.clone(), f.kind)).collect();
|
||||
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.kind, f.detected_from.as_deref())).collect();
|
||||
// A project outside the root is not a module the UI could address.
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
("src/it/java".into(), RootKind::Test),
|
||||
(abs(svc.join("src/main/java")), RootKind::Source),
|
||||
(abs(svc.join("build")), RootKind::Excluded),
|
||||
("web".into(), RootKind::Source),
|
||||
("src/it/java".into(), RootKind::Test, Some("Gradle")),
|
||||
(abs(svc.join("src/main/java")), RootKind::Source, Some("Gradle")),
|
||||
(abs(svc.join("build")), RootKind::Excluded, Some("Gradle")),
|
||||
("web".into(), RootKind::Source, None),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -156,6 +156,7 @@ const SHELL_OWN: &[&str] = &["PWD", "OLDPWD", "SHLVL", "_"];
|
||||
pub(crate) fn read_login_env(shell: &str, timeout: std::time::Duration) -> Option<Vec<(OsString, OsString)>> {
|
||||
use std::io::Read;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::Instant;
|
||||
|
||||
@@ -182,6 +183,11 @@ pub(crate) fn read_login_env(shell: &str, timeout: std::time::Duration) -> Optio
|
||||
cmd.env_remove(k);
|
||||
}
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
// An interactive shell takes job control from its inherited terminal. A new session leaves it
|
||||
// without a controlling terminal, so it cannot stop its parent's process group with SIGTTIN.
|
||||
unsafe {
|
||||
cmd.pre_exec(|| rustix::process::setsid().map(|_| ()).map_err(Into::into));
|
||||
}
|
||||
let mut child = cmd
|
||||
.args(["-ilc", &format!("printf '{MARK}'; /usr/bin/env -0; printf '{MARK}'")])
|
||||
.stdin(Stdio::null())
|
||||
@@ -271,6 +277,36 @@ mod tests {
|
||||
assert_eq!(get(&third, "OPENIDEA_TEST_SEEN").as_deref(), Some("unset"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_shell_gets_a_new_session() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (shell, rc) = fake_shell(tmp.path());
|
||||
// macOS `ps` has no session id column; a session leader also leads its own process group.
|
||||
let column = if cfg!(target_os = "linux") { "sid" } else { "pgid" };
|
||||
std::fs::write(
|
||||
&rc,
|
||||
format!("export OPENIDEA_TEST_PID=$$\nexport OPENIDEA_TEST_SID=$(ps -o {column}= -p $$)\n"),
|
||||
)
|
||||
.unwrap();
|
||||
let env = read_login_env(&shell, Duration::from_secs(10)).unwrap();
|
||||
let get = |k: &str| {
|
||||
env.iter()
|
||||
.find(|(name, _)| name == k)
|
||||
.map(|(_, value)| value.to_string_lossy().trim().parse::<i32>().unwrap())
|
||||
.unwrap()
|
||||
};
|
||||
let shell_pid = get("OPENIDEA_TEST_PID");
|
||||
let shell_sid = get("OPENIDEA_TEST_SID");
|
||||
let test_sid = if cfg!(target_os = "linux") {
|
||||
rustix::process::getsid(None).unwrap().as_raw_nonzero().get()
|
||||
} else {
|
||||
rustix::process::getpgrp().as_raw_nonzero().get()
|
||||
};
|
||||
|
||||
assert_eq!(shell_sid, shell_pid);
|
||||
assert_ne!(shell_sid, test_sid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shell_that_hangs_times_out() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -2,6 +2,26 @@ mod common;
|
||||
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_moves_legacy_ssh_credentials_without_opening_a_project_or_connection() {
|
||||
use ide_ssh::secrets::testing::{files_containing, use_memory_store};
|
||||
|
||||
use_memory_store();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let config = common::host_config(tmp.path());
|
||||
std::fs::create_dir_all(&config.data_dir).unwrap();
|
||||
std::fs::write(config.data_dir.join("ssh-passwords.json"), r#"{"box":"legacy-fixture"}"#).unwrap();
|
||||
let host = Host::new(config);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
while !files_containing(tmp.path(), "legacy-fixture").is_empty() {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("startup migration");
|
||||
assert_eq!(host.ssh.password("box").as_deref(), Some("legacy-fixture"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn split_storage_keeps_user_history_and_uses_local_tools_and_caches() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
mod common;
|
||||
|
||||
use ide_build::compile::BuildEvent;
|
||||
use ide_core::RequestId;
|
||||
use ide_host::{Host, ops};
|
||||
use ide_run::BuildPolicy;
|
||||
use ide_workspace::{SettingsStore, settings::SettingsScope};
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
fn write(root: &Path, rel: &str, text: &str) {
|
||||
let path = root.join(rel);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
/// A Maven launch compiles with the IDE's Java build (javac, outputs in the project cache)
|
||||
/// and runs from its outputs. Needs `mvn` and a JDK (`JAVA_HOME`), else it is skipped.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn maven_launch_compiles_with_the_ides_java_build() {
|
||||
let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir());
|
||||
if !has_jdk || ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path()).is_none() {
|
||||
eprintln!("skipped: needs JAVA_HOME and mvn");
|
||||
return;
|
||||
}
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
write(
|
||||
&root,
|
||||
"pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
|
||||
<modules><module>lib</module><module>app</module></modules>
|
||||
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties></project>"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"lib/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"app/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
|
||||
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies></project>"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"lib/src/main/java/l/L.java",
|
||||
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"app/src/main/java/a/A.java",
|
||||
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
|
||||
);
|
||||
// No language server: the build tool compiles the launch.
|
||||
let global = SettingsStore::load(&base.join("config"), None);
|
||||
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
|
||||
global
|
||||
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
|
||||
.unwrap();
|
||||
}
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
let channel = ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event));
|
||||
let info = ops::java::java_resolve_launch(
|
||||
&host,
|
||||
"main",
|
||||
root.join("app"),
|
||||
false,
|
||||
false,
|
||||
BuildPolicy::Make,
|
||||
RequestId::next(),
|
||||
channel,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let steps: Vec<String> = events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
BuildEvent::Step { command, .. } => Some(command.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(steps.iter().any(|s| s.starts_with("javac lib")), "{steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("javac app")), "{steps:?}");
|
||||
assert!(!steps.iter().any(|s| s.contains("-am")), "{steps:?}");
|
||||
let first = Path::new(&info.class_paths[0]);
|
||||
assert!(first.ends_with("out/t.app/classes"), "{:?}", info.class_paths);
|
||||
assert!(first.join("a/A.class").is_file());
|
||||
assert!(info.class_paths.iter().any(|p| Path::new(p).ends_with("out/t.lib/classes")), "{:?}", info.class_paths);
|
||||
assert!(!root.join("app/target/classes").exists());
|
||||
|
||||
// Build › Build Project compiles with it too, and reports javac's errors.
|
||||
write(&root, "lib/src/main/java/l/L.java", "package l;\npublic class L { }\n");
|
||||
let built = ops::build::build_run(
|
||||
&host,
|
||||
"main",
|
||||
ide_build::compile::BuildKind::Build,
|
||||
None,
|
||||
None,
|
||||
RequestId::next(),
|
||||
Vec::new(),
|
||||
ops::Channel::new(|_: BuildEvent| {}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(built.system, ide_build::compile::BuildSystem::Javac);
|
||||
assert!(!built.success);
|
||||
assert_eq!(built.errors, 1, "{:?}", built.messages);
|
||||
assert!(built.messages[0].path.as_deref().is_some_and(|p| p.ends_with("a/A.java")), "{:?}", built.messages);
|
||||
assert!(!root.join("lib/target/classes").exists());
|
||||
host.shutdown().await;
|
||||
}
|
||||
|
||||
/// With Settings › Gradle › Build and run using: IDE, a Gradle launch and Build Project compile
|
||||
/// with the IDE's Java build too. Needs a JDK (`JAVA_HOME`) and Gradle (`OPENIDEA_TEST_GRADLE`).
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn gradle_launch_compiles_with_the_ides_java_build() {
|
||||
let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir());
|
||||
let Some(gradle) = std::env::var_os("OPENIDEA_TEST_GRADLE").filter(|_| has_jdk) else {
|
||||
eprintln!("skipped: needs JAVA_HOME and OPENIDEA_TEST_GRADLE");
|
||||
return;
|
||||
};
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
write(&root, "settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n");
|
||||
write(&root, "build.gradle", "subprojects {\n apply plugin: 'java'\n group = 't'\n}\n");
|
||||
write(&root, "lib/build.gradle", "");
|
||||
write(&root, "app/build.gradle", "dependencies { implementation project(':lib') }\n");
|
||||
write(&root, "gradlew", &format!("#!/bin/sh\nexec '{}' \"$@\"\n", Path::new(&gradle).display()));
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(root.join("gradlew"), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"lib/src/main/java/l/L.java",
|
||||
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"app/src/main/java/a/A.java",
|
||||
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
|
||||
);
|
||||
let global = SettingsStore::load(&base.join("config"), None);
|
||||
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
|
||||
global
|
||||
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
|
||||
.unwrap();
|
||||
}
|
||||
global.set(SettingsScope::Global, "languages.java.gradle.runUsing", serde_json::json!("ide")).unwrap();
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
let channel = ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event));
|
||||
let info = ops::java::java_resolve_launch(
|
||||
&host,
|
||||
"main",
|
||||
root.join("app"),
|
||||
false,
|
||||
false,
|
||||
BuildPolicy::Make,
|
||||
RequestId::next(),
|
||||
channel,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let steps: Vec<String> = events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
BuildEvent::Step { command, .. } => Some(command.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(steps.iter().any(|s| s.contains("openideaBuildModel")), "{steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("javac lib")), "{steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("javac app")), "{steps:?}");
|
||||
let first = Path::new(&info.class_paths[0]);
|
||||
assert!(first.ends_with("out/t.app/classes"), "{:?}", info.class_paths);
|
||||
assert!(first.join("a/A.class").is_file());
|
||||
assert!(info.class_paths.iter().any(|p| Path::new(p).ends_with("out/t.lib/classes")), "{:?}", info.class_paths);
|
||||
assert!(!root.join("app/build/classes").exists());
|
||||
|
||||
write(&root, "lib/src/main/java/l/L.java", "package l;\npublic class L { }\n");
|
||||
let built = ops::build::build_run(
|
||||
&host,
|
||||
"main",
|
||||
ide_build::compile::BuildKind::Build,
|
||||
None,
|
||||
None,
|
||||
RequestId::next(),
|
||||
Vec::new(),
|
||||
ops::Channel::new(|_: BuildEvent| {}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(built.system, ide_build::compile::BuildSystem::Javac);
|
||||
assert_eq!(built.errors, 1, "{:?}", built.messages);
|
||||
assert!(built.messages[0].path.as_deref().is_some_and(|p| p.ends_with("a/A.java")), "{:?}", built.messages);
|
||||
host.shutdown().await;
|
||||
}
|
||||
@@ -1572,7 +1572,7 @@ async fn a_run_started_without_confirmation_works_in_a_background_project_and_ho
|
||||
id: "serve".into(),
|
||||
name: "serve stock".into(),
|
||||
kind: "shell".into(),
|
||||
command: "sleep 30".into(),
|
||||
command: "cat".into(),
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: Default::default(),
|
||||
@@ -1598,11 +1598,11 @@ async fn a_run_started_without_confirmation_works_in_a_background_project_and_ho
|
||||
// The call still waits for the run: it holds the project first, the run second.
|
||||
let held = h.host.mcp_background.snapshot(&h.host, std::time::Instant::now()).remove(0);
|
||||
assert_eq!(held.kept_open_by, Some(ide_host::mcp::McpBackgroundHold::Request));
|
||||
h.host.processes.stop(run.id).unwrap();
|
||||
h.host.processes.close_stdin(run.id).unwrap();
|
||||
};
|
||||
let (result, ()) = tokio::join!(call, observe);
|
||||
let result: Value = serde_json::from_str(&result.unwrap()).unwrap();
|
||||
assert!(result["exitCode"].is_number() || result["exitCode"].is_null(), "{result}");
|
||||
assert_eq!(result["exitCode"], 0, "{result}");
|
||||
let loaded = h.host.mcp_background.snapshot(&h.host, std::time::Instant::now()).remove(0);
|
||||
assert_eq!(loaded.kept_open_by, None, "the call is over and the run has exited");
|
||||
}
|
||||
@@ -7010,6 +7010,31 @@ fn markdown_decorations_publish_a_hover_card_and_clear() {
|
||||
assert!(f.host.decoration_sets()["decorations"].is_empty());
|
||||
}
|
||||
|
||||
/// API 1.17: `set-styled` items carry their own colors, normalized by the host, and replace
|
||||
/// the set's earlier kind of items.
|
||||
#[test]
|
||||
fn styled_decorations_carry_normalized_colors() {
|
||||
let f = fixture(Limits::default());
|
||||
f.install(&sample("decorations"));
|
||||
f.run("decorations", "publish", Some("src/notes.txt")).unwrap();
|
||||
f.run("decorations", "styled", Some("src/notes.txt")).unwrap();
|
||||
let sets = f.host.decoration_sets();
|
||||
let set = &sets["decorations"][0];
|
||||
assert_eq!(set.set_id, "example");
|
||||
let colors: Vec<_> = set.items.iter().map(|d| (d.style.as_str(), d.colors.clone().unwrap())).collect();
|
||||
assert_eq!(
|
||||
colors,
|
||||
[
|
||||
(
|
||||
"",
|
||||
ide_plugin::DecorationColors { foreground: Some("#1a1a1a".into()), background: Some("#ffeb3b".into()) }
|
||||
),
|
||||
("", ide_plugin::DecorationColors { foreground: None, background: Some("#00e5ff80".into()) }),
|
||||
]
|
||||
);
|
||||
f.run("decorations", "clear", None).unwrap();
|
||||
}
|
||||
|
||||
// ─── Project window groups ────────────────────────────────────────────────────
|
||||
// A group's container root holds only `.openidea` metadata; the files live in
|
||||
// the member projects. The plugin surface reaches them like the editor and the
|
||||
|
||||
@@ -136,7 +136,8 @@ async fn ssh_server(home: &Path, server_home: &Path, project: &Path) -> Arc<ide_
|
||||
save_secret: true,
|
||||
..Default::default()
|
||||
}]);
|
||||
ssh.set_secret("local-test", Some("secret".into()), true);
|
||||
ide_ssh::secrets::testing::use_memory_store();
|
||||
ssh.set_secret("local-test", Some("secret".into()), true).unwrap();
|
||||
assert!(ssh.session("local-test").await.is_err(), "unknown host key first");
|
||||
ssh.trust_host("local-test").await.unwrap();
|
||||
ssh.session("local-test").await.unwrap()
|
||||
@@ -744,7 +745,18 @@ async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() {
|
||||
.unwrap();
|
||||
until("old backend socket", || guard.0.exists()).await;
|
||||
let old_open = || async {
|
||||
let mut stream = UnixStream::connect(&guard.0).await.unwrap();
|
||||
// bind() creates the socket file before listen(): a connect in between is refused.
|
||||
let mut stream = 'connect: {
|
||||
for _ in 0..600 {
|
||||
match UnixStream::connect(&guard.0).await {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::ConnectionRefused => {
|
||||
tokio::time::sleep(Duration::from_millis(15)).await;
|
||||
}
|
||||
other => break 'connect other.unwrap(),
|
||||
}
|
||||
}
|
||||
panic!("the old backend never accepted a connection");
|
||||
};
|
||||
stream.write_all(OLD_BUILD.as_bytes()).await.unwrap();
|
||||
assert_eq!(stream.read_u8().await.unwrap(), b'A');
|
||||
let (reader, writer) = stream.into_split();
|
||||
|
||||
@@ -308,6 +308,18 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
assert!(found.iter().any(|d| d["type"] == "file"), "{found:?}");
|
||||
assert_eq!(found.last().unwrap()["type"], "done");
|
||||
|
||||
// HTTP Client requests and their history are served by the project host.
|
||||
let history = invoke(&peer, "http_history", json!({})).await.unwrap();
|
||||
assert_eq!(history, json!([]));
|
||||
let curl = invoke(
|
||||
&peer,
|
||||
"http_curl",
|
||||
json!({ "path": null, "text": "GET http://localhost/x\n", "index": 0, "env": null }),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(curl.as_str().unwrap().contains("http://localhost/x"), "{curl}");
|
||||
|
||||
// A run's output streams through a channel and its exit is an event.
|
||||
let config = json!({ "id": "echo", "name": "echo", "kind": "shell", "command": "echo", "args": ["remote-hi"],
|
||||
"cwd": null, "env": {}, "detected": false, "isTest": false, "debugAdapter": null });
|
||||
@@ -371,6 +383,14 @@ async fn local_deployment_runs_on_the_project_host() {
|
||||
"remote_mkdir",
|
||||
"remote_rename",
|
||||
"remote_download_into",
|
||||
"http_environments",
|
||||
"http_execute",
|
||||
"http_history",
|
||||
"http_history_get",
|
||||
"http_history_clear",
|
||||
"http_curl",
|
||||
"http_environment_file",
|
||||
"http_variable_definitions",
|
||||
"db_sources",
|
||||
"db_save_sources",
|
||||
"db_set_password",
|
||||
@@ -387,6 +407,7 @@ async fn local_deployment_runs_on_the_project_host() {
|
||||
"db_schemas",
|
||||
"db_tables",
|
||||
"db_table_details",
|
||||
"db_table_grants",
|
||||
"db_ddl",
|
||||
"db_schema_objects",
|
||||
"db_object_ddl",
|
||||
|
||||
@@ -10,6 +10,30 @@ use std::path::Path;
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_credential_save_warns_the_window_but_keeps_the_session_password() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let config = common::host_config(tmp.path());
|
||||
std::fs::create_dir_all(config.data_dir.join("ssh-passwords.json")).unwrap();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let host = Host::new(HostConfig {
|
||||
sink_for: Box::new(move |_| {
|
||||
let tx = tx.clone();
|
||||
Arc::new(move |e| tx.send(e).unwrap())
|
||||
}),
|
||||
..config
|
||||
});
|
||||
ide_host::ops::ssh::ssh_set_secret(&host, "main", "box".into(), Some("test-value".into()), true);
|
||||
let warning = rx.try_iter().find_map(|e| match e {
|
||||
IdeEvent::Notify { level: ide_core::event::NotifyLevel::Warning, body, .. } => body,
|
||||
_ => None,
|
||||
});
|
||||
let warning = warning.expect("the window should be told saving failed");
|
||||
assert!(warning.contains("session only"));
|
||||
assert!(!warning.contains("test-value"));
|
||||
assert_eq!(host.ssh.password("box").as_deref(), Some("test-value"));
|
||||
}
|
||||
|
||||
fn read_until(rx: &mpsc::Receiver<String>, needle: &str) -> String {
|
||||
let mut all = String::new();
|
||||
while !all.contains(needle) {
|
||||
@@ -38,7 +62,8 @@ async fn host_with_ssh_box(tmp: &Path, exec: ide_ssh::testing::ExecFn) -> (Arc<H
|
||||
save_secret: true,
|
||||
..Default::default()
|
||||
}]);
|
||||
ssh.set_secret("box", Some("secret".into()), true);
|
||||
ide_ssh::secrets::testing::use_memory_store();
|
||||
ssh.set_secret("box", Some("secret".into()), true).unwrap();
|
||||
assert!(ssh.session("box").await.is_err(), "unknown host key first");
|
||||
ssh.trust_host("box").await.unwrap();
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ async fn welcome_window_browses_selected_ssh_host_without_executing_commands() {
|
||||
auth: SshAuth::Password,
|
||||
..Default::default()
|
||||
}]);
|
||||
ssh.set_secret("selected-host", Some("secret".into()), false);
|
||||
ssh.set_secret("selected-host", Some("secret".into()), false).unwrap();
|
||||
assert!(ssh.session("selected-host").await.is_err());
|
||||
ssh.trust_host("selected-host").await.unwrap();
|
||||
|
||||
|
||||
@@ -88,10 +88,18 @@ done
|
||||
let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
let channel = ops::Channel::new(move |event: ide_build::compile::BuildEvent| sink.lock().unwrap().push(event));
|
||||
let info =
|
||||
ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next(), channel)
|
||||
.await
|
||||
.unwrap();
|
||||
let info = ops::java::java_resolve_launch(
|
||||
&host,
|
||||
"main",
|
||||
module,
|
||||
test,
|
||||
false,
|
||||
BuildPolicy::Make,
|
||||
RequestId::next(),
|
||||
channel,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// The build streams its command and progress while it runs.
|
||||
use ide_build::compile::BuildEvent;
|
||||
let events = events.lock().unwrap();
|
||||
@@ -110,7 +118,9 @@ done
|
||||
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
|
||||
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == jar));
|
||||
let calls = fs::read_to_string(root.join("calls")).unwrap();
|
||||
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
|
||||
// This Maven records no build model for the IDE's Java build, so Maven builds the module.
|
||||
assert!(calls.lines().next().unwrap().contains("-Dopenidea.build.model="), "{calls}");
|
||||
assert!(calls.lines().nth(1).unwrap().contains("-pl app -am"), "{calls}");
|
||||
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
|
||||
assert!(calls.contains(":build-classpath"), "{calls}");
|
||||
}
|
||||
|
||||
@@ -378,6 +378,23 @@ fn binary_and_huge_files_are_listed_without_symbols() {
|
||||
assert_eq!(idx.status().symbols, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_files_are_classified_from_their_head_and_text_is_read_past_it() {
|
||||
let fx = Fixture::new(&[("img/logo.rs", "")]);
|
||||
let mut binary = b"fn head() {}\0".to_vec();
|
||||
binary.extend(std::iter::repeat_n(b'x', 64 * 1024));
|
||||
std::fs::write(fx.root.join("img/logo.rs"), &binary).unwrap();
|
||||
let long = format!("{}fn past_the_sniff() {{}}\n", "// pad\n".repeat(2000));
|
||||
assert!(long.len() > 8192);
|
||||
fx.write("src/long.rs", &long);
|
||||
let idx = fx.open();
|
||||
assert_eq!(symbols(&idx, "past_the_sniff", SymbolFilter::All), vec!["past_the_sniff"]);
|
||||
assert!(symbols(&idx, "head", SymbolFilter::All).is_empty());
|
||||
let data = idx.shared.data.read();
|
||||
let logo = data.files.iter().flatten().find(|entry| entry.rel.as_ref() == "img/logo.rs").unwrap();
|
||||
assert_eq!(logo.hash, [0; 32], "a binary file is not read whole to be hashed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_to_file_finds_ignored_files_but_not_their_symbols() {
|
||||
let fx = Fixture::new(&[
|
||||
|
||||
@@ -29,6 +29,8 @@ static INDEX_POOL: LazyLock<rayon::ThreadPool> = LazyLock::new(|| {
|
||||
|
||||
/// Files larger than this are listed but not parsed for symbols.
|
||||
pub const MAX_SYMBOL_FILE: u64 = 2 * 1024 * 1024;
|
||||
/// Leading bytes checked for NUL to tell a binary file from text.
|
||||
const BINARY_SNIFF: usize = 8192;
|
||||
const CHUNK: usize = 512;
|
||||
/// Insert/persist batch of the initial scan's streaming pass.
|
||||
const SCAN_BATCH: usize = 2048;
|
||||
@@ -180,7 +182,7 @@ impl Shared {
|
||||
let snapshot_started = Instant::now();
|
||||
let fast = self.try_fast_start();
|
||||
let snapshot_elapsed = snapshot_started.elapsed();
|
||||
if !fast {
|
||||
if let Err(reason) = fast {
|
||||
let snapshot_guard = SystemTime::now();
|
||||
let walk_started = Instant::now();
|
||||
let found = self.walk_roots(None);
|
||||
@@ -192,6 +194,7 @@ impl Shared {
|
||||
if !self.is_cancelled() {
|
||||
tracing::info!(
|
||||
mode = "fallback",
|
||||
reason,
|
||||
snapshot_attempt_ms = snapshot_elapsed.as_millis() as u64,
|
||||
walk_ms = walk_elapsed.as_millis() as u64,
|
||||
hydration_ms = hydration_elapsed.as_millis() as u64,
|
||||
@@ -259,25 +262,26 @@ impl Shared {
|
||||
|
||||
/// Warm start: validate the snapshot's flat directory/file manifest and hydrate
|
||||
/// without walking the tree. A changed scope, symlink, directory mtime, file
|
||||
/// mtime or file size falls back to the full walk.
|
||||
fn try_fast_start(&self) -> bool {
|
||||
/// mtime or file size falls back to the full walk; the error says which, for
|
||||
/// the start-up log.
|
||||
fn try_fast_start(&self) -> Result<(), &'static str> {
|
||||
let started = Instant::now();
|
||||
let Some(store) = &self.store else { return false };
|
||||
let Some(store) = &self.store else { return Err("no cache") };
|
||||
let load_started = Instant::now();
|
||||
let Some(snapshot) = store.load_snapshot() else { return false };
|
||||
let Some(snapshot) = store.load_snapshot() else { return Err("no snapshot for this build") };
|
||||
let loaded = load_started.elapsed();
|
||||
let filter = self.filter();
|
||||
if filter.has_extra_roots() || snapshot.filter() != filter.stamp() {
|
||||
return false;
|
||||
return Err("index scope changed");
|
||||
}
|
||||
let root = filter.root();
|
||||
let validation_started = Instant::now();
|
||||
for i in 0..snapshot.dirs_len() {
|
||||
let rel = snapshot.dir(i);
|
||||
let path = if rel.is_empty() { root.to_owned() } else { root.join(rel) };
|
||||
let Ok(meta) = std::fs::symlink_metadata(&path) else { return false };
|
||||
let Ok(meta) = std::fs::symlink_metadata(&path) else { return Err("directory changed") };
|
||||
if !meta.is_dir() || mtime_of(&meta) != snapshot.dir_mtime(i) {
|
||||
return false;
|
||||
return Err("directory changed");
|
||||
}
|
||||
}
|
||||
let external = crate::store::external_ignore_candidates(root);
|
||||
@@ -288,19 +292,19 @@ impl Shared {
|
||||
if external.len() != saved_external.len()
|
||||
|| external.iter().zip(&saved_external).any(|(path, saved)| path.to_string_lossy() != **saved)
|
||||
{
|
||||
return false;
|
||||
return Err("ignore files changed");
|
||||
}
|
||||
for i in 0..snapshot.ignore_len() {
|
||||
let path = Path::new(snapshot.ignore_path(i));
|
||||
let meta = std::fs::metadata(path).ok();
|
||||
let present = meta.is_some();
|
||||
if present != snapshot.ignore_present(i) {
|
||||
return false;
|
||||
return Err("ignore files changed");
|
||||
}
|
||||
if let Some(meta) = meta
|
||||
&& (mtime_of(&meta) != snapshot.ignore_mtime(i) || meta.len() != snapshot.ignore_size(i))
|
||||
{
|
||||
return false;
|
||||
return Err("ignore files changed");
|
||||
}
|
||||
}
|
||||
let validation_elapsed = validation_started.elapsed();
|
||||
@@ -320,7 +324,7 @@ impl Shared {
|
||||
});
|
||||
let built = build_started.elapsed();
|
||||
if entries.iter().any(Option::is_none) {
|
||||
return false;
|
||||
return Err("file changed");
|
||||
}
|
||||
let validated = entries;
|
||||
let mut entries = Vec::with_capacity(validated.len());
|
||||
@@ -372,7 +376,7 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
r.truncate(MAX_RECENT);
|
||||
true
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_recent(&self, store: &Store, root: &Path) {
|
||||
@@ -902,22 +906,32 @@ impl Shared {
|
||||
if f.size > MAX_SYMBOL_FILE {
|
||||
return Extracted::New(rec, Extraction::Oversized);
|
||||
}
|
||||
// Sniff the head first: a binary file is classified from its first
|
||||
// `BINARY_SNIFF` bytes alone, so it is never read whole or hashed.
|
||||
let mut bytes = Vec::with_capacity(f.size as usize);
|
||||
match std::fs::File::open(&f.path).and_then(|mut file| file.read_to_end(&mut bytes)) {
|
||||
Ok(_) => {}
|
||||
let read = std::fs::File::open(&f.path).and_then(|mut file| {
|
||||
(&mut file).take(BINARY_SNIFF as u64).read_to_end(&mut bytes)?;
|
||||
if bytes.contains(&0) {
|
||||
return Ok(true);
|
||||
}
|
||||
file.read_to_end(&mut bytes).map(|_| false)
|
||||
});
|
||||
let binary = match read {
|
||||
Ok(binary) => binary,
|
||||
Err(e) => {
|
||||
tracing::debug!("index: cannot read {}: {e}", f.path.display());
|
||||
return Extracted::New(rec, Extraction::ReadFailed);
|
||||
}
|
||||
};
|
||||
if binary {
|
||||
self.parsed.fetch_add(1, Ordering::Relaxed);
|
||||
return Extracted::New(rec, Extraction::Binary);
|
||||
}
|
||||
rec.hash = *blake3::hash(&bytes).as_bytes();
|
||||
if prev_hash == Some(rec.hash) {
|
||||
return Extracted::Unchanged;
|
||||
}
|
||||
self.parsed.fetch_add(1, Ordering::Relaxed);
|
||||
if bytes[..bytes.len().min(8192)].contains(&0) {
|
||||
return Extracted::New(rec, Extraction::Binary);
|
||||
}
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
let lang = self.languages.detect(&f.path, Some(first_line(&text)));
|
||||
if self.syntax.has_symbols(&lang) {
|
||||
@@ -1462,7 +1476,7 @@ mod metric_tests {
|
||||
}
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
assert!(index.try_fast_start());
|
||||
assert_eq!(index.try_fast_start(), Ok(()));
|
||||
assert_eq!(index.parsed.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(index.data.read().file_count, 1);
|
||||
assert_eq!(index.data.read().symbol_count, 1);
|
||||
|
||||
@@ -342,6 +342,27 @@ impl Drop for JavaExternalBuild {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Gradle tooling API's own messages for a build that failed, ahead of its cause.
|
||||
const GRADLE_TOOLING_FAILURES: [&str; 4] = [
|
||||
"The supplied phased action failed with an exception",
|
||||
"Could not run phased build action",
|
||||
"Could not run build action",
|
||||
"Could not fetch model of type",
|
||||
];
|
||||
|
||||
/// A diagnostic's message on one line. Buildship marks a Gradle project whose sync failed with
|
||||
/// the tooling API's message on the first line and the build's own error last ("… failed with
|
||||
/// an exception.\nA problem occurred evaluating root project 'app'.\n<the error>"); that error is
|
||||
/// kept as the cause.
|
||||
fn launch_message(message: &str) -> String {
|
||||
let mut lines = message.lines().map(str::trim).filter(|l| !l.is_empty());
|
||||
let first = lines.next().unwrap_or_default();
|
||||
match lines.next_back() {
|
||||
Some(cause) if GRADLE_TOOLING_FAILURES.iter().any(|m| first.contains(m)) => format!("{first} Cause: {cause}"),
|
||||
_ => first.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Error diagnostics sorted by file and position, capped at `limit`, and their total.
|
||||
pub fn compile_errors(
|
||||
diagnostics: Vec<(PathBuf, lsp_types::Diagnostic)>,
|
||||
@@ -354,7 +375,7 @@ pub fn compile_errors(
|
||||
path: path.into(),
|
||||
line: d.range.start.line + 1,
|
||||
column: d.range.start.character + 1,
|
||||
message: d.message.lines().next().unwrap_or_default().to_owned(),
|
||||
message: launch_message(&d.message),
|
||||
})
|
||||
.collect();
|
||||
errors.sort_by(|a, b| (&a.path, a.line, a.column).cmp(&(&b.path, b.line, b.column)));
|
||||
@@ -535,7 +556,8 @@ fn build_file_errors(diagnostics: &[(PathBuf, lsp_types::Diagnostic)], root: &Pa
|
||||
&& path.parent().is_some_and(|dir| module.starts_with(dir))
|
||||
})
|
||||
.map(|(path, d)| {
|
||||
let message = d.message.lines().next().unwrap_or_default().trim().trim_end_matches(':');
|
||||
let message = launch_message(&d.message);
|
||||
let message = message.trim().trim_end_matches(':');
|
||||
(path.components().count(), format!("{}: {message}", path.strip_prefix(root).unwrap_or(path).display()))
|
||||
})
|
||||
.collect();
|
||||
@@ -1638,6 +1660,24 @@ mod tests {
|
||||
assert_eq!(std::fs::read_to_string(prefs).unwrap(), format!("{}=error\n", ACCESS_OPTIONS[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_gradle_sync_keeps_its_cause_on_one_line() {
|
||||
let marker = "The supplied phased action failed with an exception.\n\
|
||||
A problem occurred configuring root project 'app'.\n\
|
||||
A problem occurred evaluating root project 'app'.\n\
|
||||
missing generated schema";
|
||||
assert_eq!(
|
||||
launch_message(marker),
|
||||
"The supplied phased action failed with an exception. Cause: missing generated schema"
|
||||
);
|
||||
assert_eq!(
|
||||
launch_message("The supplied phased action failed with an exception."),
|
||||
"The supplied phased action failed with an exception."
|
||||
);
|
||||
// Other messages keep their first line only.
|
||||
assert_eq!(launch_message("x cannot be resolved\nmore detail"), "x cannot be resolved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn access_warnings_do_not_hide_real_compile_errors() {
|
||||
let path = PathBuf::from("src/Main.java");
|
||||
|
||||
@@ -1188,3 +1188,107 @@ async fn phoxite_pulls_a_member_up_end_to_end() {
|
||||
assert!(!refused.message.is_empty() && !refused.message.starts_with("phoxite:"), "{refused:?}");
|
||||
mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
/// jdtls keeps building incrementally even though the IDE's Java build compiles what runs:
|
||||
/// its build is what reports an API change in one Maven module in the files of the modules
|
||||
/// that use it, open or not. With `java.autobuild.enabled: false` (and
|
||||
/// `validateAllOpenBuffersOnChanges`), neither updates.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires jdtls on PATH (or OPENIDEA_TEST_JDTLS) and a compatible JDK"]
|
||||
async fn jdtls_build_reports_cross_module_errors_in_open_and_closed_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap().join("project");
|
||||
let write = |rel: &str, text: &str| {
|
||||
let path = root.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, text).unwrap();
|
||||
path
|
||||
};
|
||||
let parent = r#"<parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent>"#;
|
||||
write(
|
||||
"pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging><modules><module>lib</module><module>app</module></modules><properties><maven.compiler.release>11</maven.compiler.release></properties></project>"#,
|
||||
);
|
||||
write(
|
||||
"lib/pom.xml",
|
||||
&format!("<project><modelVersion>4.0.0</modelVersion>{parent}<artifactId>lib</artifactId></project>"),
|
||||
);
|
||||
write(
|
||||
"app/pom.xml",
|
||||
&format!(
|
||||
"<project><modelVersion>4.0.0</modelVersion>{parent}<artifactId>app</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies></project>"
|
||||
),
|
||||
);
|
||||
let lib_source = "package l;\npublic class L { public static String name() { return \"lib\"; } }\n";
|
||||
let app_source = "package a;\npublic class A { String s = l.L.name(); }\n";
|
||||
let lib = write("lib/src/main/java/l/L.java", lib_source);
|
||||
let app = write("app/src/main/java/a/A.java", app_source);
|
||||
let closed = write("app/src/main/java/a/B.java", "package a;\nclass B { String s = l.L.name(); }\n");
|
||||
let mut java = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("java")).unwrap();
|
||||
java.language_servers.retain(|s| s.name == "jdtls");
|
||||
let server = &mut java.language_servers[0];
|
||||
if let Ok(bin) = std::env::var("OPENIDEA_TEST_JDTLS") {
|
||||
server.command = bin;
|
||||
}
|
||||
server.args.extend(["-data".into(), dir.path().join("jdtls-data").to_string_lossy().into_owned()]);
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![java]));
|
||||
let (lib_doc, app_doc) = (DocId::next(), DocId::next());
|
||||
mgr.did_open(lib_doc, &lib, &LanguageId::new("java"), 1, lib_source);
|
||||
mgr.did_open(app_doc, &app, &LanguageId::new("java"), 1, app_source);
|
||||
let errors = |path: &Path| {
|
||||
events.lock().iter().rev().find_map(|e| match e {
|
||||
IdeEvent::Diagnostics { path: p, items, .. } if p.0 == path => Some(
|
||||
items
|
||||
.iter()
|
||||
.filter(|d| d.severity == ide_core::Severity::Error)
|
||||
.map(|d| d.message.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
// The import resolves `lib` from source: the open editor of `app` has no errors.
|
||||
retry("app imported", Duration::from_secs(300), || {
|
||||
let status = last_status(&events, "jdtls");
|
||||
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, message)) = &status {
|
||||
panic!("jdtls failed: {message:?}");
|
||||
}
|
||||
let clean = errors(&app).is_some_and(|e| e.is_empty());
|
||||
let mgr = mgr.clone();
|
||||
let app = app.clone();
|
||||
async move {
|
||||
let cp =
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.java_classpath(&app, false, &Default::default()))
|
||||
.await
|
||||
.ok()?
|
||||
.ok()?;
|
||||
(clean && cp.class_paths.iter().any(|p| p.contains("/lib/"))).then_some(())
|
||||
}
|
||||
})
|
||||
.await;
|
||||
// Rename the method in the editor of `lib`, and save.
|
||||
let renamed = lib_source.replace("name()", "title()");
|
||||
let line = lib_source.lines().nth(1).unwrap();
|
||||
mgr.did_change(
|
||||
lib_doc,
|
||||
2,
|
||||
&[AppliedChange {
|
||||
range: Range::new(Pos::new(1, 0), Pos::new(1, line.len() as u32)),
|
||||
text: renamed.lines().nth(1).unwrap().to_owned(),
|
||||
}],
|
||||
&|| renamed.clone(),
|
||||
);
|
||||
std::fs::write(&lib, &renamed).unwrap();
|
||||
mgr.did_save(lib_doc, &renamed);
|
||||
retry("the open editor of app reports the removed method", Duration::from_secs(120), || {
|
||||
let found = errors(&app).is_some_and(|e| e.iter().any(|m| m.contains("name()")));
|
||||
async move { found.then_some(()) }
|
||||
})
|
||||
.await;
|
||||
retry("the closed file of app reports it too", Duration::from_secs(60), || {
|
||||
let found = errors(&closed).is_some_and(|e| e.iter().any(|m| m.contains("name()")));
|
||||
async move { found.then_some(()) }
|
||||
})
|
||||
.await;
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
@@ -59,7 +59,7 @@ use views_bindings::exports::openidea::plugin::view_provider as wit_view;
|
||||
use views_bindings::openidea::plugin::view_types as wit_vt;
|
||||
|
||||
/// The API version of the world above, `major.minor` of [`host_api`].
|
||||
pub const API_VERSION: &str = "1.16";
|
||||
pub const API_VERSION: &str = "1.17";
|
||||
const EPOCH_TICK: Duration = Duration::from_millis(10);
|
||||
pub(crate) const MAX_TEXT: usize = 1 << 20;
|
||||
/// The most text, and the most PNG bytes, `ui.read-clipboard` returns.
|
||||
|
||||
@@ -1023,6 +1023,15 @@ pub struct Decoration {
|
||||
/// Markdown rendered in the editor's hover card (API 1.16); `hover` is the
|
||||
/// plain-text fallback shown when this is absent.
|
||||
pub markdown_hover: Option<String>,
|
||||
/// The item's own colors (API 1.17 `set-styled`), validated `#rrggbb` / `#rrggbbaa`.
|
||||
#[serde(default)]
|
||||
pub colors: Option<DecorationColors>,
|
||||
}
|
||||
/// Colors of a styled editor decoration (API 1.17).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
pub struct DecorationColors {
|
||||
pub foreground: Option<String>,
|
||||
pub background: Option<String>,
|
||||
}
|
||||
/// A tree decoration.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -2888,6 +2888,7 @@ impl bindings::openidea::plugin::decorations::Host for StoreData {
|
||||
hover: d.hover,
|
||||
after: d.after,
|
||||
markdown_hover: None,
|
||||
colors: None,
|
||||
})
|
||||
.collect();
|
||||
self.replace_decorations(path, set_id, items)
|
||||
@@ -2906,6 +2907,28 @@ impl bindings::openidea::plugin::decorations::Host for StoreData {
|
||||
hover: d.hover,
|
||||
after: d.after,
|
||||
markdown_hover: d.markdown_hover,
|
||||
colors: None,
|
||||
})
|
||||
.collect();
|
||||
self.replace_decorations(path, set_id, items)
|
||||
}
|
||||
fn set_styled(
|
||||
&mut self,
|
||||
path: String,
|
||||
set_id: String,
|
||||
items: Vec<bindings::openidea::plugin::decorations::StyledDecoration>,
|
||||
) -> Fallible<()> {
|
||||
let items = items
|
||||
.into_iter()
|
||||
.map(|d| crate::Decoration {
|
||||
range: core_range(d.range),
|
||||
style: d.style,
|
||||
hover: d.hover,
|
||||
after: d.after,
|
||||
markdown_hover: d.markdown_hover,
|
||||
colors: d
|
||||
.colors
|
||||
.map(|c| crate::DecorationColors { foreground: c.foreground, background: c.background }),
|
||||
})
|
||||
.collect();
|
||||
self.replace_decorations(path, set_id, items)
|
||||
|
||||
@@ -95,7 +95,7 @@ fn the_sdk_carries_the_hosts_wit() {
|
||||
|
||||
#[test]
|
||||
fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
let host = v("1.16.0");
|
||||
let host = v("1.17.0");
|
||||
for ok in [
|
||||
"1.0.0",
|
||||
"1.3.0",
|
||||
@@ -112,15 +112,16 @@ fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
"1.14.0",
|
||||
"1.15.0",
|
||||
"1.16.0",
|
||||
"1.17.0",
|
||||
"1.0.0-rc.1",
|
||||
] {
|
||||
assert_eq!(check_api(&v(ok), &host), Ok(()), "{ok}");
|
||||
}
|
||||
let newer = check_api(&v("1.17.0"), &host).unwrap_err();
|
||||
assert!(newer.contains("1.17") && newer.contains("update OpenIDEA"), "{newer}");
|
||||
let newer = check_api(&v("1.18.0"), &host).unwrap_err();
|
||||
assert!(newer.contains("1.18") && newer.contains("update OpenIDEA"), "{newer}");
|
||||
assert!(check_api(&v("2.0.0"), &host).unwrap_err().contains("update OpenIDEA"));
|
||||
let older = check_api(&v("0.2.0"), &host).unwrap_err();
|
||||
assert!(older.contains("rebuild it with the 1.16 SDK"), "{older}");
|
||||
assert!(older.contains("rebuild it with the 1.17 SDK"), "{older}");
|
||||
// 0.x: every minor is its own API.
|
||||
assert_eq!(check_api(&v("0.2.0"), &v("0.2.5")), Ok(()));
|
||||
assert!(check_api(&v("0.1.0"), &v("0.2.0")).is_err());
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
68517d169bea40ca5a5426a3a05ace3389417073b9369e79157a2beb051dcfc0
|
||||
98e9c2b886df177bafb68a712fc1efadc4f3a7b82e8425cd1b3f4c2355bdb785
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
6edda84fad0ee7cd56a3a28b55e6c559db7b7f6b9c8c0ca645be805b545c01e7
|
||||
bb77bc0963451ca4259591bf68c72ae3eb70b1c6f855fa29dfc84d2be675404c
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
ecc6b6c52753b11521ae033a5a66c2a289119e09e07d22742203d3a13122dd97
|
||||
f381b0e20520bccf5acd46b95641f5542885184352e52ec2fed3fd53665c353b
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
4ec581c69a62bbf424983e241a79d0bfdb5d025a3e86d27eea745adcb1906253
|
||||
f72a53e7b800b8c5408c7ac67034821f814da7b1d66f527949450431bcf52e02
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
5fb89ee3d07e4275433ad9ad930ad781ef4f227af11aa5eb9dfc9174c015b1b8
|
||||
3cd2f02738b07d9a6294025cbcc6e906716d3e91db50a6f39485df9b1d6a4ead
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
236db5a85d3e7e9fee01c3ff0b9f5e66fad7e3d64fa618a0c1c980d9e5883839
|
||||
d77b80884163628791b292acc59324d3b9a7c2236034b88f87e8f56af5929a48
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
4f89bd09b571016cbb9feb0674e668aa66996997c6b53a91d1a4ffbf161083a3
|
||||
5a79d35e9fc1560a39b6459312a14c27c73739fd385f6c2568f9b1c1bf8fe4a1
|
||||
@@ -1,10 +1,10 @@
|
||||
id = "decorations"
|
||||
name = "Decoration example"
|
||||
version = "0.1.0"
|
||||
description = "Minimal plugin API 1.16 example: line-end labels with Markdown hover cards."
|
||||
description = "Minimal plugin API 1.17 example: line-end labels with Markdown hover cards and their own colors."
|
||||
authors = ["OpenIDEA contributors"]
|
||||
license = "Apache-2.0"
|
||||
engines.openidea = "^1.16"
|
||||
engines.openidea = "^1.17"
|
||||
wasm = "dist/plugin.wasm"
|
||||
activation = ["on-command:*"]
|
||||
|
||||
@@ -15,6 +15,10 @@ required = ["project.read"]
|
||||
id = "publish"
|
||||
title = "Decorations: Publish"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "styled"
|
||||
title = "Decorations: Publish Styled"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "clear"
|
||||
title = "Decorations: Clear"
|
||||
Loaded 100 of 745 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача