дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 04:56:08 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
cf6e640ac0 | ||
|
|
43c88c9512 | ||
|
|
5c0a5239fa | ||
|
|
f8d6f9df77 | ||
|
|
0c54266d03 | ||
|
|
1716f3e062 | ||
|
|
482241ebb9 | ||
|
|
7c72411dd7 | ||
|
|
376501a5fe | ||
|
|
21925b7f4b | ||
|
|
1e898367a5 | ||
|
|
7a58d9f253 | ||
|
|
ad80e903e3 | ||
|
|
9847fd2c01 | ||
|
|
fa26ba842c | ||
|
|
16033c481b | ||
|
|
2c3eabb786 | ||
|
|
c938d712b5 | ||
|
|
7cf4f7948d | ||
|
|
b281447da8 | ||
|
|
1e913c2334 | ||
|
|
52cb592692 | ||
|
|
bbaf2c89a0 | ||
|
|
6456f0e404 | ||
|
|
c3d569d3e3 | ||
|
|
0458424f9c | ||
|
|
4395975664 | ||
|
|
0bf597c2fd | ||
|
|
95e79116d1 | ||
|
|
cde74394d7 | ||
|
|
9ca65b4df6 | ||
|
|
2841f97145 | ||
|
|
0be97c4323 | ||
|
|
0411a5b08a | ||
|
|
f48cd85d0b | ||
|
|
9e35cfc064 | ||
|
|
0a71f6be88 | ||
|
|
b3c3150489 | ||
|
|
1d937d52e5 | ||
|
|
5f57ce962e | ||
|
|
95b45c095d | ||
|
|
9dc736de09 | ||
|
|
369c63979d | ||
|
|
347e3525d2 | ||
|
|
5280c9e584 | ||
|
|
67cad01ba7 | ||
|
|
ad92b1577f | ||
|
|
06109aae95 | ||
|
|
b2d1188049 | ||
|
|
5329ddc469 | ||
|
|
2faa64fb68 | ||
|
|
d6f6525ca5 |
No files matched your search
Створено
+41
-35
@@ -4038,7 +4038,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4061,7 +4061,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4075,7 +4075,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4090,7 +4090,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
@@ -4099,7 +4099,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4115,7 +4115,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4129,7 +4129,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -4147,7 +4147,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"bb8",
|
||||
"dirs 6.0.0",
|
||||
@@ -4169,7 +4169,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4183,18 +4183,19 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4208,7 +4209,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4253,7 +4254,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4271,7 +4272,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4293,7 +4294,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4309,7 +4310,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4364,7 +4365,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4388,7 +4389,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4411,7 +4412,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4429,7 +4430,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4442,7 +4443,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"globset",
|
||||
"ide-core",
|
||||
@@ -4459,7 +4460,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4482,7 +4483,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4501,7 +4502,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"globset",
|
||||
@@ -4521,7 +4522,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4534,7 +4535,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4553,7 +4554,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4568,7 +4569,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4581,7 +4582,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4593,7 +4594,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4614,7 +4615,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4633,7 +4634,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4655,7 +4656,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"open",
|
||||
@@ -4671,7 +4672,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6141,9 +6142,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"block2 0.6.2",
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
"ide-agent",
|
||||
@@ -6180,6 +6182,10 @@ dependencies = [
|
||||
"ide-vfs",
|
||||
"ide-web",
|
||||
"ide-workspace",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-web-kit 0.3.2",
|
||||
"parking_lot",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
# Third-party licenses
|
||||
|
||||
## Project Lombok
|
||||
|
||||
`plugins/lombok/lombok-1.18.48-openidea.1.jar` contains Project Lombok v1.18.48 with the Equinox
|
||||
classloader fix from [projectlombok/lombok#4059](https://github.com/projectlombok/lombok/pull/4059).
|
||||
Copyright (C) 2009-2021 The Project Lombok Authors. MIT license and bundled component
|
||||
notices are retained in [plugins/lombok/LICENSE](plugins/lombok/LICENSE) and inside the jar.
|
||||
Source tag, patch commits and build instructions: [plugins/lombok/README.md](plugins/lombok/README.md).
|
||||
|
||||
## JetBrains IntelliJ Platform icons
|
||||
|
||||
`src/ui/expui/**` contains SVG icons from the IntelliJ Platform "new UI" (expui)
|
||||
@@ -27,6 +35,20 @@ icon set, copied unmodified (some renamed) from JetBrains' open-source repositor
|
||||
`fileTypes/hashiCorp`, Apache-2.0); `makefile` (`expui/makefile` →
|
||||
`fileTypes/makefile`, MIT, Copyright (c) 2016 Victor Kropp — full text below).
|
||||
|
||||
The read/write usage filter assets (`actions/showReadAccess{,_dark}.svg` and
|
||||
`actions/showWriteAccess{,_dark}.svg`) are copied unmodified from
|
||||
`platform/icons/src/expui/actions/` at intellij-community commit
|
||||
[`e992ff4750b4c36afe2caadfa8b191a8f36fb7a2`](https://github.com/JetBrains/intellij-community/tree/e992ff4750b4c36afe2caadfa8b191a8f36fb7a2/platform/icons/src/expui/actions).
|
||||
Their original copyright headers and Apache-2.0 licensing are retained.
|
||||
|
||||
- [intellij-rust](https://github.com/intellij-rust/intellij-rust) (MIT):
|
||||
`src/main/resources/icons/expui/rustFile{,_dark}.svg` →
|
||||
`src/ui/expui/fileTypes/rust{,_dark}.svg`;
|
||||
`src/main/resources/icons/expui/cargo{,_dark}.svg` and `cargoLock{,_dark}.svg` →
|
||||
`src/ui/expui/fileTypes/cargo{,_dark}.svg` and `cargoLock{,_dark}.svg`.
|
||||
Copyright (c) 2015 Aleksey Kladov, Evgeny Kurbatsky, Alexey Kudinkin and contributors;
|
||||
Copyright (c) 2016 JetBrains. MIT licence, full text below.
|
||||
|
||||
At render time `src/ui/icons.tsx` may recolour monochrome icons to `currentColor`.
|
||||
|
||||
## JetBrains IntelliJ Platform diff algorithm
|
||||
@@ -43,7 +65,7 @@ from its tests (`LineComparisonUtilTest`, `WordComparisonUtilTest`,
|
||||
JetBrains s.r.o. and contributors. Apache License 2.0 (below).
|
||||
|
||||
`src/ui/openidea/**` holds OpenIDEA's own file-type icons drawn in the expui style for
|
||||
languages whose JetBrains icons are not open source (Go, Rust, Ruby, Dart, Lua, Zig,
|
||||
languages whose JetBrains icons are not open source (Go, Ruby, Dart, Lua, Zig,
|
||||
Svelte, …). Those using the page-with-corner-badge layout (`goMod`, `goWork`,
|
||||
`dotenv`, `readme`, `lock`, `license`) reuse the page outline of the Apache-2.0
|
||||
expui `fileTypes/h.svg`; that outline is modified from the original by JetBrains.
|
||||
@@ -54,6 +76,31 @@ The lettering in `src-tauri/icons/source/openidea-wordmark*.svg` is outlined fro
|
||||
Inter Tight (Copyright 2022 The Inter Project Authors, SIL Open Font License 1.1,
|
||||
https://github.com/rsms/inter-tight).
|
||||
|
||||
### MIT License (Rust and Cargo icons)
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 Aleksey Kladov, Evgeny Kurbatsky, Alexey Kudinkin and contributors
|
||||
Copyright (c) 2016 JetBrains
|
||||
|
||||
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.
|
||||
|
||||
### MIT License (makefile icon)
|
||||
|
||||
Copyright (c) 2016 Victor Kropp
|
||||
|
||||
@@ -915,7 +915,11 @@ impl Session {
|
||||
} else {
|
||||
"end_turn"
|
||||
};
|
||||
finished = st.turn.take().map(|t| (t, TurnEnd::Stop(stop)));
|
||||
finished = st.turn.take().map(|mut t| {
|
||||
// Claude Code reports a turn that failed as cancelled here.
|
||||
let failure = t.failure.take().filter(|_| !t.cancelled);
|
||||
(t, failure.unwrap_or(TurnEnd::Stop(stop)))
|
||||
});
|
||||
}
|
||||
}
|
||||
"assistant" if msg.get("parent_tool_use_id").is_none_or(Value::is_null) => {
|
||||
@@ -1139,7 +1143,8 @@ where
|
||||
/// Whether `result` ends `turn`: it answers the turn's last message, or (stopped) any of
|
||||
/// its messages, or names none (the CLI's own error before the turn began).
|
||||
fn belongs(turn: &Turn, result: &Value) -> bool {
|
||||
if result.get("origin").is_some_and(|o| !o.is_null()) {
|
||||
// Prompts are sent with the origin `human`, and their results echo it.
|
||||
if result.get("origin").is_some_and(|o| !o.is_null() && o.get("kind").and_then(Value::as_str) != Some("human")) {
|
||||
return false;
|
||||
}
|
||||
let mut uuids = strings(result.get("user_message_uuids"));
|
||||
|
||||
@@ -738,6 +738,50 @@ async fn a_stop_ahead_of_its_prompt_cancels_it() {
|
||||
assert!(cli.sent.lock()[0].iter().all(|m| m["type"] != "user"), "nothing was sent");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_failed_turn_reports_its_failure() {
|
||||
let text = "Failed to authenticate: OAuth session expired and could not be refreshed";
|
||||
let lifecycle = |uuid: &str, state: &str| {
|
||||
Frame::Cli(json!({ "type": "command_lifecycle", "command_uuid": uuid, "state": state }))
|
||||
};
|
||||
let result = |uuid: &str| {
|
||||
Frame::Cli(json!({
|
||||
"type": "result", "subtype": "success", "is_error": true, "result": text, "stop_reason": "stop_sequence",
|
||||
"terminal_reason": "api_error", "origin": { "kind": "human" }, "user_message_uuids": [uuid],
|
||||
}))
|
||||
};
|
||||
// As Claude Code sends it, and with the turn's end ahead of its result.
|
||||
for lifecycle_first in [false, true] {
|
||||
let mut process = load_fixture("simple").remove(0);
|
||||
process.truncate(6);
|
||||
let Some(Frame::Shim(prompt)) = process.last() else { panic!("the fixture's prompt") };
|
||||
let uuid = prompt["uuid"].as_str().unwrap().to_owned();
|
||||
process.push(Frame::Cli(json!({
|
||||
"type": "assistant", "error": "authentication_failed", "parent_tool_use_id": null,
|
||||
"message": { "id": "m", "model": "<synthetic>", "content": [{ "type": "text", "text": text }] },
|
||||
})));
|
||||
if lifecycle_first {
|
||||
process.extend([lifecycle(&uuid, "cancelled"), result(&uuid)]);
|
||||
} else {
|
||||
process.extend([result(&uuid), lifecycle(&uuid, "cancelled")]);
|
||||
}
|
||||
let cli = Arc::new(Replay {
|
||||
processes: Mutex::new(VecDeque::from([process])),
|
||||
sent: Arc::default(),
|
||||
launched: Mutex::default(),
|
||||
errors: Arc::default(),
|
||||
});
|
||||
let (dir, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let h =
|
||||
Harness::connect(cli.clone(), dir.path().into(), dir.path().join("p"), cwd.path().into(), Vec::new()).await;
|
||||
let s = h.new_session().await;
|
||||
let Err(RpcError::Server { message, .. }) = h.prompt(&s, "hi").await else {
|
||||
panic!("the turn should fail (lifecycle first: {lifecycle_first})");
|
||||
};
|
||||
assert_eq!(message, format!("Claude Code authentication failed: {text}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Fork and undo against the real CLI, across connections, in a symlinked directory
|
||||
/// (macOS `/tmp`).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -829,6 +873,7 @@ fn which_result_ends_a_turn() {
|
||||
assert!(!belongs(&t, &json!({"user_message_uuids": ["a"]})), "a steer superseded it");
|
||||
assert!(belongs(&t, &json!({"subtype": "error_during_execution"})), "names no message");
|
||||
assert!(!belongs(&t, &json!({"origin": {"kind": "task-notification"}})), "Claude Code's own turn");
|
||||
assert!(belongs(&t, &json!({"origin": {"kind": "human"}, "user_message_uuids": ["b"]})), "the prompt's own result");
|
||||
assert!(belongs(&turn(&["a", "b"], true), &json!({"user_message_uuids": ["a"]})));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
//! Resource processing by the project's build tool, then publishing to the live JVM's output directory.
|
||||
use crate::BuildModel;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub struct ResourceBuild {
|
||||
pub command: String,
|
||||
pub args: Vec<String>,
|
||||
pub cwd: String,
|
||||
pub env: BTreeMap<String, String>,
|
||||
pub kind: &'static str,
|
||||
}
|
||||
|
||||
fn literal(value: &str) -> String {
|
||||
format!("'{}'", value.replace('\\', "\\\\").replace('\'', "\\'"))
|
||||
}
|
||||
|
||||
pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> IdeResult<ResourceBuild> {
|
||||
fs::create_dir_all(cache)?;
|
||||
let manifest = cache.join("resource-output.txt");
|
||||
if manifest.exists() {
|
||||
fs::remove_file(&manifest)?;
|
||||
}
|
||||
let module = dunce::canonicalize(root.join(module))?;
|
||||
if let Some(p) = model.maven.as_ref().and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module)) {
|
||||
let mut args = p.options.clone();
|
||||
args.extend([
|
||||
"process-resources".into(),
|
||||
"help:evaluate".into(),
|
||||
"-Dexpression=project.build.outputDirectory".into(),
|
||||
format!("-Doutput={}", manifest.display()),
|
||||
]);
|
||||
return Ok(ResourceBuild {
|
||||
command: p.command.clone(),
|
||||
args,
|
||||
cwd: p.dir.clone(),
|
||||
env: p.env.clone(),
|
||||
kind: "maven",
|
||||
});
|
||||
}
|
||||
if let Some(g) = &model.gradle
|
||||
&& let Some(p) = g.projects.iter().find(|p| root.join(&p.dir) == module)
|
||||
{
|
||||
let script = cache.join("resources.init.gradle");
|
||||
fs::write(
|
||||
&script,
|
||||
format!(
|
||||
r#"gradle.projectsEvaluated {{
|
||||
def p = gradle.rootProject.project({})
|
||||
def resources = p.tasks.named('processResources')
|
||||
p.tasks.register('openideaUpdateResources') {{
|
||||
dependsOn resources
|
||||
doLast {{ new File({}).setText(resources.get().destinationDir.absolutePath, 'UTF-8') }}
|
||||
}}
|
||||
}}
|
||||
"#,
|
||||
literal(&p.path),
|
||||
literal(&manifest.to_string_lossy())
|
||||
),
|
||||
)?;
|
||||
return Ok(ResourceBuild {
|
||||
command: g.command.clone(),
|
||||
args: vec![
|
||||
"--init-script".into(),
|
||||
script.to_string_lossy().into_owned(),
|
||||
format!("{}:openideaUpdateResources", p.path.trim_end_matches(':')),
|
||||
],
|
||||
cwd: g.dir.clone(),
|
||||
env: g.env.clone(),
|
||||
kind: "gradle",
|
||||
});
|
||||
}
|
||||
Err(IdeError::invalid("The Spring Boot module must belong to a linked Maven or Gradle build"))
|
||||
}
|
||||
|
||||
pub fn publish(root: &Path, cache: &Path, class_paths: &[String], main_class: &str) -> IdeResult<()> {
|
||||
let output = PathBuf::from(fs::read_to_string(cache.join("resource-output.txt"))?.trim());
|
||||
if !output.is_absolute() || !output.is_dir() {
|
||||
return Err(IdeError::invalid("The resource build did not report an output directory"));
|
||||
}
|
||||
let output = dunce::canonicalize(output)?;
|
||||
let paths: Vec<_> = class_paths.iter().filter_map(|p| dunce::canonicalize(root.join(p)).ok()).collect();
|
||||
// A separate resource directory is already on the runtime classpath (e.g. build/resources/main).
|
||||
if paths.contains(&output) {
|
||||
return Ok(());
|
||||
}
|
||||
// jdtls uses bin/main for Gradle, rather than Gradle's build/resources/main.
|
||||
let class_file = main_class.split('.').collect::<PathBuf>().with_extension("class");
|
||||
let destination = paths.iter().find(|p| p.join(&class_file).is_file()).ok_or_else(|| {
|
||||
IdeError::invalid("Cannot find the running main class output directory; restart the application")
|
||||
})?;
|
||||
let previous: Vec<String> = fs::read(cache.join("published-resources.json"))
|
||||
.ok()
|
||||
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
|
||||
.unwrap_or_default();
|
||||
let mut current = Vec::new();
|
||||
copy_resources(&output, &output, destination, &mut current)?;
|
||||
for rel in previous.iter().filter(|p| !current.contains(p)) {
|
||||
let path = destination.join(rel);
|
||||
if path.is_file() {
|
||||
fs::remove_file(path)?;
|
||||
}
|
||||
}
|
||||
fs::write(
|
||||
cache.join("published-resources.json"),
|
||||
serde_json::to_vec(¤t).map_err(|e| IdeError::internal(e.to_string()))?,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy_resources(root: &Path, from: &Path, to: &Path, copied: &mut Vec<String>) -> IdeResult<()> {
|
||||
for entry in fs::read_dir(from)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
let kind = entry.file_type()?;
|
||||
if kind.is_symlink() {
|
||||
continue;
|
||||
}
|
||||
if kind.is_dir() {
|
||||
copy_resources(root, &path, to, copied)?;
|
||||
} else if kind.is_file() && path.extension().is_none_or(|e| e != "class") {
|
||||
let rel = path.strip_prefix(root).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let dest = to.join(rel);
|
||||
if let Some(parent) = dest.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::copy(&path, dest)?;
|
||||
copied.push(rel.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn resource_plans_use_the_selected_module_and_build_configuration() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
fs::create_dir(root.join("app")).unwrap();
|
||||
let mut model = BuildModel {
|
||||
maven: Some(crate::MavenModel {
|
||||
projects: vec![crate::MavenProject {
|
||||
dir: "app".into(),
|
||||
command: "/tools/mvnw".into(),
|
||||
options: vec!["-Pdev".into()],
|
||||
env: BTreeMap::from([("JAVA_HOME".into(), "/jdk".into())]),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let cache = root.join("cache");
|
||||
let maven = plan(&root, &model, Path::new("app"), &cache).unwrap();
|
||||
assert_eq!(maven.command, "/tools/mvnw");
|
||||
assert_eq!(maven.cwd, "app");
|
||||
assert_eq!(maven.args[0..2], ["-Pdev", "process-resources"]);
|
||||
assert!(maven.args.contains(&"-Dexpression=project.build.outputDirectory".into()));
|
||||
assert_eq!(maven.env["JAVA_HOME"], "/jdk");
|
||||
model.maven = None;
|
||||
model.gradle = Some(crate::GradleModel {
|
||||
command: "/tools/gradlew".into(),
|
||||
projects: vec![crate::GradleProject { path: ":app".into(), dir: "app".into(), ..Default::default() }],
|
||||
..Default::default()
|
||||
});
|
||||
let gradle = plan(&root, &model, Path::new("app"), &cache).unwrap();
|
||||
assert_eq!(gradle.command, "/tools/gradlew");
|
||||
assert_eq!(gradle.args.last().unwrap(), ":app:openideaUpdateResources");
|
||||
let script = fs::read_to_string(cache.join("resources.init.gradle")).unwrap();
|
||||
assert!(script.contains("processResources") && script.contains("destinationDir.absolutePath"));
|
||||
assert!(!script.contains("build/resources/main")); // The task owns custom output locations.
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publishes_maven_and_gradle_resource_outputs_to_the_runtime_classpath() {
|
||||
for layout in ["target/classes", "build/resources/main", "custom resource output"] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let cache = root.join("cache");
|
||||
let output = root.join(layout);
|
||||
let runtime = if layout == "target/classes" { output.clone() } else { root.join("bin/main") };
|
||||
fs::create_dir_all(output.join("static")).unwrap();
|
||||
fs::create_dir_all(runtime.join("example")).unwrap();
|
||||
fs::create_dir_all(&cache).unwrap();
|
||||
fs::write(cache.join("resource-output.txt"), output.to_string_lossy().as_bytes()).unwrap();
|
||||
fs::write(output.join("static/index.html"), "after").unwrap();
|
||||
fs::write(output.join("unrelated.class"), "do not publish").unwrap();
|
||||
fs::write(runtime.join("example/Application.class"), "running").unwrap();
|
||||
publish(root, &cache, &[runtime.to_string_lossy().into_owned()], "example.Application").unwrap();
|
||||
assert_eq!(fs::read_to_string(runtime.join("static/index.html")).unwrap(), "after");
|
||||
assert_eq!(fs::read_to_string(runtime.join("example/Application.class")).unwrap(), "running");
|
||||
if output != runtime {
|
||||
assert!(!runtime.join("unrelated.class").exists());
|
||||
fs::remove_file(output.join("static/index.html")).unwrap();
|
||||
publish(root, &cache, &[runtime.to_string_lossy().into_owned()], "example.Application").unwrap();
|
||||
assert!(!runtime.join("static/index.html").exists());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_separate_runtime_resource_directories_in_place_and_rejects_jar_only_runs() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let output = root.join("build/resources/main");
|
||||
let cache = root.join("cache");
|
||||
fs::create_dir_all(&output).unwrap();
|
||||
fs::create_dir(&cache).unwrap();
|
||||
fs::write(cache.join("resource-output.txt"), output.to_string_lossy().as_bytes()).unwrap();
|
||||
publish(root, &cache, &[output.to_string_lossy().into_owned()], "a.Main").unwrap();
|
||||
assert!(publish(root, &cache, &["app.jar".into()], "a.Main").is_err());
|
||||
}
|
||||
}
|
||||
@@ -237,12 +237,7 @@ fn maven_steps(root: &Path, model: &BuildModel, kind: BuildKind, module: Option<
|
||||
if !m.projects.iter().any(|p| p.dir == rel) {
|
||||
return Err(IdeError::not_found("no linked Maven project found for module"));
|
||||
}
|
||||
let top = tops
|
||||
.iter()
|
||||
.filter(|t| t.dir.is_empty() || rel == t.dir || rel.starts_with(&format!("{}/", t.dir)))
|
||||
.max_by_key(|t| t.dir.len())
|
||||
.copied()
|
||||
.unwrap_or(tops[0]);
|
||||
let top = maven_reactor(m, &rel).ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
if module == top_dir {
|
||||
return Ok(vec![step(top, &[])]);
|
||||
@@ -611,6 +606,90 @@ pub fn has_non_java_sources(module: &Path) -> bool {
|
||||
walk(&module.join("src"), 12)
|
||||
}
|
||||
|
||||
fn reactor_projects<'a>(m: &'a maven::MavenModel, top: &'a maven::MavenProject) -> Vec<&'a maven::MavenProject> {
|
||||
let mut projects = Vec::new();
|
||||
let mut pending = vec![top];
|
||||
let mut seen = HashSet::new();
|
||||
while let Some(p) = pending.pop() {
|
||||
if !seen.insert(&p.pom) {
|
||||
continue;
|
||||
}
|
||||
projects.push(p);
|
||||
pending.extend(m.projects.iter().filter(|child| p.modules.contains(&child.pom)));
|
||||
}
|
||||
projects
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
/// Launch module first, followed by its upstream modules in the same Maven reactor.
|
||||
/// External artifacts and unrelated linked reactors are never rebuilt for this launch.
|
||||
fn maven_launch_projects<'a>(
|
||||
root: &Path,
|
||||
m: &'a maven::MavenModel,
|
||||
module: &Path,
|
||||
test: bool,
|
||||
) -> Vec<&'a maven::MavenProject> {
|
||||
let rel = rel_str(root, module);
|
||||
let Some(top) = maven_reactor(m, &rel) else { return Vec::new() };
|
||||
let reactor = reactor_projects(m, top);
|
||||
let Some(start) = reactor.iter().find(|p| p.dir == rel) else { return Vec::new() };
|
||||
let mut pending = vec![*start];
|
||||
let mut seen = HashSet::new();
|
||||
let mut projects = Vec::new();
|
||||
while let Some(p) = pending.pop() {
|
||||
if !seen.insert(&p.pom) {
|
||||
continue;
|
||||
}
|
||||
projects.push(p);
|
||||
for dep in &p.dependencies {
|
||||
if !dep.resolved() || (dep.scope == "test" && (!test || p.pom != start.pom)) {
|
||||
continue;
|
||||
}
|
||||
if let Some(upstream) = reactor.iter().find(|u| {
|
||||
u.group_id == dep.group_id
|
||||
&& u.artifact_id == dep.artifact_id
|
||||
&& dep.version.as_ref().is_none_or(|v| *v == u.version)
|
||||
}) {
|
||||
pending.push(*upstream);
|
||||
}
|
||||
}
|
||||
}
|
||||
projects
|
||||
}
|
||||
|
||||
/// Whether a launch requires the external JVM compiler. Maven includes upstream
|
||||
/// reactor dependencies; adapter selection remains a separate, module-local decision.
|
||||
pub fn launch_has_non_java_sources(root: &Path, model: &BuildModel, module: &Path, test: bool) -> bool {
|
||||
if let Some(m) = &model.maven {
|
||||
let projects = maven_launch_projects(root, m, module, test);
|
||||
if !projects.is_empty() {
|
||||
return projects.iter().any(|p| has_non_java_sources(&subdir(root, &p.dir)));
|
||||
}
|
||||
}
|
||||
has_non_java_sources(module)
|
||||
}
|
||||
|
||||
fn launch_plan(root: &Path, model: &BuildModel, module: &Path, test: bool) -> IdeResult<BuildPlan> {
|
||||
let kind = if model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| subdir(root, &p.dir) == module)) {
|
||||
// JDT may have left newer error stubs in Maven's output directories.
|
||||
BuildKind::Rebuild
|
||||
} else {
|
||||
BuildKind::Build
|
||||
};
|
||||
let mut plan = plan(root, model, kind, Some(module))?;
|
||||
if plan.system == BuildSystem::Maven && !test {
|
||||
for step in &mut plan.steps {
|
||||
if let Some(goal) = step.args.last_mut() {
|
||||
*goal = "compile".into();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
/// Compiles the module at `module` with its build system before a JVM launch and
|
||||
/// returns the class directories it wrote, to put ahead of the jdtls classpath.
|
||||
pub fn build_for_launch(
|
||||
@@ -620,7 +699,7 @@ pub fn build_for_launch(
|
||||
test: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Vec<PathBuf>> {
|
||||
let plan = plan(root, model, BuildKind::Build, Some(module))?;
|
||||
let plan = launch_plan(root, model, module, test)?;
|
||||
let result = run(root, &plan, cancel, &|_| {})?;
|
||||
if !result.success {
|
||||
let errors: Vec<String> = result
|
||||
@@ -635,6 +714,14 @@ pub fn build_for_launch(
|
||||
.collect();
|
||||
return Err(IdeError::internal(format!("Build failed:\n{}", errors.join("\n"))));
|
||||
}
|
||||
if plan.system == BuildSystem::Maven
|
||||
&& let Some(m) = &model.maven
|
||||
{
|
||||
return Ok(maven_launch_projects(root, m, module, test)
|
||||
.iter()
|
||||
.flat_map(|p| launch_class_dirs(plan.system, &subdir(root, &p.dir), test && subdir(root, &p.dir) == module))
|
||||
.collect());
|
||||
}
|
||||
Ok(launch_class_dirs(plan.system, module, test))
|
||||
}
|
||||
|
||||
@@ -821,6 +908,142 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn reactor_model() -> BuildModel {
|
||||
let project = |dir: &str, deps: &[&str]| maven::MavenProject {
|
||||
pom: format!("{dir}/pom.xml"),
|
||||
dir: dir.into(),
|
||||
group_id: "probe".into(),
|
||||
artifact_id: dir.into(),
|
||||
version: "1".into(),
|
||||
aggregated: true,
|
||||
dependencies: deps
|
||||
.iter()
|
||||
.map(|d| maven::MavenDependency {
|
||||
group_id: "probe".into(),
|
||||
artifact_id: (*d).into(),
|
||||
version: Some("1".into()),
|
||||
scope: "compile".into(),
|
||||
..Default::default()
|
||||
})
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut projects = vec![
|
||||
project("app", &["middle"]),
|
||||
project("middle", &["lib"]),
|
||||
project("lib", &["app"]),
|
||||
project("unrelated", &[]),
|
||||
];
|
||||
projects.insert(
|
||||
0,
|
||||
maven::MavenProject {
|
||||
pom: "pom.xml".into(),
|
||||
artifact_id: "reactor".into(),
|
||||
command: "mvnw".into(),
|
||||
modules: projects.iter().map(|p| p.pom.clone()).collect(),
|
||||
options: vec!["-s".into(), "settings.xml".into()],
|
||||
env: BTreeMap::from([("JAVA_HOME".into(), "/jdk".into())]),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
BuildModel { maven: Some(maven::MavenModel { projects, ..Default::default() }), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_launch_detection_follows_only_reactor_dependencies() {
|
||||
for extension in ["kt", "groovy", "scala"] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let mut model = reactor_model();
|
||||
write(root, "app/src/main/java/Application.java", "class Application {}");
|
||||
write(root, &format!("unrelated/src/main/java/Other.{extension}"), "");
|
||||
assert!(!launch_has_non_java_sources(root, &model, &root.join("app"), false));
|
||||
write(root, &format!("lib/src/main/java/Channel.{extension}"), "");
|
||||
assert!(launch_has_non_java_sources(root, &model, &root.join("app"), false));
|
||||
assert_eq!(
|
||||
maven_launch_projects(root, model.maven.as_ref().unwrap(), &root.join("app"), false).len(),
|
||||
3,
|
||||
"cycles terminate"
|
||||
);
|
||||
let m = model.maven.as_mut().unwrap();
|
||||
m.projects[2].dependencies[0].scope = "test".into();
|
||||
assert!(
|
||||
!launch_has_non_java_sources(root, &model, &root.join("app"), true),
|
||||
"upstream test dependencies are not transitive"
|
||||
);
|
||||
let m = model.maven.as_mut().unwrap();
|
||||
m.projects[1].dependencies[0].scope = "test".into();
|
||||
m.projects[2].dependencies[0].scope = "compile".into();
|
||||
assert!(!launch_has_non_java_sources(root, &model, &root.join("app"), false));
|
||||
assert!(launch_has_non_java_sources(root, &model, &root.join("app"), true));
|
||||
model.maven.as_mut().unwrap().projects[2].dependencies[0].version = Some("external".into());
|
||||
assert!(!launch_has_non_java_sources(root, &model, &root.join("app"), true));
|
||||
model.maven.as_mut().unwrap().projects[2].dependencies[0].version = Some("1".into());
|
||||
model.maven.as_mut().unwrap().projects[3].aggregated = false;
|
||||
model.maven.as_mut().unwrap().projects[0].modules.retain(|p| p != "lib/pom.xml");
|
||||
assert!(
|
||||
!launch_has_non_java_sources(root, &model, &root.join("app"), true),
|
||||
"another linked reactor is external"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_launch_steps_use_reactor_settings_and_launch_scope() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(root, "app/pom.xml", "<project/>");
|
||||
let model = reactor_model();
|
||||
for (test, goal) in [(false, "compile"), (true, "test-compile")] {
|
||||
let plan = launch_plan(root, &model, &root.join("app"), test).unwrap();
|
||||
let step = &plan.steps[0];
|
||||
assert_eq!(step.cwd, root);
|
||||
assert_eq!(step.program, "mvnw");
|
||||
assert_eq!(step.env["JAVA_HOME"], "/jdk");
|
||||
assert_eq!(
|
||||
step.args,
|
||||
["-B", "-Dstyle.color=never", "-s", "settings.xml", "-pl", "app", "-am", "clean", goal]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn external_launch_returns_upstream_outputs_and_blocks_failure_or_cancellation() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(root, "app/pom.xml", "<project/>");
|
||||
write(
|
||||
root,
|
||||
"mvnw",
|
||||
"#!/bin/sh\nmkdir -p app/target/classes middle/target/classes lib/target/classes app/target/test-classes\n",
|
||||
);
|
||||
let wrapper = root.join("mvnw");
|
||||
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let mut model = reactor_model();
|
||||
model.maven.as_mut().unwrap().projects[0].command = wrapper.to_string_lossy().into_owned();
|
||||
let dirs = build_for_launch(root, &model, &root.join("app"), true, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(
|
||||
dirs,
|
||||
["app/target/test-classes", "app/target/classes", "middle/target/classes", "lib/target/classes"]
|
||||
.map(|p| root.join(p))
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"mvnw",
|
||||
"#!/bin/sh\necho '[ERROR] Kotlin compilation failed: unresolved reference broken' >&2\nexit 1\n",
|
||||
);
|
||||
let error = build_for_launch(root, &model, &root.join("app"), false, &CancellationToken::new()).unwrap_err();
|
||||
assert!(error.message.contains("Kotlin compilation failed"), "{}", error.message);
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
assert_eq!(
|
||||
build_for_launch(root, &model, &root.join("app"), false, &cancel).unwrap_err().kind,
|
||||
ide_core::error::ErrorKind::Cancelled
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_java_launch_class_dirs() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! and merges what the last sync ([`sync_maven`] / [`sync_gradle`], which run
|
||||
//! Maven / Gradle in the background) cached for the project.
|
||||
|
||||
pub mod application_update;
|
||||
pub mod compile;
|
||||
pub mod gradle;
|
||||
pub mod maven;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! The file list on the OS clipboard: what Explorer copies when the user
|
||||
//! copies files, so the project view can paste them, and what the project view
|
||||
//! writes so Explorer can paste the files it copied (IDEA does both).
|
||||
//! writes so Explorer can paste the files it copied (IDEA does both). The
|
||||
//! written list comes with the paths as text, so a paste into an editor
|
||||
//! inserts them instead of doing nothing.
|
||||
//!
|
||||
//! Windows keeps it as `CF_HDROP`: a `DROPFILES` header and a double-NUL
|
||||
//! terminated list of absolute paths, wide when `fWide` is set. The data is set
|
||||
@@ -10,6 +12,9 @@
|
||||
//! macOS keeps one `public.file-url` item per file on the general
|
||||
//! `NSPasteboard`; `NSURL` reads and writes them, so Finder's copies paste here
|
||||
//! and ours paste in Finder.
|
||||
//! On macOS, [`files`], [`has_files`] and [`set_files`] must run on the main
|
||||
//! 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.
|
||||
@@ -20,7 +25,8 @@ use std::path::PathBuf;
|
||||
const HEADER: usize = 20;
|
||||
|
||||
/// The absolute paths on the clipboard, empty when it holds no file list.
|
||||
pub fn files() -> Vec<PathBuf> {
|
||||
/// Read failures remain errors so callers can retain an internal copy.
|
||||
pub fn files() -> std::io::Result<Vec<PathBuf>> {
|
||||
imp::files()
|
||||
}
|
||||
|
||||
@@ -29,9 +35,8 @@ pub fn has_files() -> bool {
|
||||
imp::has_files()
|
||||
}
|
||||
|
||||
/// Replaces the clipboard with `paths`. False when it is busy or holds nothing
|
||||
/// to write; the clipboard is a shared resource, so callers treat this as
|
||||
/// best-effort.
|
||||
/// Replaces the clipboard with `paths`. True only when the file list was
|
||||
/// accepted; writing just the accompanying text is not a successful hand-off.
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
if paths.is_empty() {
|
||||
return false;
|
||||
@@ -111,6 +116,8 @@ mod imp {
|
||||
|
||||
/// `CF_HDROP`, the clipboard format holding a file list.
|
||||
const CF_HDROP: u32 = 15;
|
||||
/// `CF_UNICODETEXT`, so an editor paste of copied files inserts the paths.
|
||||
const CF_UNICODETEXT: u32 = 13;
|
||||
|
||||
/// An `HGLOBAL` or a `HANDLE`: both are opaque pointers here.
|
||||
type Handle = *mut c_void;
|
||||
@@ -156,25 +163,29 @@ mod imp {
|
||||
(unsafe { IsClipboardFormatAvailable(CF_HDROP) }) != 0
|
||||
}
|
||||
|
||||
pub fn files() -> Vec<PathBuf> {
|
||||
if !has_files() || !open() {
|
||||
return Vec::new();
|
||||
pub fn files() -> std::io::Result<Vec<PathBuf>> {
|
||||
if !open() {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
if !has_files() {
|
||||
unsafe { CloseClipboard() };
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let memory = unsafe { GetClipboardData(CF_HDROP) };
|
||||
let paths = if memory.is_null() {
|
||||
Vec::new()
|
||||
Err(std::io::Error::last_os_error())
|
||||
} else {
|
||||
// SAFETY: the clipboard keeps the block alive while it is open, and
|
||||
// `GlobalSize` bounds the bytes read from it.
|
||||
unsafe {
|
||||
let data = GlobalLock(memory);
|
||||
if data.is_null() {
|
||||
Vec::new()
|
||||
Err(std::io::Error::last_os_error())
|
||||
} else {
|
||||
let bytes = std::slice::from_raw_parts(data as *const u8, GlobalSize(memory));
|
||||
let paths = decode(bytes);
|
||||
GlobalUnlock(memory);
|
||||
paths
|
||||
Ok(paths)
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -182,12 +193,37 @@ mod imp {
|
||||
paths
|
||||
}
|
||||
|
||||
/// An `HGLOBAL` holding `text` as UTF-16 with a terminating NUL, and its
|
||||
/// byte size. Null when the allocation failed.
|
||||
fn global_text(text: &str) -> (Handle, usize) {
|
||||
let mut units: Vec<u16> = text.encode_utf16().collect();
|
||||
units.push(0);
|
||||
let bytes = units.len() * 2;
|
||||
unsafe {
|
||||
let memory = GlobalAlloc(GMEM_MOVEABLE, bytes);
|
||||
if memory.is_null() {
|
||||
return (ptr::null_mut(), 0);
|
||||
}
|
||||
let data = GlobalLock(memory);
|
||||
if data.is_null() {
|
||||
GlobalFree(memory);
|
||||
return (ptr::null_mut(), 0);
|
||||
}
|
||||
ptr::copy_nonoverlapping(units.as_ptr() as *const u8, data as *mut u8, bytes);
|
||||
GlobalUnlock(memory);
|
||||
(memory, bytes)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
let bytes = encode(paths);
|
||||
if bytes.len() <= HEADER {
|
||||
return false;
|
||||
}
|
||||
// SAFETY: the block is allocated, filled, handed to the clipboard and
|
||||
// The paths as text, newline-separated, so pasting into an editor
|
||||
// inserts them (IDEA writes the list and the text together).
|
||||
let text = paths.iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>().join("\r\n");
|
||||
// SAFETY: the blocks are allocated, filled, handed to the clipboard and
|
||||
// freed only on the paths where the clipboard did not take ownership.
|
||||
unsafe {
|
||||
let memory = GlobalAlloc(GMEM_MOVEABLE, bytes.len());
|
||||
@@ -205,17 +241,26 @@ mod imp {
|
||||
GlobalFree(memory);
|
||||
return false;
|
||||
}
|
||||
// Replacing the list also drops the text the user copied before.
|
||||
// Replacing the list also drops the text the user copied before;
|
||||
// the paths' own text is set back with it.
|
||||
if EmptyClipboard() == 0 {
|
||||
CloseClipboard();
|
||||
GlobalFree(memory);
|
||||
return false;
|
||||
}
|
||||
let taken = !SetClipboardData(CF_HDROP, memory).is_null();
|
||||
CloseClipboard();
|
||||
if !taken {
|
||||
GlobalFree(memory);
|
||||
}
|
||||
let (text_memory, _) = global_text(&text);
|
||||
if !text_memory.is_null() {
|
||||
// The text alone still pastes somewhere useful.
|
||||
let text_taken = !SetClipboardData(CF_UNICODETEXT, text_memory).is_null();
|
||||
if !text_taken {
|
||||
GlobalFree(text_memory);
|
||||
}
|
||||
}
|
||||
CloseClipboard();
|
||||
taken
|
||||
}
|
||||
}
|
||||
@@ -223,13 +268,14 @@ mod imp {
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod imp {
|
||||
use objc2::ClassType;
|
||||
use objc2::rc::{Retained, autoreleasepool};
|
||||
use objc2::runtime::{AnyClass, AnyObject, ProtocolObject};
|
||||
use objc2::{ClassType, MainThreadMarker};
|
||||
use objc2_app_kit::{
|
||||
NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
|
||||
NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypeString, NSPasteboardURLReadingFileURLsOnlyKey,
|
||||
NSPasteboardWriting,
|
||||
};
|
||||
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSURL};
|
||||
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// `NSURL` as the one class to read, limited to file URLs: a web link the
|
||||
@@ -237,6 +283,7 @@ mod imp {
|
||||
fn read_file_urls<R>(
|
||||
f: impl FnOnce(&NSPasteboard, &NSArray<AnyClass>, &NSDictionary<NSPasteboardReadingOptionKey, AnyObject>) -> R,
|
||||
) -> R {
|
||||
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
|
||||
autoreleasepool(|_| {
|
||||
let board = NSPasteboard::generalPasteboard();
|
||||
let classes = NSArray::from_slice(&[NSURL::class()]);
|
||||
@@ -256,23 +303,28 @@ mod imp {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn files() -> Vec<PathBuf> {
|
||||
pub fn files() -> std::io::Result<Vec<PathBuf>> {
|
||||
read_file_urls(|board, classes, options| {
|
||||
// SAFETY: as in `has_files`; every object read for `NSURL` is one.
|
||||
let Some(objects) = (unsafe { board.readObjectsForClasses_options(classes, Some(options)) }) else {
|
||||
return Vec::new();
|
||||
return if unsafe { board.canReadObjectForClasses_options(classes, Some(options)) } {
|
||||
Err(std::io::Error::other("Cannot read clipboard files"))
|
||||
} else {
|
||||
Ok(Vec::new())
|
||||
};
|
||||
};
|
||||
objects
|
||||
Ok(objects
|
||||
.iter()
|
||||
.filter_map(|object| object.downcast::<NSURL>().ok())
|
||||
.filter_map(|url| url.to_file_path())
|
||||
// Finder ends a folder's URL in `/`; the project view names it without.
|
||||
.map(|path| path.components().collect())
|
||||
.collect()
|
||||
.collect())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
|
||||
autoreleasepool(|_| {
|
||||
// Folders get a directory URL (ending in `/`), as Finder writes them.
|
||||
let urls: Vec<Retained<NSURL>> = paths
|
||||
@@ -285,9 +337,16 @@ mod imp {
|
||||
let writers: Vec<&ProtocolObject<dyn NSPasteboardWriting>> =
|
||||
urls.iter().map(|url| ProtocolObject::from_ref(&**url)).collect();
|
||||
let board = NSPasteboard::generalPasteboard();
|
||||
// Replacing the list also drops the text the user copied before.
|
||||
// Replacing the list also drops the text the user copied before;
|
||||
// the paths' own text is set back with it, so an editor paste
|
||||
// inserts them (IDEA writes the list and the text together).
|
||||
board.clearContents();
|
||||
board.writeObjects(&NSArray::from_slice(&writers))
|
||||
let written = board.writeObjects(&NSArray::from_slice(&writers));
|
||||
let text = NSString::from_str(
|
||||
&paths.iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>().join("\n"),
|
||||
);
|
||||
board.setString_forType(&text, unsafe { NSPasteboardTypeString });
|
||||
written
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -300,8 +359,8 @@ mod imp {
|
||||
false
|
||||
}
|
||||
|
||||
pub fn files() -> Vec<PathBuf> {
|
||||
Vec::new()
|
||||
pub fn files() -> std::io::Result<Vec<PathBuf>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
pub fn set_files(_paths: &[PathBuf]) -> bool {
|
||||
|
||||
@@ -276,6 +276,8 @@ pub struct AppearanceSettings {
|
||||
/// Apply `ui_font_family` / `ui_font_size` (otherwise the theme's).
|
||||
pub use_custom_font: bool,
|
||||
pub ui_font_family: String,
|
||||
/// Font tried when `ui_font_family` lacks a glyph; empty = none.
|
||||
pub ui_font_fallback: String,
|
||||
pub contrast_scrollbars: bool,
|
||||
/// Adjust colours for red-green vision deficiency.
|
||||
pub red_green_vision: bool,
|
||||
@@ -292,6 +294,7 @@ pub struct AppearanceSettings {
|
||||
pub editor_antialiasing: String,
|
||||
pub show_tool_window_bars: bool,
|
||||
pub show_tool_window_names: bool,
|
||||
pub show_tool_window_badges: bool,
|
||||
pub widescreen_tool_windows: bool,
|
||||
/// Status bar widgets shown (`true`) or hidden (`false`) by the user
|
||||
/// (status bar context menu); widgets not listed use their default.
|
||||
@@ -325,6 +328,7 @@ impl Default for AppearanceSettings {
|
||||
zoom: 100,
|
||||
use_custom_font: false,
|
||||
ui_font_family: "Inter".into(),
|
||||
ui_font_fallback: String::new(),
|
||||
contrast_scrollbars: false,
|
||||
red_green_vision: false,
|
||||
different_tool_window_background: false,
|
||||
@@ -338,6 +342,7 @@ impl Default for AppearanceSettings {
|
||||
editor_antialiasing: "greyscale".into(),
|
||||
show_tool_window_bars: true,
|
||||
show_tool_window_names: false,
|
||||
show_tool_window_badges: true,
|
||||
widescreen_tool_windows: false,
|
||||
status_bar_widgets: BTreeMap::new(),
|
||||
main_toolbar: None,
|
||||
@@ -719,6 +724,35 @@ impl Settings {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ui_font_fallback_defaults_empty_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"useCustomFont":true}}"#).unwrap();
|
||||
assert!(old.appearance.ui_font_fallback.is_empty());
|
||||
for family in ["", "Songti SC", "Maple Mono NF CN"] {
|
||||
let mut settings = Settings::default();
|
||||
settings.appearance.ui_font_fallback = family.into();
|
||||
let json = serde_json::to_value(&settings).unwrap();
|
||||
assert_eq!(json["appearance"]["uiFontFallback"], family);
|
||||
let restored: Settings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(restored.appearance.ui_font_fallback, family);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_window_badges_default_on_and_round_trip() {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"showToolWindowNames":true}}"#).unwrap();
|
||||
assert!(old.appearance.show_tool_window_badges);
|
||||
assert!(Settings::default().appearance.show_tool_window_badges);
|
||||
for enabled in [false, true] {
|
||||
let mut settings = Settings::default();
|
||||
settings.appearance.show_tool_window_badges = enabled;
|
||||
let json = serde_json::to_value(&settings).unwrap();
|
||||
assert_eq!(json["appearance"]["showToolWindowBadges"], enabled);
|
||||
let restored: Settings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(restored.appearance.show_tool_window_badges, enabled);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn main_menu_style_defaults_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"compactMode":true}}"#).unwrap();
|
||||
|
||||
@@ -7,10 +7,11 @@ license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFArray", "CFDictionary", "CFNumber", "CFString"] }
|
||||
objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFArray", "CFDictionary", "CFNumber", "CFString", "CFURL"] }
|
||||
objc2-core-text = { version = "0.3", default-features = false, features = ["std", "CTFontCollection", "CTFontDescriptor", "CTFontTraits"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
//! The font families installed on this machine, for the font pickers in
|
||||
//! Settings (editor, typography fallback, terminal, UI font).
|
||||
//!
|
||||
//! Each platform asks the font system the WebView itself resolves CSS
|
||||
//! `font-family` names against, so every listed name renders: CoreText on
|
||||
//! Each platform asks the native font system for installed families: CoreText on
|
||||
//! macOS, DirectWrite on Windows, fontconfig (`fc-list`) on Linux and the BSDs.
|
||||
//! The list is read on first use and cached until explicitly refreshed; the
|
||||
//! query can take a few hundred milliseconds, so callers run it off the UI and
|
||||
@@ -84,14 +83,164 @@ pub fn parse_fc_list(output: &str) -> Vec<(String, bool)> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Binary font bundle: little-endian u32 JSON-header length, a face metadata
|
||||
/// array, then raw font bytes. Paths never cross IPC; only CoreText-enumerated
|
||||
/// files under user font directories can be read, selected by family name.
|
||||
/// Includes only the nearest regular/bold faces and their optional italics.
|
||||
pub fn user_font_data(family: &str) -> std::io::Result<Vec<u8>> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let entries = imp::user_faces();
|
||||
bundle_family(family, &entries)
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
let _ = family;
|
||||
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "User font loading is macOS only"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
#[derive(Debug)]
|
||||
struct UserFace {
|
||||
family: String,
|
||||
path: std::path::PathBuf,
|
||||
weight: u16,
|
||||
italic: bool,
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn user_font_path(path: &std::path::Path, roots: &[std::path::PathBuf]) -> Option<std::path::PathBuf> {
|
||||
let path = path.canonicalize().ok()?;
|
||||
roots.iter().any(|root| path.starts_with(root)).then_some(path)
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn family_faces<'a>(family: &str, entries: &'a [UserFace]) -> Vec<&'a UserFace> {
|
||||
let mut selected: Vec<&UserFace> = Vec::new();
|
||||
for italic in [false, true] {
|
||||
for weight in [400u16, 700] {
|
||||
let closest = entries
|
||||
.iter()
|
||||
.filter(|e| e.family.eq_ignore_ascii_case(family.trim()) && e.italic == italic)
|
||||
.min_by_key(|e| (e.weight.abs_diff(weight), e.weight, &e.path));
|
||||
if let Some(face) = closest
|
||||
&& !selected.iter().any(|f| std::ptr::eq(*f, face))
|
||||
{
|
||||
selected.push(face);
|
||||
}
|
||||
}
|
||||
}
|
||||
selected
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn bundle_family(family: &str, entries: &[UserFace]) -> std::io::Result<Vec<u8>> {
|
||||
#[derive(Serialize)]
|
||||
struct Face {
|
||||
weight: u16,
|
||||
style: &'static str,
|
||||
offset: usize,
|
||||
length: usize,
|
||||
}
|
||||
let mut faces = Vec::new();
|
||||
let mut data = Vec::new();
|
||||
let mut files = BTreeMap::new();
|
||||
// Bound large CJK families to regular/bold and their nearest italic faces.
|
||||
for entry in family_faces(family, entries) {
|
||||
// Reject a file replaced by a symlink after enumeration.
|
||||
if entry.path.canonicalize()? != entry.path {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "Font file changed"));
|
||||
}
|
||||
let (offset, length) = if let Some(range) = files.get(&entry.path) {
|
||||
*range
|
||||
} else {
|
||||
let bytes = std::fs::read(&entry.path)?;
|
||||
let range = (data.len(), bytes.len());
|
||||
data.extend(bytes);
|
||||
files.insert(entry.path.clone(), range);
|
||||
range
|
||||
};
|
||||
faces.push(Face {
|
||||
weight: entry.weight,
|
||||
style: if entry.italic { "italic" } else { "normal" },
|
||||
offset,
|
||||
length,
|
||||
});
|
||||
}
|
||||
if faces.is_empty() {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::NotFound, "No installed user font family"));
|
||||
}
|
||||
let header = serde_json::to_vec(&faces)?;
|
||||
let mut out = (header.len() as u32).to_le_bytes().to_vec();
|
||||
out.extend(header);
|
||||
out.extend(data);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod imp {
|
||||
use objc2_core_foundation::{CFArray, CFDictionary, CFNumber, CFString, CFType};
|
||||
use objc2_core_foundation::{CFArray, CFDictionary, CFNumber, CFString, CFType, CFURL};
|
||||
use objc2_core_text::{
|
||||
CTFontCollection, CTFontDescriptor, CTFontSymbolicTraits, kCTFontFamilyNameAttribute, kCTFontSymbolicTrait,
|
||||
kCTFontTraitsAttribute,
|
||||
kCTFontTraitsAttribute, kCTFontURLAttribute, kCTFontWeightTrait,
|
||||
};
|
||||
|
||||
pub(crate) fn user_faces() -> Vec<super::UserFace> {
|
||||
let mut roots = vec![std::path::PathBuf::from("/Library/Fonts")];
|
||||
if let Some(home) = std::env::var_os("HOME") {
|
||||
roots.push(std::path::PathBuf::from(home).join("Library/Fonts"));
|
||||
}
|
||||
let roots: Vec<_> = roots.into_iter().filter_map(|r| r.canonicalize().ok()).collect();
|
||||
// SAFETY: CoreText descriptors carry documented CFString, CFURL and trait dictionary values.
|
||||
unsafe {
|
||||
let collection = CTFontCollection::from_available_fonts(None);
|
||||
let Some(descriptors) = collection.matching_font_descriptors() else { return Vec::new() };
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
descriptors
|
||||
.cast_unchecked::<CTFontDescriptor>()
|
||||
.iter()
|
||||
.filter_map(|d| {
|
||||
let family = d.attribute(kCTFontFamilyNameAttribute)?.downcast::<CFString>().ok()?.to_string();
|
||||
let path = d.attribute(kCTFontURLAttribute)?.downcast::<CFURL>().ok()?.to_file_path()?;
|
||||
let path = super::user_font_path(&path, &roots)?;
|
||||
let traits = d.attribute(kCTFontTraitsAttribute)?.downcast::<CFDictionary>().ok()?;
|
||||
let traits = traits.cast_unchecked::<CFString, CFType>();
|
||||
let symbolic = traits
|
||||
.get(kCTFontSymbolicTrait)
|
||||
.and_then(|n| n.downcast::<CFNumber>().ok())
|
||||
.and_then(|n| n.as_i64())
|
||||
.unwrap_or(0) as u32;
|
||||
let weight = traits
|
||||
.get(kCTFontWeightTrait)
|
||||
.and_then(|n| n.downcast::<CFNumber>().ok())
|
||||
.and_then(|n| n.as_f64())
|
||||
.unwrap_or(0.0);
|
||||
// CoreText's normalized weight values corresponding to CSS's nine standard weights.
|
||||
let weight = [
|
||||
(-0.8, 100),
|
||||
(-0.6, 200),
|
||||
(-0.4, 300),
|
||||
(0.0, 400),
|
||||
(0.23, 500),
|
||||
(0.3, 600),
|
||||
(0.4, 700),
|
||||
(0.56, 800),
|
||||
(0.62, 900),
|
||||
]
|
||||
.into_iter()
|
||||
.min_by(|(a, _), (b, _)| (weight - a).abs().total_cmp(&(weight - b).abs()))?
|
||||
.1;
|
||||
let italic = symbolic & CTFontSymbolicTraits::TraitItalic.0 != 0;
|
||||
if !seen.insert((family.clone(), path.clone(), weight, italic)) {
|
||||
return None;
|
||||
}
|
||||
Some(super::UserFace { family, path, weight, italic })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Every face CoreText makes available to this process, as (family, fixed pitch).
|
||||
pub(crate) fn list(_refresh: bool) -> Vec<(String, bool)> {
|
||||
// SAFETY: CoreText's documented types: the matching descriptors array
|
||||
@@ -210,6 +359,92 @@ mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
#[test]
|
||||
fn selects_only_regular_bold_and_matching_italics_from_dense_families() {
|
||||
let entries: Vec<_> = [false, true]
|
||||
.into_iter()
|
||||
.flat_map(|italic| {
|
||||
(100..=900).step_by(100).map(move |weight| UserFace {
|
||||
family: "CJK".into(),
|
||||
path: format!("{weight}-{italic}.ttf").into(),
|
||||
weight,
|
||||
italic,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let selected = family_faces(" cjk ", &entries);
|
||||
assert_eq!(
|
||||
selected.iter().map(|f| (f.weight, f.italic)).collect::<Vec<_>>(),
|
||||
[(400, false), (700, false), (400, true), (700, true),]
|
||||
);
|
||||
assert!(family_faces("unknown", &entries).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_nearest_available_weights_once_with_optional_italics() {
|
||||
let entries: Vec<_> = [(300, false), (500, false), (800, false), (500, true)]
|
||||
.into_iter()
|
||||
.map(|(weight, italic)| UserFace {
|
||||
family: "Sparse".into(),
|
||||
path: format!("{weight}-{italic}.ttf").into(),
|
||||
weight,
|
||||
italic,
|
||||
})
|
||||
.collect();
|
||||
let selected = family_faces("Sparse", &entries);
|
||||
assert_eq!(
|
||||
selected.iter().map(|f| (f.weight, f.italic)).collect::<Vec<_>>(),
|
||||
[(300, false), (800, false), (500, true),]
|
||||
);
|
||||
assert_eq!(family_faces("Sparse", &entries[..1]).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundle_only_reads_enumerated_family_faces() {
|
||||
let root = std::env::current_dir().unwrap().join(format!("../../.font-bundle-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let root = root.canonicalize().unwrap();
|
||||
let regular = root.join("regular.ttf");
|
||||
let bold = root.join("bold.ttf");
|
||||
std::fs::write(®ular, [1, 2, 3]).unwrap();
|
||||
std::fs::write(&bold, [4, 5]).unwrap();
|
||||
let entries = [
|
||||
UserFace { family: "Test Nerd Font".into(), path: regular.clone(), weight: 400, italic: false },
|
||||
UserFace { family: "Test Nerd Font".into(), path: bold, weight: 700, italic: false },
|
||||
// A non-selected face is never opened, even if its file has disappeared.
|
||||
UserFace { family: "Test Nerd Font".into(), path: root.join("thin.ttf"), weight: 100, italic: false },
|
||||
];
|
||||
let result = bundle_family("test nerd font", &entries).unwrap();
|
||||
let len = u32::from_le_bytes(result[..4].try_into().unwrap()) as usize;
|
||||
let faces: serde_json::Value = serde_json::from_slice(&result[4..4 + len]).unwrap();
|
||||
assert_eq!(faces[0]["weight"], 400);
|
||||
assert_eq!(faces[1]["weight"], 700);
|
||||
assert_eq!(faces.as_array().unwrap().len(), 2);
|
||||
assert_eq!(&result[4 + len..], &[1, 2, 3, 4, 5]);
|
||||
// Existing files are not inputs: neither paths nor unenumerated families grant access.
|
||||
assert!(bundle_family(regular.to_str().unwrap(), &entries).is_err());
|
||||
assert!(bundle_family("Unenumerated", &entries).is_err());
|
||||
assert!(user_font_path(®ular, &[]).is_none());
|
||||
assert!(user_font_path(®ular, std::slice::from_ref(&root)).is_some());
|
||||
// Multiple selected descriptors in a collection still transfer the file only once.
|
||||
let shared = [
|
||||
UserFace { family: "Collection".into(), path: regular.clone(), weight: 400, italic: false },
|
||||
UserFace { family: "Collection".into(), path: regular, weight: 700, italic: false },
|
||||
];
|
||||
let result = bundle_family("Collection", &shared).unwrap();
|
||||
let len = u32::from_le_bytes(result[..4].try_into().unwrap()) as usize;
|
||||
let faces: serde_json::Value = serde_json::from_slice(&result[4..4 + len]).unwrap();
|
||||
assert_eq!(faces[0]["offset"], faces[1]["offset"]);
|
||||
assert_eq!(&result[4 + len..], &[1, 2, 3]);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let link = root.join("outside.ttf");
|
||||
std::os::unix::fs::symlink(std::env::current_exe().unwrap(), &link).unwrap();
|
||||
assert!(user_font_path(&link, std::slice::from_ref(&root)).is_none());
|
||||
}
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
fn fam(name: &str, monospaced: bool) -> FontFamily {
|
||||
FontFamily { name: name.into(), monospaced }
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ parking_lot.workspace = true
|
||||
dunce.workspace = true
|
||||
dirs.workspace = true
|
||||
uuid.workspace = true
|
||||
tempfile.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "io-util", "test-util"] }
|
||||
tempfile.workspace = true
|
||||
@@ -1,8 +1,73 @@
|
||||
use super::Channel;
|
||||
use crate::Host;
|
||||
use ide_core::IdeResult;
|
||||
use ide_core::{IdeResult, RequestId};
|
||||
use ide_vfs::FileEntry;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub async fn entry_kind(host: &Host, path: PathBuf) -> IdeResult<ide_vfs::EntryKind> {
|
||||
host.blocking(move || {
|
||||
let meta = std::fs::metadata(path)?;
|
||||
Ok(if meta.is_dir() { ide_vfs::EntryKind::Dir } else { ide_vfs::EntryKind::File })
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn compare_directories(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
left: PathBuf,
|
||||
right: PathBuf,
|
||||
request: RequestId,
|
||||
on_progress: Channel<ide_vfs::DirectoryCompareProgress>,
|
||||
) -> IdeResult<Vec<ide_vfs::DirectoryCompareEntry>> {
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
let last = std::cell::Cell::new(std::time::Instant::now() - std::time::Duration::from_secs(1));
|
||||
ide_vfs::compare_directories(&left, &right, Some(&project.root), &project.exclude_globs(), &cancel, |p| {
|
||||
// Bound IPC traffic even when hashing multi-gigabyte files.
|
||||
if last.get().elapsed() >= std::time::Duration::from_millis(80) || p.total == Some(p.compared) {
|
||||
let _ = on_progress.send(p);
|
||||
last.set(std::time::Instant::now());
|
||||
}
|
||||
})
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn copy_merge(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
source_root: PathBuf,
|
||||
destination_root: PathBuf,
|
||||
path: PathBuf,
|
||||
overwrite: bool,
|
||||
) -> IdeResult<()> {
|
||||
if path.as_os_str().is_empty() || path.components().any(|c| !matches!(c, std::path::Component::Normal(_))) {
|
||||
return Err(ide_core::IdeError::invalid("expected a relative comparison entry path"));
|
||||
}
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || {
|
||||
let from = source_root.join(&path);
|
||||
let to = destination_root.join(&path);
|
||||
if overwrite {
|
||||
project.history.record_deletion(&to, DELETE_SNAPSHOT_LIMIT);
|
||||
}
|
||||
ide_vfs::copy_merge(
|
||||
&from,
|
||||
&to,
|
||||
overwrite,
|
||||
Some(&project.root),
|
||||
&project.exclude_globs(),
|
||||
(&source_root, &destination_root),
|
||||
)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Files of a deleted folder snapshotted in Local History.
|
||||
const DELETE_SNAPSHOT_LIMIT: usize = 2000;
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::rpc::Dispatcher;
|
||||
use super::build::load;
|
||||
use ide_build::compile;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
|
||||
use ide_lsp::jdtls::JavaLaunchInfo;
|
||||
use ide_lsp::jdtls::{JavaBuildStatus, JavaLaunchInfo};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Cancellable with `cancel_request(request)`.
|
||||
@@ -39,23 +39,42 @@ async fn resolve_launch(
|
||||
let project = host.project(window)?;
|
||||
let module = project.root.join(module);
|
||||
let settings = project.settings.effective();
|
||||
// Let jdtls finish its build before the external compiler writes Kotlin/Scala classes.
|
||||
let mut info = project.lsp.java_launch(&module, test, build, cancel).await?;
|
||||
let (model, external, delegated) = {
|
||||
let project = project.clone();
|
||||
let settings = settings.clone();
|
||||
let module = module.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = load(&project.root, &project.build_cache_dir(), &settings);
|
||||
let external = build && compile::launch_has_non_java_sources(&project.root, &model, &module, test);
|
||||
let delegated = external
|
||||
&& model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
|
||||
(model, external, delegated)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
};
|
||||
let external_build = if delegated { Some(project.lsp.java_external_build(&module, cancel).await?) } else { None };
|
||||
let mut info = project.lsp.java_launch(&module, test, build && !delegated, cancel).await?;
|
||||
let lsp_ms = started.elapsed().as_millis();
|
||||
let data_dir = host.data_dir.clone();
|
||||
let cancel = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let built = if build && compile::has_non_java_sources(&module) {
|
||||
compile::build_for_launch(
|
||||
&project.root,
|
||||
&load(&project.root, &project.build_cache_dir(), &settings),
|
||||
&module,
|
||||
test,
|
||||
&cancel,
|
||||
)?
|
||||
let _external_build = external_build;
|
||||
let built = if external {
|
||||
compile::build_for_launch(&project.root, &model, &module, test, &cancel)?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let built = if delegated {
|
||||
let (snapshot, copies) = snapshot_outputs(&mut info, &built, &cancel)?;
|
||||
project.java_launch_outputs.lock().push(snapshot);
|
||||
info.build = Some(JavaBuildStatus::Succeeded);
|
||||
info.errors.clear();
|
||||
info.error_count = 0;
|
||||
copies
|
||||
} else {
|
||||
built
|
||||
};
|
||||
let mut class_paths: Vec<String> = built.iter().map(|p| p.to_string_lossy().into_owned()).collect();
|
||||
for p in std::mem::take(&mut info.class_paths) {
|
||||
if !class_paths.contains(&p) {
|
||||
@@ -103,6 +122,35 @@ async fn resolve_launch(
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
fn snapshot_outputs(
|
||||
info: &mut JavaLaunchInfo,
|
||||
built: &[PathBuf],
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<(tempfile::TempDir, Vec<PathBuf>)> {
|
||||
let snapshot = tempfile::Builder::new().prefix("openidea-java-launch-").tempdir()?;
|
||||
let mut copies = Vec::new();
|
||||
for (index, source) in built.iter().enumerate() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let dest = snapshot.path().join(index.to_string());
|
||||
ide_vfs::copy(source, &dest)?;
|
||||
let original = source.to_string_lossy();
|
||||
info.class_paths.retain(|p| p != original.as_ref());
|
||||
let mut modular = false;
|
||||
for path in &mut info.module_paths {
|
||||
if path == original.as_ref() {
|
||||
*path = dest.to_string_lossy().into_owned();
|
||||
modular = true;
|
||||
}
|
||||
}
|
||||
if !modular {
|
||||
copies.push(dest);
|
||||
}
|
||||
}
|
||||
Ok((snapshot, copies))
|
||||
}
|
||||
|
||||
/// Port of java-debug's DAP server inside the jdtls serving `module` (started on demand).
|
||||
pub async fn java_debug_server(host: &Host, window: &str, module: PathBuf) -> IdeResult<u16> {
|
||||
host.require_trust(window)?;
|
||||
@@ -132,3 +180,43 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("java_debug_server", |c| async move { java_debug_server(&c.host, &c.window, c.arg("module")?).await });
|
||||
d.add("java_build_workspace", |c| async move { java_build_workspace(&c.host, &c.window, c.arg("module")?).await });
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn launch_snapshots_survive_jdt_overwrites_and_replace_module_outputs() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let app = root.path().join("app/target/classes");
|
||||
let lib = root.path().join("lib/target/classes");
|
||||
for dir in [&app, &lib] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
std::fs::write(dir.join("Channel.class"), "Maven bytecode").unwrap();
|
||||
}
|
||||
let mut info = JavaLaunchInfo {
|
||||
class_paths: vec![app.to_string_lossy().into_owned(), "stdlib.jar".into()],
|
||||
module_paths: vec![lib.to_string_lossy().into_owned()],
|
||||
..Default::default()
|
||||
};
|
||||
let (snapshot, paths) =
|
||||
snapshot_outputs(&mut info, &[app.clone(), lib.clone()], &CancellationToken::new()).unwrap();
|
||||
assert_eq!(paths, [snapshot.path().join("0")]);
|
||||
assert_eq!(info.class_paths, ["stdlib.jar"]);
|
||||
assert_eq!(info.module_paths, [snapshot.path().join("1").to_string_lossy().into_owned()]);
|
||||
std::fs::write(app.join("Channel.class"), "JDT error stub").unwrap();
|
||||
std::fs::remove_dir_all(lib).unwrap();
|
||||
for index in ["0", "1"] {
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(snapshot.path().join(index).join("Channel.class")).unwrap(),
|
||||
"Maven bytecode"
|
||||
);
|
||||
}
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
assert_eq!(
|
||||
snapshot_outputs(&mut info, &[app], &cancel).unwrap_err().kind,
|
||||
ide_core::error::ErrorKind::Cancelled
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -83,12 +83,18 @@ pub async fn lsp_implementations(
|
||||
result
|
||||
}
|
||||
|
||||
/// Contents of a virtual document (library class, decompiled code) that a
|
||||
/// language server returned a non-`file:` URI for. Cached per project.
|
||||
/// Contents of a read-only language-server document, including JDT library
|
||||
/// classes and disk class files. Cached per project.
|
||||
pub async fn lsp_virtual_document(host: &Host, window: &str, uri: String) -> IdeResult<VirtualDocument> {
|
||||
host.project(window)?.lsp.virtual_document(&uri).await
|
||||
}
|
||||
|
||||
/// Opens compiled classes through JDT, with project source taking priority on disk.
|
||||
pub async fn lsp_resolve_class_file(host: &Host, window: &str, path: std::path::PathBuf) -> IdeResult<String> {
|
||||
let archive = ide_vfs::split_archive_path(&path);
|
||||
host.project(window)?.lsp.java_class_file(&path, archive).await
|
||||
}
|
||||
|
||||
/// References of the symbol at `pos`. `project_wide` also searches project files
|
||||
/// outside the language server's analysis scope; bulk scans over many symbols
|
||||
/// leave it off. Cancel with `cancel_request(request)`.
|
||||
@@ -290,6 +296,58 @@ pub async fn lsp_execute_command(host: &Host, window: &str, doc: DocId, command:
|
||||
host.project(window)?.lsp.execute_command(doc, command).await
|
||||
}
|
||||
|
||||
/// Resolves an interactive command without applying edits or executing it.
|
||||
pub async fn lsp_resolve_command(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
server: ServerId,
|
||||
command: Command,
|
||||
answers: Vec<FormAnswer>,
|
||||
) -> IdeResult<Option<CommandForm>> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = lsp.resolve_command(doc, server, command, answers, cancel).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Applies an explicitly invoked action after the interactive answers have been validated.
|
||||
pub async fn lsp_execute_code_action(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
action: CodeAction,
|
||||
answers: Vec<FormAnswer>,
|
||||
) -> IdeResult<Vec<ide_core::IpcPath>> {
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = async {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(ide_core::IdeError::cancelled());
|
||||
}
|
||||
if let Some(edit) = action.edit {
|
||||
let documents = project.documents.clone();
|
||||
tokio::task::spawn_blocking(move || apply_edit(&documents, &edit))
|
||||
.await
|
||||
.map_err(|e| ide_core::IdeError::internal(e.to_string()))??;
|
||||
}
|
||||
match action.command {
|
||||
Some(command) => project
|
||||
.lsp
|
||||
.execute_action_command(doc, action.server, command, answers, cancel)
|
||||
.await
|
||||
.map(|paths| paths.into_iter().map(ide_core::IpcPath::from).collect()),
|
||||
None => Ok(Vec::new()),
|
||||
}
|
||||
}
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Commands of this module the remote server answers.
|
||||
pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("lsp_completion", |c| async move {
|
||||
@@ -315,6 +373,10 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("lsp_implementations", |c| async move {
|
||||
lsp_implementations(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("positions")?).await
|
||||
});
|
||||
d.add(
|
||||
"lsp_resolve_class_file",
|
||||
|c| async move { lsp_resolve_class_file(&c.host, &c.window, c.arg("path")?).await },
|
||||
);
|
||||
d.add("lsp_virtual_document", |c| async move { lsp_virtual_document(&c.host, &c.window, c.arg("uri")?).await });
|
||||
d.add("lsp_references", |c| async move {
|
||||
lsp_references(
|
||||
@@ -374,6 +436,29 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("lsp_resend_diagnostics", |c| async move { lsp_resend_diagnostics(&c.host, &c.window) });
|
||||
d.add("lsp_restart", |c| async move { lsp_restart(&c.host, &c.window, c.arg("server")?).await });
|
||||
d.add("apply_workspace_edit", |c| async move { apply_workspace_edit(&c.host, &c.window, c.arg("edit")?) });
|
||||
d.add("lsp_resolve_command", |c| async move {
|
||||
lsp_resolve_command(
|
||||
&c.host,
|
||||
&c.window,
|
||||
c.arg("request")?,
|
||||
c.arg("doc")?,
|
||||
c.arg("server")?,
|
||||
c.arg("command")?,
|
||||
c.arg("answers")?,
|
||||
)
|
||||
.await
|
||||
});
|
||||
d.add("lsp_execute_code_action", |c| async move {
|
||||
lsp_execute_code_action(
|
||||
&c.host,
|
||||
&c.window,
|
||||
c.arg("request")?,
|
||||
c.arg("doc")?,
|
||||
c.arg("action")?,
|
||||
c.arg("answers")?,
|
||||
)
|
||||
.await
|
||||
});
|
||||
d.add("lsp_execute_command", |c| async move {
|
||||
lsp_execute_command(&c.host, &c.window, c.arg("doc")?, c.arg("command")?).await
|
||||
});
|
||||
|
||||
@@ -172,7 +172,10 @@ pub fn set_settings(
|
||||
host.apply_proxy();
|
||||
}
|
||||
// A new interpreter / toolchain / server executable restarts the language servers it affects.
|
||||
if ["languages", "tools", "languageServers"].iter().any(|k| key == *k || key.starts_with(&format!("{k}."))) {
|
||||
if ["languages", "tools", "languageServers", "projectStructure"]
|
||||
.iter()
|
||||
.any(|k| key == *k || key.starts_with(&format!("{k}.")))
|
||||
{
|
||||
for project in affected() {
|
||||
let lsp = project.lsp.clone();
|
||||
host.runtime.spawn(async move { lsp.reconfigure().await });
|
||||
|
||||
@@ -5,6 +5,78 @@ use crate::rpc::Dispatcher;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_run::RunConfig;
|
||||
|
||||
fn application_cache(project: &crate::project::Project, id: &str) -> std::path::PathBuf {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hash = std::collections::hash_map::DefaultHasher::new();
|
||||
id.hash(&mut hash);
|
||||
project.cache_dir.join("application-update").join(format!("{:x}", hash.finish()))
|
||||
}
|
||||
|
||||
pub async fn run_application_build(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
config: RunConfig,
|
||||
module: std::path::PathBuf,
|
||||
) -> IdeResult<RunConfig> {
|
||||
host.require_trust(window)?;
|
||||
if config.kind != "spring-boot" || config.extras.target.as_ref().is_some_and(|t| !t.is_empty()) {
|
||||
return Err(IdeError::invalid("Application resource updates require a local Spring Boot configuration"));
|
||||
}
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &project.settings.effective());
|
||||
let plan = ide_build::application_update::plan(
|
||||
&project.root,
|
||||
&model,
|
||||
&module,
|
||||
&application_cache(&project, &config.id),
|
||||
)?;
|
||||
let mut env = plan.env;
|
||||
env.extend(config.env);
|
||||
Ok(RunConfig {
|
||||
id: format!("application-build:{}", config.id),
|
||||
name: format!("Update {}", config.name),
|
||||
kind: plan.kind.into(),
|
||||
command: plan.command,
|
||||
args: plan.args,
|
||||
cwd: Some(project.root.join(plan.cwd).into()),
|
||||
env,
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: ide_run::RunExtras {
|
||||
include_system_env: config.extras.include_system_env,
|
||||
env_files: config.extras.env_files,
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
pub async fn run_application_publish(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
config: RunConfig,
|
||||
class_paths: Vec<String>,
|
||||
main_class: String,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
ide_build::application_update::publish(
|
||||
&project.root,
|
||||
&application_cache(&project, &config.id),
|
||||
&class_paths,
|
||||
&main_class,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Configuration templates: per-type defaults applied to new configurations.
|
||||
pub fn run_templates(host: &Host, window: &str) -> IdeResult<Vec<RunConfig>> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
@@ -134,6 +206,12 @@ pub async fn run_tomcat_update(host: &Host, window: &str, config: RunConfig, mod
|
||||
|
||||
/// Commands of this module the remote server answers.
|
||||
pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("run_application_build", |c| async move {
|
||||
run_application_build(&c.host, &c.window, c.arg("config")?, c.arg("module")?).await
|
||||
});
|
||||
d.add("run_application_publish", |c| async move {
|
||||
run_application_publish(&c.host, &c.window, c.arg("config")?, c.arg("classPaths")?, c.arg("mainClass")?).await
|
||||
});
|
||||
d.add("run_tomcat_home", |c| async move { run_tomcat_home(&c.host, &c.window, c.arg("home")?).await });
|
||||
d.add("run_tomcat_artifacts", |c| async move { run_tomcat_artifacts(&c.host, &c.window).await });
|
||||
d.add("run_tomcat_build", |c| async move { run_tomcat_build(&c.host, &c.window, c.arg("config")?).await });
|
||||
|
||||
@@ -16,11 +16,15 @@ pub fn spawn(
|
||||
options.args.clear();
|
||||
options.env = global.env;
|
||||
}
|
||||
// Python › "Activate virtualenv": typed into the new shell, like PyCharm.
|
||||
let activation =
|
||||
host.project(window).ok().filter(|p| p.is_trusted()).and_then(|p| {
|
||||
ide_sdk::apply::terminal_activation(&p.root, &p.settings.effective(), options.shell.as_deref())
|
||||
});
|
||||
let (shell, args) = ide_terminal::resolve_shell(options.shell.as_deref(), &options.args);
|
||||
options.shell = Some(shell.clone());
|
||||
options.args = args;
|
||||
// Python › "Activate virtualenv": typed into the same shell the PTY starts.
|
||||
let activation = host
|
||||
.project(window)
|
||||
.ok()
|
||||
.filter(|p| p.is_trusted())
|
||||
.and_then(|p| ide_sdk::apply::terminal_activation(&p.root, &p.settings.effective(), &shell));
|
||||
let info = host.terminals.spawn(options, host.window_sink(window), Box::new(move |chunk| on_output(chunk)))?;
|
||||
if let Some(line) = activation {
|
||||
let _ = host.terminals.write(info.id, &format!(" {line}\r"));
|
||||
|
||||
@@ -100,11 +100,11 @@ pub fn jdk_download_vendors(_host: &Host, _window: &str) -> Vec<JdkVendor> {
|
||||
/// Java versions `vendor` publishes; cancellable with `cancel_request(request)`.
|
||||
pub async fn jdk_download_releases(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
_window: &str,
|
||||
vendor: String,
|
||||
request: RequestId,
|
||||
) -> IdeResult<JdkReleases> {
|
||||
let tools = tools(host, window)?;
|
||||
let tools = Tools::new(&host.data_dir);
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::task::spawn_blocking(move || tools.jdk_releases(&vendor, &cancel)).await.map_err(join_err);
|
||||
host.end_request(request);
|
||||
@@ -123,14 +123,14 @@ pub fn jdk_download_location(host: &Host, _window: &str) -> IdeResult<ide_core::
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn jdk_download(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
_window: &str,
|
||||
vendor: String,
|
||||
version: u32,
|
||||
location: Option<PathBuf>,
|
||||
request: RequestId,
|
||||
on_event: Channel<InstallEvent>,
|
||||
) -> IdeResult<Sdk> {
|
||||
let tools = tools(host, window)?;
|
||||
let tools = Tools::new(&host.data_dir);
|
||||
let location = location.filter(|p| !p.as_os_str().is_empty());
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
|
||||
@@ -746,6 +746,33 @@ pub async fn vcs_remove_worktree(
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.remove_worktree(&path, force))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_compare_scope(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<CompareScope> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || Ok(project.repos().compare_scope(&paths))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_compare_paths(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
paths: Vec<PathBuf>,
|
||||
revision: String,
|
||||
repositories: Option<Vec<PathBuf>>,
|
||||
request: RequestId,
|
||||
) -> IdeResult<CompareResult> {
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let settings = project.settings.effective();
|
||||
if project.is_trusted() {
|
||||
apply_git_executable(&settings);
|
||||
}
|
||||
project.repos().compare_paths(&paths, &revision, repositories.as_deref(), &cancel)
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Compare with Local: tracked files that differ between `rev` and the working tree.
|
||||
pub async fn vcs_diff_with_worktree(
|
||||
host: &Host,
|
||||
@@ -1040,6 +1067,18 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("vcs_remove_worktree", |c| async move {
|
||||
vcs_remove_worktree(&c.host, &c.window, c.arg("repo")?, c.arg("path")?, c.arg("force")?).await
|
||||
});
|
||||
d.add("vcs_compare_scope", |c| async move { vcs_compare_scope(&c.host, &c.window, c.arg("paths")?).await });
|
||||
d.add("vcs_compare_paths", |c| async move {
|
||||
vcs_compare_paths(
|
||||
&c.host,
|
||||
&c.window,
|
||||
c.arg("paths")?,
|
||||
c.arg("revision")?,
|
||||
c.arg("repositories")?,
|
||||
c.arg("request")?,
|
||||
)
|
||||
.await
|
||||
});
|
||||
d.add("vcs_diff_with_worktree", |c| async move {
|
||||
vcs_diff_with_worktree(&c.host, &c.window, c.arg("repo")?, c.arg("rev")?).await
|
||||
});
|
||||
|
||||
@@ -42,6 +42,8 @@ pub struct Project {
|
||||
pub detected_roots: Arc<RwLock<Vec<SourceFolder>>>,
|
||||
/// Per-project cache directory (build tool sync results…).
|
||||
pub cache_dir: PathBuf,
|
||||
/// Launch snapshots stay alive while any JVM of this project may load classes.
|
||||
pub(crate) java_launch_outputs: Mutex<Vec<tempfile::TempDir>>,
|
||||
/// Database tool window: data sources and their connections.
|
||||
pub db: Arc<ide_db::DbManager>,
|
||||
/// HTTP Client responses (IDEA's `.idea/httpRequests`), in the app data dir.
|
||||
@@ -139,8 +141,18 @@ impl Host {
|
||||
ide_sdk::apply::configure_server(cfg, root, server_root, &effective);
|
||||
ide_sdk::java::cap_java_home(cfg, &ide_sdk::java::installed_jdks());
|
||||
if cfg.name == "jdtls" {
|
||||
let bundles: Vec<PathBuf> =
|
||||
ide_tools::managed_bundle(&data_dir, "java-debug").into_iter().collect();
|
||||
ide_lsp::jdtls::configure_source_paths(
|
||||
cfg,
|
||||
ide_workspace::roots::unmanaged_java_source_paths(
|
||||
root,
|
||||
server_root,
|
||||
&effective.project_structure,
|
||||
),
|
||||
);
|
||||
let bundles: Vec<PathBuf> = ide_tools::managed_bundle(&data_dir, "java-debug")
|
||||
.into_iter()
|
||||
.chain(ide_sdk::java::usages_bundle(&data_dir))
|
||||
.collect();
|
||||
let min_java = ide_sdk::java::jdtls_min_java(cfg);
|
||||
let jdks = ide_sdk::java::jdtls_jdks(min_java, &data_dir);
|
||||
let lombok = ide_sdk::lombok::lombok_agent(
|
||||
@@ -356,6 +368,7 @@ impl Host {
|
||||
syntax,
|
||||
detected_roots,
|
||||
cache_dir: self.data_dir.join("cache").join(&project_key),
|
||||
java_launch_outputs: Mutex::new(Vec::new()),
|
||||
db,
|
||||
http_history,
|
||||
agents,
|
||||
@@ -471,6 +484,7 @@ impl Host {
|
||||
syntax,
|
||||
detected_roots: Arc::default(),
|
||||
cache_dir: self.data_dir.join("cache").join(&project_key),
|
||||
java_launch_outputs: Mutex::new(Vec::new()),
|
||||
db,
|
||||
http_history,
|
||||
agents,
|
||||
|
||||
@@ -179,6 +179,7 @@ impl Dispatcher {
|
||||
})
|
||||
.add("cancel_task", |c| async move { Ok(ide_core::task::cancel(c.arg::<TaskId>("id")?)) })
|
||||
.add("fs_read_dir", |c| async move { ops::fs::read_dir(&c.host, &c.window, c.arg("path")?) })
|
||||
.add("fs_entry_kind", |c| async move { ops::fs::entry_kind(&c.host, c.arg("path")?).await })
|
||||
.add("fs_create_file", |c| async move { ops::fs::create_file(&c.host, &c.window, c.arg("path")?) })
|
||||
.add("fs_create_file_bytes", |c| async move {
|
||||
ops::fs::create_file_bytes(&c.host, c.arg("path")?, c.arg("data")?).await
|
||||
@@ -190,6 +191,28 @@ impl Dispatcher {
|
||||
})
|
||||
.add("fs_delete", |c| async move { ops::fs::delete(&c.host, &c.window, c.arg("path")?).await })
|
||||
.add("fs_copy", |c| async move { ops::fs::copy(&c.host, c.arg("from")?, c.arg("to")?).await })
|
||||
.add("fs_copy_merge", |c| async move {
|
||||
ops::fs::copy_merge(
|
||||
&c.host,
|
||||
&c.window,
|
||||
c.arg("sourceRoot")?,
|
||||
c.arg("destinationRoot")?,
|
||||
c.arg("path")?,
|
||||
c.arg("overwrite")?,
|
||||
)
|
||||
.await
|
||||
})
|
||||
.add("fs_compare_directories", |c| async move {
|
||||
ops::fs::compare_directories(
|
||||
&c.host,
|
||||
&c.window,
|
||||
c.arg("left")?,
|
||||
c.arg("right")?,
|
||||
c.arg("request")?,
|
||||
c.sender("onProgress")?,
|
||||
)
|
||||
.await
|
||||
})
|
||||
.add("fs_read_text", |c| async move { ops::fs::read_text(&c.host, &c.window, c.arg("path")?).await })
|
||||
.add("doc_open", |c| async move { ops::doc::open(&c.host, &c.window, c.arg("path")?).await })
|
||||
.add("doc_close", |c| async move { ops::doc::close(&c.host, &c.window, c.arg("doc")?) })
|
||||
|
||||
@@ -175,6 +175,30 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
matches!(
|
||||
cmd,
|
||||
"app_info"
|
||||
| "app_build_info"
|
||||
| "app_log_location"
|
||||
| "app_check_update"
|
||||
| "app_startup_update_check"
|
||||
| "app_install_update"
|
||||
| "caches_schedule_invalidation"
|
||||
| "clear_caches"
|
||||
| "clipboard_file_list"
|
||||
| "clipboard_has_files"
|
||||
| "clipboard_set_file_list"
|
||||
| "jdk_download_vendors"
|
||||
| "jdk_download_releases"
|
||||
| "jdk_download_location"
|
||||
| "jdk_download"
|
||||
| "run_system_env"
|
||||
| "run_gradle_jvm_args_script"
|
||||
| "proxy_check_connection"
|
||||
| "docker_settings"
|
||||
| "docker_save_settings"
|
||||
| "docker_set_registry_password"
|
||||
| "docker_run_env"
|
||||
| "db_console_path"
|
||||
| "db_export_file"
|
||||
| "vcs_write_patch"
|
||||
| "app_metrics"
|
||||
| "app_quit"
|
||||
| "app_cancel_quit"
|
||||
@@ -235,6 +259,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
| "agent_registry_remove"
|
||||
| "coverage_import"
|
||||
| "system_font_families"
|
||||
| "user_font_data"
|
||||
| "plugin_subscribe"
|
||||
| "plugin_list"
|
||||
| "plugin_set_active_file"
|
||||
@@ -276,6 +301,8 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
| "vcs_remotes"
|
||||
| "vcs_worktrees"
|
||||
| "vcs_diff_with_worktree"
|
||||
| "vcs_compare_scope"
|
||||
| "vcs_compare_paths"
|
||||
| "vcs_diff_revisions"
|
||||
| "vcs_merge_base"
|
||||
| "vcs_shelves"
|
||||
|
||||
@@ -104,7 +104,7 @@ async fn properties_search_git_and_document_coordinates_agree() {
|
||||
"main",
|
||||
opened.id,
|
||||
opened.version,
|
||||
ChangeSet { changes: vec![TextChange { from: 10, to: 16, insert: "世界".into() }] },
|
||||
ChangeSet { changes: vec![TextChange { from: 10, to: 16, insert: r"\u4E16\u754C".into() }] },
|
||||
)
|
||||
.unwrap();
|
||||
let hunks = vcs::vcs_line_hunks(&host, "main", path.clone()).await.unwrap();
|
||||
@@ -129,7 +129,7 @@ async fn properties_search_git_and_document_coordinates_agree() {
|
||||
assert!(project.documents.snapshot(opened.id).unwrap().version > snap.version);
|
||||
assert!(vcs::vcs_line_hunks(&host, "main", path.clone()).await.unwrap().is_empty());
|
||||
// Partial commits identify hunks in displayed line coordinates as well.
|
||||
let partial_text = displayed.replace("target", "世界").replace("logical", "changed");
|
||||
let partial_text = displayed.replace("target", r"\u4E16\u754C").replace("logical", "changed");
|
||||
project.documents.replace_all(opened.id, &partial_text).unwrap();
|
||||
doc::save(&host, "main", opened.id).await.unwrap();
|
||||
let hunks = ide_vcs::diff_hunks(displayed, &partial_text);
|
||||
@@ -169,7 +169,7 @@ async fn properties_search_git_and_document_coordinates_agree() {
|
||||
"main",
|
||||
RequestId(520),
|
||||
query,
|
||||
"世界".into(),
|
||||
r"\u4E16\u754C".into(),
|
||||
false,
|
||||
vec![ide_search::ReplaceTarget {
|
||||
path: closed_path.clone().into(),
|
||||
@@ -181,5 +181,6 @@ async fn properties_search_git_and_document_coordinates_agree() {
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&closed_path).unwrap(), r"value=\u4F60\u597D\uD83D\uDE00\u4E16\u754C");
|
||||
assert!(project.documents.by_path(&closed_path).is_none());
|
||||
assert_eq!(project.text_of(&closed_path).unwrap(), "value=你好😀世界");
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -94,6 +94,39 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
let entries = invoke(&peer, "fs_read_dir", json!({ "path": project })).await.unwrap();
|
||||
assert!(entries.as_array().unwrap().iter().any(|e| e["name"] == "src"), "{entries}");
|
||||
|
||||
// Directory comparisons, streamed progress and confirmed copies share the remote filesystem.
|
||||
let left = project.join("compare-left");
|
||||
let right = project.join("compare-right");
|
||||
std::fs::create_dir_all(&left).unwrap();
|
||||
std::fs::create_dir_all(&right).unwrap();
|
||||
std::fs::write(left.join("中文.bin"), [0, 255, 1]).unwrap();
|
||||
std::fs::write(right.join("中文.bin"), [0, 254, 1]).unwrap();
|
||||
assert_eq!(invoke(&peer, "fs_entry_kind", json!({"path": left})).await.unwrap(), "dir");
|
||||
assert_eq!(invoke(&peer, "fs_entry_kind", json!({"path": left.join("中文.bin")})).await.unwrap(), "file");
|
||||
let compare_args =
|
||||
|request| json!({"left": left, "right": right, "request": request, "onProgress": {"$channel": 520}});
|
||||
let rows = invoke(&peer, "fs_compare_directories", compare_args(520)).await.unwrap();
|
||||
assert_eq!(rows[0]["status"], "different");
|
||||
assert!(client.channels.lock().iter().any(|c| c.id == 520 && c.data["compared"] == 1));
|
||||
let copy_args =
|
||||
|overwrite| json!({"sourceRoot": left, "destinationRoot": right, "path": "中文.bin", "overwrite": overwrite});
|
||||
let error = invoke(&peer, "fs_copy_merge", copy_args(false)).await.unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::AlreadyExists);
|
||||
invoke(&peer, "fs_copy_merge", copy_args(true)).await.unwrap();
|
||||
let rows = invoke(&peer, "fs_compare_directories", compare_args(521)).await.unwrap();
|
||||
assert_eq!(rows[0]["status"], "equal");
|
||||
invoke(&peer, "cancel_request", json!({"id": 522})).await.unwrap();
|
||||
let error = invoke(&peer, "fs_compare_directories", compare_args(522)).await.unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
let error = invoke(
|
||||
&peer,
|
||||
"fs_copy_merge",
|
||||
json!({"sourceRoot": left, "destinationRoot": right, "path": "../escape", "overwrite": true}),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
|
||||
// JVM icons use the same read-only protocol as local windows.
|
||||
let java = project.join("src/Foo.java");
|
||||
let kotlin = project.join("src/Singleton.kt");
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
//! Own test process: the inherited shell deliberately differs from the login shell.
|
||||
#![cfg(unix)]
|
||||
|
||||
use ide_core::NullSink;
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[test]
|
||||
fn terminal_activation_uses_the_resolved_default_shell() {
|
||||
// SAFETY: no runtime or worker threads have been started.
|
||||
unsafe { std::env::set_var("SHELL", "/not-the-terminal/docker") };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||||
let bin = root.join(".venv/bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
std::fs::write(root.join(".venv/pyvenv.cfg"), "home = /usr/bin\n").unwrap();
|
||||
std::fs::write(bin.join("python"), "").unwrap();
|
||||
for script in ["activate", "activate.fish", "activate.csh", "activate.nu", "Activate.ps1"] {
|
||||
std::fs::write(bin.join(script), "echo activated > activation.marker\n").unwrap();
|
||||
}
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
|
||||
runtime.block_on(async {
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir: tmp.path().join("config"),
|
||||
data_dir: tmp.path().join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
}));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
for shell in [None, Some("".to_owned()), Some(" \t ".to_owned())] {
|
||||
let terminal = ops::term::spawn(
|
||||
&host,
|
||||
"main",
|
||||
ide_terminal::TerminalOptions {
|
||||
cwd: root.clone().into(),
|
||||
shell,
|
||||
args: vec![],
|
||||
env: Default::default(),
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
shell_integration: false,
|
||||
},
|
||||
Arc::new(|_| {}),
|
||||
)
|
||||
.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while !std::fs::read_to_string(root.join("activation.marker")).is_ok_and(|s| s.trim() == "activated") {
|
||||
assert!(Instant::now() < deadline, "default terminal shell must run the activation script");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
host.terminals.kill(terminal.id).unwrap();
|
||||
std::fs::remove_file(root.join("activation.marker")).unwrap();
|
||||
}
|
||||
host.shutdown().await;
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
use ide_core::NullSink;
|
||||
use ide_host::{Host, HostConfig, ops, trust::TrustStore};
|
||||
#[cfg(unix)]
|
||||
use ide_host::ops;
|
||||
use ide_host::{Host, HostConfig, trust::TrustStore};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
#[cfg(unix)]
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn host(base: &Path, environment: bool) -> Arc<Host> {
|
||||
@@ -17,6 +20,94 @@ fn host(base: &Path, environment: bool) -> Arc<Host> {
|
||||
}))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn application_commands_work_in_restricted_projects_and_without_a_project() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let host = host(&tmp.path().join("app"), false);
|
||||
assert!(host.project("welcome").is_err());
|
||||
assert!(ide_host::ops::project::roots(&host, "welcome").is_err());
|
||||
assert!(!host.open_project("main", &root).unwrap().is_trusted());
|
||||
for command in [
|
||||
"app_info",
|
||||
"app_build_info",
|
||||
"app_log_location",
|
||||
"app_check_update",
|
||||
"app_startup_update_check",
|
||||
"app_install_update",
|
||||
"caches_schedule_invalidation",
|
||||
"clear_caches",
|
||||
"clipboard_file_list",
|
||||
"clipboard_has_files",
|
||||
"clipboard_set_file_list",
|
||||
"jdk_download_vendors",
|
||||
"jdk_download_releases",
|
||||
"jdk_download_location",
|
||||
"jdk_download",
|
||||
"run_system_env",
|
||||
"run_gradle_jvm_args_script",
|
||||
"proxy_check_connection",
|
||||
"docker_settings",
|
||||
"docker_save_settings",
|
||||
"docker_set_registry_password",
|
||||
"docker_run_env",
|
||||
"db_console_path",
|
||||
"db_export_file",
|
||||
"vcs_write_patch",
|
||||
] {
|
||||
assert!(ide_host::trust::restricted_command_allowed(command), "{command}");
|
||||
for window in ["main", "welcome"] {
|
||||
assert!(host.authorize_command(window, command).is_ok(), "{window}: {command}");
|
||||
}
|
||||
}
|
||||
for command in [
|
||||
"run_start",
|
||||
"build_sync",
|
||||
"debug_start",
|
||||
"sdk_detect",
|
||||
"tools_list",
|
||||
"tools_install",
|
||||
"tools_uninstall",
|
||||
"plugin_install_dir",
|
||||
"plugin_reload",
|
||||
"vcs_git_version",
|
||||
"docker_compose_op",
|
||||
"db_execute",
|
||||
"unknown_command",
|
||||
] {
|
||||
assert!(!ide_host::trust::restricted_command_allowed(command), "{command}");
|
||||
for window in ["main", "welcome"] {
|
||||
assert!(host.authorize_command(window, command).is_err(), "{window}: {command}");
|
||||
}
|
||||
}
|
||||
// These requests validate the vendor before any network access, independently of project trust.
|
||||
for window in ["main", "welcome"] {
|
||||
let error = ide_host::ops::tools::jdk_download_releases(
|
||||
&host,
|
||||
window,
|
||||
"unknown-vendor".into(),
|
||||
ide_core::RequestId(901),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
let error = ide_host::ops::tools::jdk_download(
|
||||
&host,
|
||||
window,
|
||||
"unknown-vendor".into(),
|
||||
25,
|
||||
None,
|
||||
ide_core::RequestId(902),
|
||||
ide_host::ops::Channel::new(|_| {}),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
}
|
||||
host.shutdown().await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persists_user_decisions_locations_revocation_and_one_time_migration() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -209,8 +209,9 @@ impl SyntaxCache {
|
||||
|m| &mut m.folding,
|
||||
|| {
|
||||
self.with_tree(doc, lang, version, text, |g, tree, text| {
|
||||
Some(folding::folding(g.spec, g.kinds(), tree, text))
|
||||
Some(folding::folding(g.spec, g.kinds(), tree, text, self.syntax.comment_tokens(lang)))
|
||||
})
|
||||
.or_else(|| Some(self.syntax.custom_folding(lang, text)))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! comment runs, import runs and `region` / `endregion` marker comments.
|
||||
|
||||
use super::grammars::Spec;
|
||||
use crate::{FoldKind, FoldRange};
|
||||
use crate::{FoldKind, FoldRange, LanguageConfig};
|
||||
use tree_sitter::{Language, Node, Tree, TreeCursor};
|
||||
|
||||
const PAIRS: &[(&str, &str)] = &[("{", "}"), ("[", "]"), ("(", ")"), ("#{", "}"), ("${", "}"), ("@{", "}")];
|
||||
@@ -85,7 +85,25 @@ impl KindTable {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn folding(spec: &Spec, kinds: &KindTable, tree: &Tree, text: &str) -> Vec<FoldRange> {
|
||||
#[derive(Default)]
|
||||
pub(super) struct CommentTokens {
|
||||
line: Option<String>,
|
||||
block: Option<(String, String)>,
|
||||
}
|
||||
|
||||
impl From<&LanguageConfig> for CommentTokens {
|
||||
fn from(config: &LanguageConfig) -> Self {
|
||||
Self { line: config.line_comment.clone(), block: config.block_comment.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn folding(
|
||||
spec: &Spec,
|
||||
kinds: &KindTable,
|
||||
tree: &Tree,
|
||||
text: &str,
|
||||
tokens: &CommentTokens,
|
||||
) -> Vec<FoldRange> {
|
||||
let mut out: Vec<FoldRange> = Vec::new();
|
||||
let mut comments: Vec<Comment> = Vec::new();
|
||||
let mut cursor = tree.walk();
|
||||
@@ -96,7 +114,7 @@ pub(crate) fn folding(spec: &Spec, kinds: &KindTable, tree: &Tree, text: &str) -
|
||||
start_row: start,
|
||||
end_row: last_content_row(&node, text),
|
||||
own_line: own_line(text, node.start_byte(), node.start_position().column),
|
||||
marker: region_marker(text.get(node.start_byte()..node.end_byte()).unwrap_or_default()),
|
||||
marker: region_marker(text.get(node.start_byte()..node.end_byte()).unwrap_or_default(), tokens),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -185,7 +203,7 @@ fn visit(cursor: &mut TreeCursor, mut f: impl FnMut(Node) -> bool) {
|
||||
}
|
||||
|
||||
pub(crate) fn is_comment(kind: &str) -> bool {
|
||||
kind.contains("comment")
|
||||
kind.contains("comment") || kind == "Comment"
|
||||
}
|
||||
|
||||
/// Row of the closing token when `node` is delimited by a matching bracket pair.
|
||||
@@ -220,21 +238,64 @@ fn own_line(text: &str, byte: usize, column: usize) -> bool {
|
||||
}
|
||||
|
||||
/// `Some(true)` for a region start marker, `Some(false)` for an end marker.
|
||||
fn region_marker(comment: &str) -> Option<bool> {
|
||||
let body = comment
|
||||
.trim_start_matches(['/', '*', '#', '-', ';', '%', '!', '<', ' ', '\t'])
|
||||
.trim_start_matches("--")
|
||||
.trim_start();
|
||||
let lower = body.get(..body.len().min(32))?.to_ascii_lowercase();
|
||||
if lower.starts_with("endregion") || lower.starts_with("#endregion") || lower.starts_with("</editor-fold") {
|
||||
/// Strip whole configured delimiters, preserving the `<` in editor-fold tags.
|
||||
pub(super) fn region_marker(comment: &str, tokens: &CommentTokens) -> Option<bool> {
|
||||
let comment = comment.trim();
|
||||
let body = if let Some((open, close)) = &tokens.block
|
||||
&& let Some(body) = comment.strip_prefix(open.as_str())
|
||||
{
|
||||
let body = body.trim_end().strip_suffix(close.as_str())?;
|
||||
if open == "/*" { body.trim_start_matches('*') } else { body }
|
||||
} else if let Some(open) = &tokens.line
|
||||
&& let Some(body) = comment.strip_prefix(open.as_str())
|
||||
{
|
||||
match open.as_str() {
|
||||
"//" => body.trim_start_matches('/'),
|
||||
";" => body.trim_start_matches(';'),
|
||||
_ => body,
|
||||
}
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
let body = body.trim();
|
||||
if body.contains(['\n', '\r']) {
|
||||
return None;
|
||||
}
|
||||
let lower = body.to_ascii_lowercase();
|
||||
let region = lower.strip_prefix('#').unwrap_or(&lower);
|
||||
let boundary = |tail: &str| !tail.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_');
|
||||
if region.strip_prefix("endregion").is_some_and(boundary)
|
||||
|| lower
|
||||
.strip_prefix("</editor-fold")
|
||||
.and_then(|tail| tail.strip_suffix('>'))
|
||||
.is_some_and(|tail| tail.trim().is_empty())
|
||||
{
|
||||
Some(false)
|
||||
} else if lower.starts_with("region") || lower.starts_with("#region") || lower.starts_with("<editor-fold") {
|
||||
} else if region.strip_prefix("region").is_some_and(boundary)
|
||||
|| lower.strip_prefix("<editor-fold").is_some_and(|tail| boundary(tail) && tail.contains('>'))
|
||||
{
|
||||
Some(true)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Languages without a bundled grammar still support own-line custom markers.
|
||||
pub(super) fn custom_folding(text: &str, tokens: &CommentTokens) -> Vec<FoldRange> {
|
||||
let comments: Vec<_> = text
|
||||
.lines()
|
||||
.enumerate()
|
||||
.filter_map(|(row, line)| {
|
||||
let marker = region_marker(line, tokens)?;
|
||||
Some(Comment { start_row: row, end_row: row, own_line: true, marker: Some(marker) })
|
||||
})
|
||||
.collect();
|
||||
let mut out = Vec::new();
|
||||
comment_folds(&comments, &mut out);
|
||||
out.sort_by_key(|f| f.start_line);
|
||||
out
|
||||
}
|
||||
|
||||
fn comment_folds(comments: &[Comment], out: &mut Vec<FoldRange>) {
|
||||
let mut regions: Vec<usize> = Vec::new();
|
||||
let mut run: Option<(usize, usize)> = None;
|
||||
|
||||
@@ -32,6 +32,7 @@ pub struct Syntax {
|
||||
grammars: Vec<Grammar>,
|
||||
/// Language id (and grammar name) -> index into `grammars`.
|
||||
by_lang: HashMap<String, usize>,
|
||||
comments: HashMap<String, folding::CommentTokens>,
|
||||
}
|
||||
|
||||
pub(crate) struct Grammar {
|
||||
@@ -107,7 +108,14 @@ impl Syntax {
|
||||
}
|
||||
}
|
||||
}
|
||||
Self { grammars, by_lang }
|
||||
let mut comments = HashMap::new();
|
||||
for cfg in languages {
|
||||
comments.insert(cfg.id.as_str().to_owned(), folding::CommentTokens::from(cfg));
|
||||
if let Some(name) = &cfg.tree_sitter {
|
||||
comments.entry(name.clone()).or_insert_with(|| folding::CommentTokens::from(cfg));
|
||||
}
|
||||
}
|
||||
Self { grammars, by_lang, comments }
|
||||
}
|
||||
|
||||
/// Names of the bundled grammars (valid values for `tree-sitter = "..."`).
|
||||
@@ -161,8 +169,21 @@ impl Syntax {
|
||||
}
|
||||
|
||||
pub fn folding(&self, lang: &LanguageId, text: &str) -> Vec<FoldRange> {
|
||||
self.analyze(lang, text, |g, tree, text| Some(folding::folding(g.spec, g.kinds(), tree, text)))
|
||||
.unwrap_or_default()
|
||||
let tokens = self.comment_tokens(lang);
|
||||
self.analyze(lang, text, |g, tree, text| Some(folding::folding(g.spec, g.kinds(), tree, text, tokens)))
|
||||
.unwrap_or_else(|| self.custom_folding(lang, text))
|
||||
}
|
||||
|
||||
fn comment_tokens(&self, lang: &LanguageId) -> &folding::CommentTokens {
|
||||
static EMPTY: OnceLock<folding::CommentTokens> = OnceLock::new();
|
||||
self.comments.get(lang.as_str()).unwrap_or_else(|| EMPTY.get_or_init(Default::default))
|
||||
}
|
||||
|
||||
fn custom_folding(&self, lang: &LanguageId, text: &str) -> Vec<FoldRange> {
|
||||
if text.len() > MAX_PARSE_BYTES {
|
||||
return Vec::new();
|
||||
}
|
||||
folding::custom_folding(text, self.comment_tokens(lang))
|
||||
}
|
||||
|
||||
pub fn tags(&self, lang: &LanguageId, text: &str) -> Vec<SymbolTag> {
|
||||
|
||||
@@ -969,6 +969,85 @@ fn g() {}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_xml_custom_regions() {
|
||||
for (start, end) in [
|
||||
("<!--region要折叠的内容-->", "<!-- endregion -->"),
|
||||
("<!--region name-->", "<!--endregion-->"),
|
||||
("<!-- <editor-fold desc=\"Head\"> -->", "<!-- </editor-fold> -->"),
|
||||
] {
|
||||
let text = format!("<project>\n {start}\n <name>demo</name>\n {end}\n</project>\n");
|
||||
assert!(folds("xml", &text).contains(&(1, 3, FoldKind::Region)), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_custom_regions_use_configured_comment_tokens() {
|
||||
let fixture: serde_json::Value =
|
||||
serde_json::from_str(include_str!("../../../../fixtures/folding/regions.json")).unwrap();
|
||||
let registry = LanguageRegistry::load(None).unwrap();
|
||||
let cache = SyntaxCache::new(std::sync::Arc::new(Syntax::new()));
|
||||
for language in fixture["languages"].as_array().unwrap() {
|
||||
let id = language.as_str().unwrap();
|
||||
let cfg = registry.get(&lang(id)).unwrap();
|
||||
let mut tokens = Vec::new();
|
||||
if let Some(line) = &cfg.line_comment {
|
||||
tokens.push((line.as_str(), ""));
|
||||
}
|
||||
if let Some((open, close)) = &cfg.block_comment {
|
||||
tokens.push((open.as_str(), close.as_str()));
|
||||
}
|
||||
for (open, close) in tokens {
|
||||
for space in ["", " ", " "] {
|
||||
// Word delimiters require a separator in the language itself.
|
||||
if space.is_empty() && open.ends_with(|c: char| c.is_ascii_alphanumeric()) {
|
||||
continue;
|
||||
}
|
||||
let wrap = |body: &str| format!(" {open}{space}{body}{space}{close}");
|
||||
for marker in fixture["markers"].as_array().unwrap() {
|
||||
let start = wrap(marker["start"].as_str().unwrap());
|
||||
let end = wrap(marker["end"].as_str().unwrap());
|
||||
let tokens = folding::CommentTokens::from(&cfg);
|
||||
assert_eq!(folding::region_marker(&start, &tokens), Some(true), "{id}: {start}");
|
||||
assert_eq!(folding::region_marker(&end, &tokens), Some(false), "{id}: {end}");
|
||||
// Ruby block delimiters must occupy separate lines; Haskell
|
||||
// interprets `--` followed immediately by a symbol as an operator.
|
||||
if (id == "ruby" && open == "=begin") || (id == "haskell" && space.is_empty()) {
|
||||
continue;
|
||||
}
|
||||
let text = format!("{start}\n\n{end}\n");
|
||||
let expected = vec![(0, 2, FoldKind::Region)];
|
||||
assert_eq!(folds(id, &text), expected, "{id}: {text}");
|
||||
let doc = ide_core::DocId::next();
|
||||
cache.open(doc, &lang(id), 0);
|
||||
let actual = cache.folding(doc, &lang(id), 0, &text);
|
||||
assert_eq!(cache.folding(doc, &lang(id), 0, &text), actual);
|
||||
cache.close(doc);
|
||||
assert_eq!(
|
||||
actual.iter().map(|f| (f.start_line, f.end_line, f.kind)).collect::<Vec<_>>(),
|
||||
expected,
|
||||
"cached {id}: {text}"
|
||||
);
|
||||
let nested = format!("{end}\n\n{start}\n{start}\n\n{end}\n{end}\n{start}\n");
|
||||
assert_eq!(
|
||||
folds(id, &nested),
|
||||
vec![(2, 6, FoldKind::Region), (3, 5, FoldKind::Region)],
|
||||
"nested {id}: {nested}"
|
||||
);
|
||||
}
|
||||
for invalid in fixture["invalid"].as_array().unwrap() {
|
||||
let start = wrap(invalid.as_str().unwrap());
|
||||
assert_eq!(
|
||||
folding::region_marker(&start, &folding::CommentTokens::from(&cfg)),
|
||||
None,
|
||||
"invalid {id}: {start}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_python_bodies_start_at_header() {
|
||||
let src = "import os\nimport sys\n\nclass A:\n def f(self):\n return [\n 1,\n ]\n\n\ndef g():\n pass\n";
|
||||
|
||||
@@ -189,9 +189,12 @@ impl ClientHandler {
|
||||
// Convert before calling the hook: it re-enters document sync.
|
||||
let edit = convert::workspace_edit(&mgr.conv(self.encoding()), edit);
|
||||
let applied = match mgr.apply_edit_hook() {
|
||||
Some(hook) => hook(edit),
|
||||
Some(hook) => hook(edit.clone()),
|
||||
None => false,
|
||||
};
|
||||
if applied {
|
||||
let _ = mgr.applied_edits.send((self.server.id, edit));
|
||||
}
|
||||
let mut reply = json!({ "applied": applied });
|
||||
if !applied {
|
||||
reply["failureReason"] = json!("edit could not be applied");
|
||||
@@ -291,6 +294,21 @@ impl Handler for ClientHandler {
|
||||
/// `initializationOptions` with its `settings` merged over them.
|
||||
pub(crate) fn all_settings(cfg: &ide_language::LanguageServerConfig) -> Value {
|
||||
let mut out = cfg.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok()).unwrap_or(Value::Null);
|
||||
if cfg.name == "jdtls" {
|
||||
out = out.get("settings").cloned().unwrap_or_else(|| json!({}));
|
||||
if let Some(settings) = &cfg.settings {
|
||||
// Accept the initialization-options wrapper as well as LSP settings.
|
||||
if let Some(nested) = settings.get("settings") {
|
||||
merge(&mut out, nested.clone());
|
||||
}
|
||||
let mut direct = settings.clone();
|
||||
if let Some(direct) = direct.as_object_mut() {
|
||||
direct.remove("settings");
|
||||
}
|
||||
merge(&mut out, direct);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if let Some(settings) = &cfg.settings {
|
||||
merge(&mut out, settings.clone());
|
||||
}
|
||||
|
||||
@@ -35,6 +35,48 @@ const ACCESS_OPTIONS: [&str; 2] = [
|
||||
"org.eclipse.jdt.core.compiler.problem.discouragedReference",
|
||||
];
|
||||
|
||||
/// Keep the source model in protocol settings so jdtls's invisible-project
|
||||
/// initialization and configuration use the same roots as workspace builds.
|
||||
pub fn configure_source_paths(cfg: &mut ide_language::LanguageServerConfig, paths: Option<Vec<String>>) {
|
||||
if cfg.name != SERVER {
|
||||
return;
|
||||
}
|
||||
if let Some(paths) = paths {
|
||||
let mut settings = cfg.settings.take().unwrap_or_else(|| json!({}));
|
||||
settings["java"]["project"]["sourcePaths"] = json!(paths);
|
||||
cfg.settings = Some(settings);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn source_paths_removed(
|
||||
current: &ide_language::LanguageServerConfig,
|
||||
next: &ide_language::LanguageServerConfig,
|
||||
) -> bool {
|
||||
current.name == SERVER
|
||||
&& crate::handler::all_settings(current).pointer("/java/project/sourcePaths").is_some()
|
||||
&& crate::handler::all_settings(next).pointer("/java/project/sourcePaths").is_none()
|
||||
}
|
||||
|
||||
pub(crate) fn source_trigger(root: &Path, paths: &[Value]) -> Option<PathBuf> {
|
||||
for path in paths.iter().filter_map(Value::as_str) {
|
||||
// Runs can start jdtls without an editor. Invisible-project import still
|
||||
// needs a Java trigger file; discovery is bounded and runs off async workers.
|
||||
let found = ignore::WalkBuilder::new(root.join(path))
|
||||
.standard_filters(false)
|
||||
.max_depth(Some(32))
|
||||
.build()
|
||||
.take(4000)
|
||||
.filter_map(Result::ok)
|
||||
.find(|e| {
|
||||
e.file_type().is_some_and(|t| t.is_file()) && e.path().extension().is_some_and(|ext| ext == "java")
|
||||
});
|
||||
if let Some(entry) = found {
|
||||
return Some(entry.into_path());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn compiler_defaults(cfg: &ide_language::LanguageServerConfig) -> Value {
|
||||
// updateSettings persists project options. Only use it when jdtls redirects
|
||||
// generated metadata into its workspace, and never touch an existing .settings.
|
||||
@@ -147,6 +189,24 @@ pub struct JavaCompileError {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// Holds off JDT writers while an external compiler builds and snapshots launch outputs.
|
||||
/// Restores current settings even when preparation fails or is cancelled.
|
||||
pub struct JavaExternalBuild {
|
||||
server: Arc<Server>,
|
||||
run: Running,
|
||||
_lock: tokio::sync::OwnedMutexGuard<()>,
|
||||
}
|
||||
|
||||
impl Drop for JavaExternalBuild {
|
||||
fn drop(&mut self) {
|
||||
self.server.java_autobuild_suspended.store(false, std::sync::atomic::Ordering::SeqCst);
|
||||
let settings = crate::handler::all_settings(&self.server.effective_config());
|
||||
if let Err(e) = self.run.peer.notify("workspace/didChangeConfiguration", json!({ "settings": settings })) {
|
||||
tracing::debug!("jdtls: restoring autobuild: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Error diagnostics sorted by file and position, capped at `limit`, and their total.
|
||||
pub fn compile_errors(
|
||||
diagnostics: Vec<(PathBuf, lsp_types::Diagnostic)>,
|
||||
@@ -391,9 +451,28 @@ impl LspManager {
|
||||
.map_err(|e| crate::rpc_err(&server.name, "java/projectConfigurationsUpdate", e))
|
||||
}
|
||||
|
||||
/// Pause autobuild before resolving the launch classpath. That query takes the
|
||||
/// Java project's workspace scheduling rule, draining the interrupted autobuild.
|
||||
/// Keep this guard until Maven outputs have been copied out of JDT's reach.
|
||||
pub async fn java_external_build(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<JavaExternalBuild> {
|
||||
let (server, run) = self.jdtls(path, cancel).await?;
|
||||
let lock = cancellable_wait(cancel, server.java_build_lock.clone().lock_owned()).await?;
|
||||
server.java_autobuild_suspended.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
let guard = JavaExternalBuild { server, run, _lock: lock };
|
||||
let settings = crate::handler::all_settings(&guard.server.effective_config());
|
||||
guard
|
||||
.run
|
||||
.peer
|
||||
.notify("workspace/didChangeConfiguration", json!({ "settings": settings }))
|
||||
.map_err(|e| crate::rpc_err(SERVER, "workspace/didChangeConfiguration", e))?;
|
||||
Ok(guard)
|
||||
}
|
||||
|
||||
/// Incremental build of the jdtls workspace (`java/buildWorkspace`), so
|
||||
/// class files are up to date before a launch.
|
||||
pub async fn java_build(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<JavaBuildStatus> {
|
||||
let (server, _) = self.jdtls(path, cancel).await?;
|
||||
let _lock = cancellable_wait(cancel, server.java_build_lock.lock()).await?;
|
||||
let mut v = self.jdtls_request(path, "java/buildWorkspace", json!(false), BUILD_TIMEOUT, cancel).await?;
|
||||
// The first build can finish the Maven import before ServiceReady is handled.
|
||||
let (server, run) = self.jdtls(path, cancel).await?;
|
||||
@@ -490,6 +569,59 @@ impl LspManager {
|
||||
collect()
|
||||
}
|
||||
|
||||
/// Resolve a disk/archive class to project source or the server's binary document.
|
||||
/// Archive URIs must come from JDT's Java model: fabricated handles cannot map debug lines.
|
||||
pub async fn java_class_file(&self, path: &Path, archive: Option<(PathBuf, String)>) -> IdeResult<String> {
|
||||
let cancel = CancellationToken::new();
|
||||
self.jdtls(&self.project_root, &cancel).await?;
|
||||
if let Some((jar, entry)) = archive {
|
||||
let entry = entry
|
||||
.strip_prefix("META-INF/versions/")
|
||||
.and_then(|s| s.split_once('/').map(|(_, s)| s))
|
||||
.unwrap_or(&entry);
|
||||
let class = entry.strip_suffix(".class").ok_or_else(|| IdeError::not_found("expected a class file"))?;
|
||||
let outer = class.split('$').next().unwrap_or(class);
|
||||
let (package, name) = outer.rsplit_once('/').unwrap_or(("", outer));
|
||||
let query = outer.replace('/', ".");
|
||||
let symbols = self.workspace_symbols(&query, cancel).await?;
|
||||
let package = package.replace('/', ".");
|
||||
let name = name.to_owned();
|
||||
let outer = outer.to_owned();
|
||||
return tokio::task::spawn_blocking(move || {
|
||||
symbols
|
||||
.into_iter()
|
||||
.filter_map(|s| s.location.uri)
|
||||
.find(|uri| crate::virtual_doc::matches_class(uri, &jar, &package, &name))
|
||||
.ok_or_else(|| {
|
||||
IdeError::not_found(format!("jdtls could not resolve {} in {}", outer, jar.display()))
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
}
|
||||
let uri = crate::uri::path_to_uri_string(path);
|
||||
// classFileContents accepts file URIs, but java-debug's line mapping only accepts JDT handles.
|
||||
let doc = self.virtual_document(&uri).await?;
|
||||
let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("").split('$').next().unwrap_or("");
|
||||
let package = doc
|
||||
.text
|
||||
.lines()
|
||||
.find_map(|l| l.trim().strip_prefix("package ").and_then(|p| p.strip_suffix(';')))
|
||||
.unwrap_or("");
|
||||
let relative = PathBuf::from(package.replace('.', "/")).join(format!("{name}.java"));
|
||||
let key = "org.eclipse.jdt.ls.core.sourcePaths";
|
||||
let settings = self
|
||||
.jdtls_project_command(path, "java.project.getSettings", vec![json!(uri), json!([key])], &cancel)
|
||||
.await?;
|
||||
let roots: Vec<PathBuf> =
|
||||
settings[key].as_array().into_iter().flatten().filter_map(Value::as_str).map(PathBuf::from).collect();
|
||||
let source =
|
||||
tokio::task::spawn_blocking(move || roots.into_iter().map(|r| r.join(&relative)).find(|p| p.is_file()))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
Ok(source.map(|s| s.to_string_lossy().into_owned()).unwrap_or(uri))
|
||||
}
|
||||
|
||||
/// Starts (or reuses) java-debug's DAP server inside jdtls and returns its port.
|
||||
pub async fn java_debug_server(&self, path: &Path) -> IdeResult<u16> {
|
||||
let v = self.jdtls_command(path, "vscode.java.startDebugSession", Vec::new()).await.map_err(|e| {
|
||||
@@ -500,7 +632,7 @@ impl LspManager {
|
||||
}
|
||||
})?;
|
||||
// Hot code replace after each (auto-)build; errors only cost the feature.
|
||||
let settings = json!({ "hotCodeReplace": "auto", "showStaticVariables": false, "showQualifiedNames": false,
|
||||
let settings = json!({ "debugSupportOnDecompiledSource": "on", "hotCodeReplace": "auto", "showStaticVariables": false, "showQualifiedNames": false,
|
||||
"showLogicalStructure": true, "showToString": true, "maxStringLength": 0,
|
||||
// java-debug NPEs on a missing level (java.util.logging names).
|
||||
"logLevel": "WARNING" });
|
||||
@@ -518,6 +650,65 @@ impl LspManager {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn java_config() -> ide_language::LanguageServerConfig {
|
||||
let language: ide_language::LanguageConfig =
|
||||
toml::from_str(include_str!("../../../languages/java.toml")).unwrap();
|
||||
language.language_servers.into_iter().next().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_settings_preserve_java_defaults_and_library_resolution() {
|
||||
let mut cfg = java_config();
|
||||
configure_source_paths(&mut cfg, Some(vec!["src/main/java".into(), "tests".into()]));
|
||||
let settings = crate::handler::all_settings(&cfg);
|
||||
assert_eq!(settings["java"]["project"]["sourcePaths"], json!(["src/main/java", "tests"]));
|
||||
assert_eq!(settings["java"]["project"]["referencedLibraries"], json!(["lib/**/*.jar"]));
|
||||
assert_eq!(settings["java"]["autobuild"]["enabled"], true);
|
||||
assert_eq!(settings["java"]["contentProvider"]["preferred"], "fernflowerContentProvider");
|
||||
assert!(settings.get("bundles").is_none());
|
||||
assert!(settings.get("settings").is_none(), "didChangeConfiguration takes java settings directly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmarked_and_managed_source_models_are_not_overridden() {
|
||||
let mut cfg = java_config();
|
||||
let initial = cfg.clone();
|
||||
configure_source_paths(&mut cfg, None);
|
||||
assert_eq!(cfg, initial);
|
||||
assert!(crate::handler::all_settings(&cfg).pointer("/java/project/sourcePaths").is_none());
|
||||
configure_source_paths(&mut cfg, Some(vec!["custom".into()]));
|
||||
assert!(source_paths_removed(&cfg, &initial));
|
||||
assert!(!source_paths_removed(&initial, &cfg));
|
||||
let mut other = initial;
|
||||
other.name = "other".into();
|
||||
let initial = other.clone();
|
||||
configure_source_paths(&mut other, Some(vec!["custom".into()]));
|
||||
assert_eq!(other, initial);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_java_protocol_settings_override_defaults_in_either_shape() {
|
||||
for wrapped in [false, true] {
|
||||
let mut cfg = java_config();
|
||||
let settings = json!({"java": {"project": {"referencedLibraries": ["vendor/*.jar"]}}});
|
||||
cfg.settings = Some(if wrapped { json!({"settings": settings}) } else { settings });
|
||||
configure_source_paths(&mut cfg, Some(vec!["custom".into()]));
|
||||
let settings = crate::handler::all_settings(&cfg);
|
||||
assert_eq!(settings["java"]["project"]["referencedLibraries"], json!(["vendor/*.jar"]));
|
||||
assert_eq!(settings["java"]["project"]["sourcePaths"], json!(["custom"]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_without_an_editor_discovers_a_trigger_inside_its_source_roots() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("src/demo/engine")).unwrap();
|
||||
let file = dir.path().join("src/demo/engine/Main.java");
|
||||
std::fs::write(&file, "package demo.engine; public class Main {}").unwrap();
|
||||
assert_eq!(source_trigger(dir.path(), &[json!("generated"), json!("src")]), Some(file));
|
||||
assert_eq!(source_trigger(dir.path(), &[json!("tests")]), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_ends_a_pending_wait() {
|
||||
let cancel = CancellationToken::new();
|
||||
|
||||
@@ -129,6 +129,7 @@ impl Target {
|
||||
}
|
||||
|
||||
struct DocSnap {
|
||||
version: i32,
|
||||
path: PathBuf,
|
||||
uri: lsp::Uri,
|
||||
language: LanguageId,
|
||||
@@ -168,6 +169,7 @@ pub struct LspManager {
|
||||
servers: Mutex<Vec<Arc<Server>>>,
|
||||
docs: Mutex<HashMap<DocId, DocState>>,
|
||||
apply_edit_hook: RwLock<Option<ApplyEditHook>>,
|
||||
applied_edits: tokio::sync::broadcast::Sender<(ide_core::ServerId, WorkspaceEdit)>,
|
||||
config_hook: RwLock<Option<ConfigHook>>,
|
||||
prepare_hook: RwLock<Option<Arc<PrepareFn>>>,
|
||||
servers_hook: RwLock<Option<Arc<ServersFn>>>,
|
||||
@@ -175,6 +177,7 @@ pub struct LspManager {
|
||||
excludes_hook: RwLock<Option<Arc<external_project::ExcludesFn>>>,
|
||||
shutting_down: AtomicBool,
|
||||
execution_allowed: AtomicBool,
|
||||
java_usages_warned: AtomicBool,
|
||||
/// `window/showMessage` texts already surfaced; servers repeat them on every restart/reconfigure.
|
||||
shown_messages: Mutex<HashSet<(String, String)>>,
|
||||
/// Virtual (non-`file:`) URIs a server returned, by the server that owns them.
|
||||
@@ -300,6 +303,7 @@ impl LspManager {
|
||||
servers: Mutex::new(Vec::new()),
|
||||
docs: Mutex::new(HashMap::new()),
|
||||
apply_edit_hook: RwLock::new(None),
|
||||
applied_edits: tokio::sync::broadcast::channel(64).0,
|
||||
config_hook: RwLock::new(None),
|
||||
prepare_hook: RwLock::new(None),
|
||||
servers_hook: RwLock::new(None),
|
||||
@@ -307,6 +311,7 @@ impl LspManager {
|
||||
excludes_hook: RwLock::new(None),
|
||||
shutting_down: AtomicBool::new(false),
|
||||
execution_allowed: AtomicBool::new(true),
|
||||
java_usages_warned: AtomicBool::new(false),
|
||||
shown_messages: Mutex::new(HashSet::new()),
|
||||
virtual_origins: Mutex::new(HashMap::new()),
|
||||
virtual_docs: Mutex::new(HashMap::new()),
|
||||
@@ -513,7 +518,19 @@ impl LspManager {
|
||||
}
|
||||
};
|
||||
|
||||
let init = self.initialize_params(&server);
|
||||
let mut init = self.initialize_params(&server);
|
||||
if server.name == "jdtls"
|
||||
&& init["initializationOptions"].get("triggerFiles").is_none()
|
||||
&& let Some(paths) = init
|
||||
.pointer("/initializationOptions/settings/java/project/sourcePaths")
|
||||
.and_then(Value::as_array)
|
||||
.cloned()
|
||||
{
|
||||
let root = server.root.clone();
|
||||
if let Ok(Some(path)) = tokio::task::spawn_blocking(move || jdtls::source_trigger(&root, &paths)).await {
|
||||
init["initializationOptions"]["triggerFiles"] = json!([uri::path_to_uri_string(&path)]);
|
||||
}
|
||||
}
|
||||
let result = tokio::time::timeout(INITIALIZE_TIMEOUT, peer.request::<_, Value>("initialize", init, None))
|
||||
.await
|
||||
.unwrap_or(Err(RpcError::Timeout));
|
||||
@@ -656,12 +673,26 @@ impl LspManager {
|
||||
fn initialize_params(&self, server: &Server) -> Value {
|
||||
let root_uri = uri::path_to_uri(&server.root);
|
||||
let name = server.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "root".into());
|
||||
let init_options = server
|
||||
.effective_config()
|
||||
.initialization_options
|
||||
.as_ref()
|
||||
.and_then(|v| serde_json::to_value(v).ok())
|
||||
.unwrap_or(Value::Null);
|
||||
let cfg = server.effective_config();
|
||||
let mut init_options =
|
||||
cfg.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok()).unwrap_or(Value::Null);
|
||||
if server.name == "jdtls" {
|
||||
if !init_options.is_object() {
|
||||
init_options = json!({});
|
||||
}
|
||||
init_options["settings"] = handler::all_settings(&cfg);
|
||||
let triggers: Vec<_> = self
|
||||
.docs
|
||||
.lock()
|
||||
.values()
|
||||
.filter(|d| d.language.as_str() == "java" && d.path.starts_with(&server.root))
|
||||
.map(|d| uri::path_to_uri_string(&d.path))
|
||||
.collect();
|
||||
if !triggers.is_empty() && init_options.get("triggerFiles").is_none() {
|
||||
// Re-import cached invisible projects with the current source model.
|
||||
init_options["triggerFiles"] = json!(triggers);
|
||||
}
|
||||
}
|
||||
let mut params = json!({
|
||||
"processId": std::process::id(),
|
||||
"clientInfo": { "name": "OpenIDEA", "version": env!("CARGO_PKG_VERSION") },
|
||||
@@ -672,6 +703,9 @@ impl LspManager {
|
||||
"capabilities": caps::client_capabilities(),
|
||||
"trace": "off",
|
||||
});
|
||||
if server.name == "gopls" {
|
||||
params["capabilities"]["experimental"]["interactiveResolve"] = json!({ "inputTypes": ["string"] });
|
||||
}
|
||||
if !init_options.is_null() {
|
||||
params["initializationOptions"] = init_options;
|
||||
}
|
||||
@@ -888,6 +922,7 @@ impl LspManager {
|
||||
let docs = self.docs.lock();
|
||||
let d = docs.get(&doc).ok_or_else(|| IdeError::not_found(format!("{doc} is not open")))?;
|
||||
Ok(DocSnap {
|
||||
version: d.version,
|
||||
path: d.path.clone(),
|
||||
uri: d.uri.clone(),
|
||||
language: d.language.clone(),
|
||||
@@ -1156,6 +1191,106 @@ impl LspManager {
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<References> {
|
||||
let (snap, targets) = self.doc_targets(doc, "find references", |c| c.has("referencesProvider")).await?;
|
||||
// The extension preserves method identity before JDT collapses references to locations.
|
||||
// Old/custom servers retain the standard protocol, including cancellation and scope widening.
|
||||
if targets.len() == 1
|
||||
&& targets[0].server.name == "jdtls"
|
||||
&& targets[0].caps().commands().iter().any(|c| c == "openidea.java.usages")
|
||||
{
|
||||
let classified = async {
|
||||
let t = &targets[0];
|
||||
let extension_error = Mutex::new(None);
|
||||
let query = || async {
|
||||
if cancel.is_cancelled() || !self.docs.lock().get(&doc).is_some_and(|d| d.version == snap.version) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let params = snap.pos_params(t, pos);
|
||||
#[derive(serde::Deserialize)]
|
||||
struct JavaReference {
|
||||
#[serde(default)]
|
||||
access: Option<ReferenceAccess>,
|
||||
location: lsp::Location,
|
||||
kind: ReferenceKind,
|
||||
}
|
||||
let result: IdeResult<Vec<JavaReference>> = self
|
||||
.call(
|
||||
t,
|
||||
"workspace/executeCommand",
|
||||
json!({
|
||||
"command": "openidea.java.usages",
|
||||
"arguments": [params["textDocument"]["uri"], params["position"]["line"],
|
||||
params["position"]["character"], include_declaration]
|
||||
}),
|
||||
Some(&cancel),
|
||||
LONG_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
if let Err(e) = &result {
|
||||
*extension_error.lock() = Some(e.clone());
|
||||
}
|
||||
let rows = result?;
|
||||
if cancel.is_cancelled() || !self.docs.lock().get(&doc).is_some_and(|d| d.version == snap.version) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let conv = self.conv(t.enc());
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
conv.location(&r.location).map(|location| ClassifiedReference {
|
||||
location,
|
||||
kind: r.kind,
|
||||
access: r.access,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>())
|
||||
};
|
||||
let files = |v: &Vec<ClassifiedReference>| {
|
||||
v.iter().filter(|r| r.location.uri.is_none()).map(|r| r.location.path.to_path_buf()).collect()
|
||||
};
|
||||
let widened = if project_wide {
|
||||
self.widened(&snap, t, pos, &cancel, query, files).await?
|
||||
} else {
|
||||
let first = query().await?;
|
||||
let empty = first.is_empty();
|
||||
scope::Widened::only(first, empty, &t.server)
|
||||
};
|
||||
// A changed source also invalidates an earlier answer retained by scope widening.
|
||||
if cancel.is_cancelled() || !self.docs.lock().get(&doc).is_some_and(|d| d.version == snap.version) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
// Scope widening can retain the first answer after a failed second query.
|
||||
if let Some(e) = extension_error.into_inner() {
|
||||
return Err(e);
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
// Prefer the second query's metadata for repeated locations.
|
||||
let classified: Vec<_> = widened
|
||||
.second
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.chain(widened.first)
|
||||
.filter(|r| seen.insert(r.location.clone()))
|
||||
.collect();
|
||||
let locations: Vec<Location> = classified.iter().map(|r| r.location.clone()).collect();
|
||||
self.note_virtual(&t.server, locations.iter().map(|l| l.uri.as_deref()));
|
||||
Ok(References { locations, classified, incomplete: widened.incomplete })
|
||||
}
|
||||
.await;
|
||||
match classified {
|
||||
Ok(references) => return Ok(references),
|
||||
Err(e) => {
|
||||
if e.kind == ErrorKind::Cancelled
|
||||
|| cancel.is_cancelled()
|
||||
|| !self.docs.lock().get(&doc).is_some_and(|d| d.version == snap.version)
|
||||
{
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if !self.java_usages_warned.swap(true, Ordering::Relaxed) {
|
||||
tracing::warn!("Java usages extension failed; using standard references: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let requests = targets.iter().map(|t| {
|
||||
let (snap, cancel) = (&snap, &cancel);
|
||||
async move {
|
||||
@@ -1420,6 +1555,92 @@ impl LspManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn command_target(&self, doc: DocId, server: ide_core::ServerId, name: &str) -> IdeResult<Target> {
|
||||
let snap = self.snapshot(doc)?;
|
||||
self.ready_targets(&snap.servers, |c| c.commands().iter().any(|c| c == name))
|
||||
.await
|
||||
.into_iter()
|
||||
.find(|t| t.server.id == server)
|
||||
.ok_or_else(|| IdeError::unavailable(format!("no language server provides command `{name}`")))
|
||||
}
|
||||
|
||||
/// Resolve only after explicit invocation; previews must never ask for input.
|
||||
pub async fn resolve_command(
|
||||
&self,
|
||||
doc: DocId,
|
||||
server: ide_core::ServerId,
|
||||
command: Command,
|
||||
answers: Vec<FormAnswer>,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<Option<CommandForm>> {
|
||||
let t = self.command_target(doc, server, &command.command).await?;
|
||||
let interactive = t.server.name == "gopls"
|
||||
&& t.caps()
|
||||
.raw
|
||||
.pointer("/experimental/interactiveResolveProvider/kinds")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|k| k.iter().any(|v| v == "command"));
|
||||
if !interactive {
|
||||
return Ok(None);
|
||||
}
|
||||
let params = json!({ "command": command.command, "arguments": command.arguments, "formAnswers": answers });
|
||||
let response: Value = self.call(&t, "command/resolve", params, Some(&cancel), LONG_TIMEOUT).await?;
|
||||
let parse_error = |e: serde_json::Error| IdeError::internal(format!("invalid command form: {e}"));
|
||||
let fields = response.get("formFields").filter(|v| !v.is_null()).cloned().unwrap_or(json!([]));
|
||||
for field in fields.as_array().into_iter().flatten() {
|
||||
if field.pointer("/type/kind").and_then(Value::as_str) != Some("string") {
|
||||
return Err(IdeError::unavailable("unsupported command input type"));
|
||||
}
|
||||
}
|
||||
Ok(Some(CommandForm {
|
||||
command: Command {
|
||||
title: command.title,
|
||||
command: response
|
||||
.get("command")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| IdeError::internal("command form omitted command"))?
|
||||
.to_owned(),
|
||||
arguments: serde_json::from_value(response.get("arguments").cloned().unwrap_or(json!([])))
|
||||
.map_err(parse_error)?,
|
||||
},
|
||||
form_fields: serde_json::from_value(fields).map_err(parse_error)?,
|
||||
form_answers: serde_json::from_value(
|
||||
response.get("formAnswers").filter(|v| !v.is_null()).cloned().unwrap_or(json!([])),
|
||||
)
|
||||
.map_err(parse_error)?,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Execute on the originating server and return files from successfully applied edits.
|
||||
pub async fn execute_action_command(
|
||||
&self,
|
||||
doc: DocId,
|
||||
server: ide_core::ServerId,
|
||||
command: Command,
|
||||
answers: Vec<FormAnswer>,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<Vec<PathBuf>> {
|
||||
let t = self.command_target(doc, server, &command.command).await?;
|
||||
let open_created = t.server.name == "gopls" && command.command == "gopls.add_test";
|
||||
let mut edits = self.applied_edits.subscribe();
|
||||
let mut params = json!({ "command": command.command, "arguments": command.arguments });
|
||||
if !answers.is_empty() {
|
||||
params["formAnswers"] = json!(answers);
|
||||
}
|
||||
let _: Value = self.call(&t, "workspace/executeCommand", params, Some(&cancel), LONG_TIMEOUT).await?;
|
||||
let mut created = Vec::new();
|
||||
while let Ok((origin, edit)) = edits.try_recv() {
|
||||
if open_created && origin == server {
|
||||
for file in edit.files {
|
||||
if let ide_core::FileEdit::Create { path, .. } = file {
|
||||
created.push(path.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(created)
|
||||
}
|
||||
|
||||
pub async fn prepare_rename(&self, doc: DocId, pos: Pos) -> IdeResult<Option<Range>> {
|
||||
let (snap, targets) = self.doc_targets(doc, "rename", |c| c.has("renameProvider")).await?;
|
||||
let mut out = Outcome::new();
|
||||
@@ -1945,6 +2166,7 @@ impl LspManager {
|
||||
return Ok(d.clone());
|
||||
}
|
||||
let scheme = virtual_doc::scheme(uri).to_owned();
|
||||
let class_file = scheme == "jdt" || (scheme == "file" && uri.ends_with(".class"));
|
||||
let origin = self.origin_server(uri);
|
||||
let mut servers: Vec<Arc<Server>> = origin.iter().cloned().collect();
|
||||
servers.extend(self.servers.lock().iter().filter(|s| Some(s.id) != origin.as_ref().map(|o| o.id)).cloned());
|
||||
@@ -1953,7 +2175,7 @@ impl LspManager {
|
||||
for t in &targets {
|
||||
let languages = t.server.languages();
|
||||
let serves_scheme = t.caps().content_schemes().contains(&scheme);
|
||||
let result: IdeResult<Option<String>> = if serves_scheme {
|
||||
let result: IdeResult<Option<String>> = if serves_scheme && !class_file {
|
||||
self.call::<_, Option<Value>>(
|
||||
t,
|
||||
"workspace/textDocumentContent",
|
||||
@@ -1963,7 +2185,7 @@ impl LspManager {
|
||||
)
|
||||
.await
|
||||
.map(|v| v.and_then(|v| v.get("text").and_then(Value::as_str).map(str::to_owned)))
|
||||
} else if scheme == "jdt" && languages.iter().any(|l| l.as_str() == "java") {
|
||||
} else if class_file && languages.iter().any(|l| l.as_str() == "java") {
|
||||
self.call::<_, Option<String>>(t, "java/classFileContents", json!({ "uri": uri }), None, LONG_TIMEOUT)
|
||||
.await
|
||||
} else {
|
||||
@@ -2081,6 +2303,7 @@ impl LspManager {
|
||||
let without_settings = |c: &LanguageServerConfig| LanguageServerConfig { settings: None, ..c.clone() };
|
||||
if let Some(run) = s.running()
|
||||
&& without_settings(&next) == without_settings(¤t)
|
||||
&& !jdtls::source_paths_removed(¤t, &next)
|
||||
{
|
||||
s.set_effective_config(next);
|
||||
let params = json!({ "settings": handler::all_settings(&s.effective_config()) });
|
||||
|
||||
@@ -99,6 +99,8 @@ pub struct Server {
|
||||
/// Woken when the last `$/progress` task ends.
|
||||
idle_notify: Notify,
|
||||
transient: Mutex<HashMap<PathBuf, Transient>>,
|
||||
pub java_build_lock: Arc<tokio::sync::Mutex<()>>,
|
||||
pub java_autobuild_suspended: std::sync::atomic::AtomicBool,
|
||||
pub external_project: tokio::sync::Mutex<crate::external_project::State>,
|
||||
pub external_diagnostics: std::sync::atomic::AtomicBool,
|
||||
pub external_refresh_queued: std::sync::atomic::AtomicBool,
|
||||
@@ -126,6 +128,8 @@ impl Server {
|
||||
published_notify: Notify::new(),
|
||||
idle_notify: Notify::new(),
|
||||
transient: Mutex::new(HashMap::new()),
|
||||
java_build_lock: Arc::new(tokio::sync::Mutex::new(())),
|
||||
java_autobuild_suspended: std::sync::atomic::AtomicBool::new(false),
|
||||
external_project: tokio::sync::Mutex::new(Default::default()),
|
||||
external_diagnostics: std::sync::atomic::AtomicBool::new(false),
|
||||
external_refresh_queued: std::sync::atomic::AtomicBool::new(false),
|
||||
@@ -134,7 +138,13 @@ impl Server {
|
||||
|
||||
/// Configuration of the current (or last) instance; the base config before the first launch.
|
||||
pub fn effective_config(&self) -> LanguageServerConfig {
|
||||
self.effective.lock().clone().unwrap_or_else(|| self.config.clone())
|
||||
let mut config = self.effective.lock().clone().unwrap_or_else(|| self.config.clone());
|
||||
if self.java_autobuild_suspended.load(std::sync::atomic::Ordering::SeqCst) {
|
||||
let mut settings = crate::handler::all_settings(&config);
|
||||
settings["java"]["autobuild"]["enabled"] = serde_json::json!(false);
|
||||
config.settings = Some(settings);
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
pub fn set_effective_config(&self, config: LanguageServerConfig) {
|
||||
@@ -553,6 +563,19 @@ mod tests {
|
||||
assert_eq!(s.record_crash(), Some(Duration::from_millis(500)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_build_suspends_only_the_effective_autobuild_setting() {
|
||||
let mut config: LanguageServerConfig = toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap();
|
||||
config.settings = Some(serde_json::json!({"java": {"autobuild": {"enabled": true}, "other": "kept"}}));
|
||||
let server = Server::new(config.clone(), PathBuf::from("/p"), LanguageId::new("java"));
|
||||
server.java_autobuild_suspended.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
let settings = crate::handler::all_settings(&server.effective_config());
|
||||
assert_eq!(settings["java"]["autobuild"]["enabled"], false);
|
||||
assert_eq!(settings["java"]["other"], "kept");
|
||||
server.java_autobuild_suspended.store(false, std::sync::atomic::Ordering::SeqCst);
|
||||
assert_eq!(server.effective_config(), config);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_failed_start_reports_its_status_before_waiters_wake() {
|
||||
// The race behind "jdtls is not ready (Starting)": a request woken by the
|
||||
|
||||
@@ -145,6 +145,34 @@ pub struct Command {
|
||||
pub arguments: Vec<serde_json::Value>,
|
||||
}
|
||||
|
||||
/// The string form supported by gopls's experimental interactive command protocol.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FormAnswer {
|
||||
pub id: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FormField {
|
||||
pub id: String,
|
||||
pub description: String,
|
||||
pub required: bool,
|
||||
#[serde(default)]
|
||||
pub default: Option<String>,
|
||||
#[serde(default)]
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CommandForm {
|
||||
pub command: Command,
|
||||
pub form_fields: Vec<FormField>,
|
||||
pub form_answers: Vec<FormAnswer>,
|
||||
}
|
||||
|
||||
/// One `textDocument/inlineCompletion` suggestion (ghost text at the caret).
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -307,7 +335,7 @@ pub struct VirtualDocument {
|
||||
pub title: String,
|
||||
/// Origin shown in the tooltip / banner, e.g. the jar path.
|
||||
pub description: Option<String>,
|
||||
/// Generated by a decompiler / disassembler rather than real sources.
|
||||
/// Generated Java from a decompiler, rather than real source or a disassembler stub.
|
||||
pub decompiled: bool,
|
||||
}
|
||||
|
||||
@@ -338,6 +366,10 @@ pub enum ReferencesIncomplete {
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct References {
|
||||
/// Semantic classifications supplied by a language extension. Missing entries are unknown.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub classified: Vec<ClassifiedReference>,
|
||||
pub locations: Vec<Location>,
|
||||
pub incomplete: Option<ReferencesIncomplete>,
|
||||
}
|
||||
@@ -355,3 +387,31 @@ pub struct CallHierarchy {
|
||||
pub items: Vec<HierarchyItem>,
|
||||
pub incomplete: Option<ReferencesIncomplete>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ReferenceKind {
|
||||
Getter,
|
||||
Setter,
|
||||
Field,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ReferenceAccess {
|
||||
Read,
|
||||
Write,
|
||||
ReadWrite,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
pub struct ClassifiedReference {
|
||||
/// Optional for older Java extensions; missing means unclassified.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub access: Option<ReferenceAccess>,
|
||||
pub location: Location,
|
||||
pub kind: ReferenceKind,
|
||||
}
|
||||
@@ -1,21 +1,29 @@
|
||||
//! Virtual documents: read-only contents a language server provides for a
|
||||
//! non-`file:` URI (library classes from `jdt://`, `workspace/textDocumentContent`).
|
||||
//! URI (library classes from `jdt://`, disk classes from `file://`, or
|
||||
//! `workspace/textDocumentContent`).
|
||||
|
||||
use percent_encoding::percent_decode_str;
|
||||
|
||||
/// Markers decompilers / disassemblers put at the top of generated code.
|
||||
const GENERATED_MARKERS: [&str; 5] = [
|
||||
"generated by the fernflower decompiler",
|
||||
"failed to get sources",
|
||||
"decompiled with cfr",
|
||||
"decompiled with procyon",
|
||||
"generated by the disassembler",
|
||||
];
|
||||
|
||||
/// Whether `text` is decompiled / disassembled code rather than real source.
|
||||
/// Recognize decompiler headers, without treating disassembler stubs as Java source.
|
||||
pub fn is_decompiled(text: &str) -> bool {
|
||||
let head: String = text.chars().take(600).collect::<String>().to_ascii_lowercase();
|
||||
GENERATED_MARKERS.iter().any(|m| head.contains(m))
|
||||
let head: String = text.chars().take(600).collect();
|
||||
head.lines()
|
||||
.take(12)
|
||||
.take_while(|line| {
|
||||
let line = line.trim();
|
||||
line.is_empty() || line.starts_with("//") || line.starts_with("/*") || line.starts_with('*')
|
||||
})
|
||||
.any(|line| {
|
||||
let line = line.trim().trim_start_matches('/').trim_start_matches('*').trim().to_ascii_lowercase();
|
||||
[
|
||||
"source code is unavailable, and was generated by the fernflower decompiler.",
|
||||
"source code is decompiled from a .class file using fernflower decompiler",
|
||||
"decompiled with cfr",
|
||||
"decompiled with procyon",
|
||||
]
|
||||
.iter()
|
||||
.any(|marker| line.starts_with(marker))
|
||||
})
|
||||
}
|
||||
|
||||
/// `scheme` of a URI (`jdt` for `jdt://…`).
|
||||
@@ -34,7 +42,16 @@ fn segments(uri: &str) -> Vec<String> {
|
||||
/// Editor tab title: the last path segment; a class file whose real source
|
||||
/// was found is shown as `.java` (IDEA: `String.java` vs `String.class`).
|
||||
pub fn title(uri: &str, decompiled: bool) -> String {
|
||||
let name = segments(uri).pop().unwrap_or_else(|| uri.to_owned());
|
||||
let mut name = segments(uri).pop().unwrap_or_else(|| uri.to_owned());
|
||||
// Recent jdtls versions use a .java path even for decompiled class handles.
|
||||
if decompiled
|
||||
&& scheme(uri) == "jdt"
|
||||
&& name.ends_with(".java")
|
||||
&& uri.split_once('?').is_some_and(|(_, q)| percent_decode_str(q).decode_utf8_lossy().contains(".class"))
|
||||
{
|
||||
name.truncate(name.len() - 5);
|
||||
name.push_str(".class");
|
||||
}
|
||||
match name.strip_suffix(".class") {
|
||||
Some(stem) if !decompiled && scheme(uri) == "jdt" => format!("{stem}.java"),
|
||||
_ => name,
|
||||
@@ -68,6 +85,19 @@ pub fn description(uri: &str) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check both the package and actual archive, so duplicate type names never pick another jar.
|
||||
pub(crate) fn matches_class(uri: &str, jar: &std::path::Path, package: &str, name: &str) -> bool {
|
||||
let segs = segments(uri);
|
||||
scheme(uri) == "jdt"
|
||||
&& (package.is_empty() && segs.len() == 3 || segs.get(2).is_some_and(|s| s == package))
|
||||
&& segs.last().is_some_and(|s| s == &format!("{name}.class") || s == &format!("{name}.java"))
|
||||
&& description(uri).is_some_and(|p| {
|
||||
let path = std::path::Path::new(&p);
|
||||
path == jar
|
||||
|| dunce::canonicalize(path).ok().zip(dunce::canonicalize(jar).ok()).is_some_and(|(a, b)| a == b)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -84,6 +114,30 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn jdt_description() {
|
||||
assert!(matches_class(
|
||||
JDT,
|
||||
std::path::Path::new("/Users/me/.m2/repository/spring-boot-4.1.1.jar"),
|
||||
"org.springframework.boot",
|
||||
"SpringApplication"
|
||||
));
|
||||
assert!(!matches_class(
|
||||
JDT,
|
||||
std::path::Path::new("/elsewhere/spring-boot-4.1.1.jar"),
|
||||
"org.springframework.boot",
|
||||
"SpringApplication"
|
||||
));
|
||||
assert!(!matches_class(
|
||||
JDT,
|
||||
std::path::Path::new("/Users/me/.m2/repository/spring-boot-4.1.1.jar"),
|
||||
"other.package",
|
||||
"SpringApplication"
|
||||
));
|
||||
assert!(matches_class(
|
||||
"jdt://contents/a.jar//C.java?=p/%5C/m2%5C/a.jar%3C%28C.class",
|
||||
std::path::Path::new("/m2/a.jar"),
|
||||
"",
|
||||
"C"
|
||||
));
|
||||
assert_eq!(description(JDT).as_deref(), Some("/Users/me/.m2/repository/spring-boot-4.1.1.jar"));
|
||||
assert_eq!(
|
||||
description(
|
||||
@@ -98,10 +152,18 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn detects_generated_code() {
|
||||
assert!(is_decompiled(
|
||||
"// Source code is decompiled from a .class file using FernFlower decompiler (from Intellij IDEA).\npackage a;"
|
||||
));
|
||||
assert!(!is_decompiled("package a;\n// generated by the fernflower decompiler"));
|
||||
assert!(!is_decompiled("// Documentation about code generated by the Fernflower decompiler.\npackage a;"));
|
||||
let recent = "jdt://contents/a.jar/p/C.java?=p/a.jar%3Cp%28C.class";
|
||||
assert_eq!(title(recent, true), "C.class");
|
||||
assert_eq!(title(recent, false), "C.java");
|
||||
assert!(is_decompiled(
|
||||
"// Source code is unavailable, and was generated by the Fernflower decompiler.\npackage a;"
|
||||
));
|
||||
assert!(is_decompiled(
|
||||
assert!(!is_decompiled(
|
||||
"// Failed to get sources. Instead, stub sources have been generated by the disassembler."
|
||||
));
|
||||
assert!(!is_decompiled("/*\n * Copyright 2012-2024 the original author or authors.\n */\npackage a;"));
|
||||
|
||||
@@ -27,6 +27,7 @@ struct MockState {
|
||||
/// uri → text as reconstructed by the mock from didOpen/didChange.
|
||||
docs: Mutex<HashMap<String, String>>,
|
||||
responses: Mutex<HashMap<String, Value>>,
|
||||
errors: Mutex<HashMap<String, (i64, String)>>,
|
||||
/// Computes a response from the request and the open documents (before `responses`).
|
||||
responder: Mutex<Option<Responder>>,
|
||||
peer: Mutex<Option<Peer>>,
|
||||
@@ -122,6 +123,9 @@ impl Handler for MockHandler {
|
||||
"initialize" => Ok(json!({ "capabilities": s.caps.lock().clone(), "serverInfo": { "name": "mock" } })),
|
||||
"shutdown" => Ok(Value::Null),
|
||||
_ => {
|
||||
if let Some(error) = s.errors.lock().get(method).cloned() {
|
||||
return Err(error);
|
||||
}
|
||||
let responder = s.responder.lock().clone();
|
||||
if let Some(v) = responder.and_then(|f| f(s, method, ¶ms)) {
|
||||
return Ok(v);
|
||||
@@ -1012,6 +1016,76 @@ async fn settings_changes_reach_servers_without_restarts() {
|
||||
assert_eq!(s.launches.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn java_source_paths_reach_initialization_live_configuration_and_builds() {
|
||||
let h = harness_configured("java", "java", &[("jdtls", incremental_caps())], |cfg| {
|
||||
cfg.initialization_options = Some(
|
||||
toml::Value::try_from(json!({
|
||||
"bundles": [], "settings": {"java": {"project": {"referencedLibraries": ["lib/**/*.jar"]}}}
|
||||
}))
|
||||
.unwrap(),
|
||||
);
|
||||
});
|
||||
let paths = Arc::new(Mutex::new(Some(vec!["src/main/java".into()])));
|
||||
h.mgr.set_config_hook(Box::new({
|
||||
let paths = paths.clone();
|
||||
move |cfg, _| ide_lsp::jdtls::configure_source_paths(cfg, paths.lock().clone())
|
||||
}));
|
||||
let (_, file) = h.open("Main.java", "public class Main {}");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let state = h.launcher.state("jdtls");
|
||||
let init = state.requested("initialize")[0].clone();
|
||||
assert_eq!(init["initializationOptions"]["settings"]["java"]["project"]["sourcePaths"], json!(["src/main/java"]));
|
||||
assert_eq!(init["initializationOptions"]["triggerFiles"], json!([uri_of(&file)]));
|
||||
*paths.lock() = Some(vec!["generated".into(), "tests".into()]);
|
||||
h.mgr.reconfigure().await;
|
||||
eventually(|| {
|
||||
state
|
||||
.notified("workspace/didChangeConfiguration")
|
||||
.last()
|
||||
.is_some_and(|p| p["settings"]["java"]["project"]["sourcePaths"] == json!(["generated", "tests"]))
|
||||
})
|
||||
.await;
|
||||
let notification = state.notified("workspace/didChangeConfiguration").pop().unwrap();
|
||||
assert_eq!(notification["settings"]["java"]["project"]["referencedLibraries"], json!(["lib/**/*.jar"]));
|
||||
assert_eq!(state.launches.load(Ordering::SeqCst), 1);
|
||||
state.respond("java/buildWorkspace", json!(1));
|
||||
assert_eq!(
|
||||
h.mgr.java_build(&h.root, &Default::default()).await.unwrap(),
|
||||
ide_lsp::jdtls::JavaBuildStatus::Succeeded
|
||||
);
|
||||
assert_eq!(state.requested("java/buildWorkspace"), vec![json!(false)]);
|
||||
|
||||
// Removing the last hint restores importer inference. Omitting a setting
|
||||
// in didChangeConfiguration would retain jdtls's previous preference.
|
||||
*paths.lock() = None;
|
||||
h.mgr.reconfigure().await;
|
||||
eventually(|| state.launches.load(Ordering::SeqCst) == 2).await;
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let init = state.requested("initialize").pop().unwrap();
|
||||
assert!(init["initializationOptions"]["settings"]["java"]["project"].get("sourcePaths").is_none());
|
||||
assert_eq!(init["initializationOptions"]["triggerFiles"], json!([uri_of(&file)]));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn unmanaged_java_run_imports_sources_without_an_open_editor() {
|
||||
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
|
||||
std::fs::create_dir_all(h.root.join("src/demo")).unwrap();
|
||||
let file = h.root.join("src/demo/Main.java");
|
||||
std::fs::write(&file, "package demo; public class Main {}").unwrap();
|
||||
h.mgr.set_config_hook(Box::new(|cfg, _| {
|
||||
ide_lsp::jdtls::configure_source_paths(cfg, Some(vec!["src".into()]));
|
||||
}));
|
||||
let state = h.launcher.state("jdtls");
|
||||
state.respond("java/buildWorkspace", json!(1));
|
||||
assert_eq!(
|
||||
h.mgr.java_build(&h.root, &Default::default()).await.unwrap(),
|
||||
ide_lsp::jdtls::JavaBuildStatus::Succeeded
|
||||
);
|
||||
assert_eq!(state.requested("initialize")[0]["initializationOptions"]["triggerFiles"], json!([uri_of(&file)]));
|
||||
assert!(state.notified("textDocument/didOpen").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fallback_servers_only_run_when_the_preferred_one_is_missing() {
|
||||
// Preferred installed: the alternative is never started.
|
||||
@@ -1543,6 +1617,58 @@ async fn jdt_class_file_contents() {
|
||||
assert_eq!(vd.title, "Lib.class");
|
||||
assert_eq!(vd.language_id.as_str(), "java");
|
||||
assert_eq!(vd.description.as_deref(), Some("/m2/lib-1.0.jar"));
|
||||
let source_uri = jdt.replace("Lib.class", "WithSources.class");
|
||||
s.respond(
|
||||
"java/classFileContents",
|
||||
json!("/* Copyright library author */\npackage org.example;\npublic class WithSources {}"),
|
||||
);
|
||||
let source = h.mgr.virtual_document(&source_uri).await.unwrap();
|
||||
assert!(!source.decompiled);
|
||||
assert_eq!(source.title, "WithSources.java");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn class_file_opening_routes_sources_and_binary_documents() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["workspaceSymbolProvider"] = json!(true);
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
h.open("App.java", "class App {}\n");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("jdtls");
|
||||
let jdt = "jdt://contents/lib.jar/p/Outer.java?=demo/%5C/m2%5C/lib.jar%3Cp%28Outer.class";
|
||||
s.respond("workspace/symbol", json!([
|
||||
{"name":"Outer", "kind":5, "location":{"uri":jdt,"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":0}}}}
|
||||
]));
|
||||
let archive = Some((PathBuf::from("/m2/lib.jar"), "p/Outer$1.class".into()));
|
||||
assert_eq!(h.mgr.java_class_file(Path::new("/m2/lib.jar!/p/Outer$1.class"), archive).await.unwrap(), jdt);
|
||||
assert!(
|
||||
h.mgr
|
||||
.java_class_file(
|
||||
Path::new("/other/lib.jar!/p/Outer.class"),
|
||||
Some(("/other/lib.jar".into(), "p/Outer.class".into()))
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
let sources = h.root.join("src/main/java");
|
||||
std::fs::create_dir_all(sources.join("p")).unwrap();
|
||||
let source = sources.join("p/Outer.java");
|
||||
std::fs::write(&source, "package p; class Outer {} ").unwrap();
|
||||
s.respond("java/classFileContents", json!("// Source code is decompiled from a .class file using FernFlower decompiler (from Intellij IDEA).\npackage p;\npublic class Outer {}"));
|
||||
s.respond("workspace/executeCommand", json!({"org.eclipse.jdt.ls.core.sourcePaths":[sources]}));
|
||||
for class in ["Outer", "Outer$Nested", "Outer$1"] {
|
||||
let path = h.root.join(format!("target/classes/p/{class}.class"));
|
||||
assert_eq!(h.mgr.java_class_file(&path, None).await.unwrap(), source.to_string_lossy());
|
||||
}
|
||||
let path = h.root.join("build/classes/java/main/p/Missing.class");
|
||||
let uri = uri_of(&path);
|
||||
assert_eq!(h.mgr.java_class_file(&path, None).await.unwrap(), uri);
|
||||
let vd = h.mgr.virtual_document(&uri).await.unwrap();
|
||||
assert!(vd.decompiled);
|
||||
assert_eq!(vd.language_id.as_str(), "java");
|
||||
assert_eq!(vd.title, "Missing.class");
|
||||
assert!(s.requested("java/classFileContents").iter().any(|p| p["uri"] == uri));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -1960,6 +2086,155 @@ async fn references_report_a_capped_candidate_search() {
|
||||
assert_eq!(refs.incomplete, Some(ReferencesIncomplete::TooManyFiles));
|
||||
}
|
||||
|
||||
/// The Java command must participate in the same widening contract as standard LSP.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn classified_java_references_widen_without_losing_metadata() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.usages"]});
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
let s = h.launcher.state("jdtls");
|
||||
*s.responder.lock() = Some(Arc::new(|s, method, _| {
|
||||
(method == "workspace/executeCommand").then(|| {
|
||||
let docs = s.docs.lock();
|
||||
let access = if docs.len() == 1 { "read" } else { "readWrite" };
|
||||
Value::Array(
|
||||
docs.iter()
|
||||
.flat_map(|(uri, text)| {
|
||||
occurrences(uri, text)
|
||||
.into_iter()
|
||||
.map(|location| json!({"location": location, "kind": "field", "access": access}))
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
})
|
||||
}));
|
||||
let b = h.root.join("b.java");
|
||||
std::fs::write(&b, "target++;").unwrap();
|
||||
let (doc, _) = h.open("a.java", "int target;");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
eventually(|| s.docs.lock().len() == 1).await;
|
||||
let seen = grep_candidates(&h);
|
||||
let scoped = h.mgr.references(doc, Pos::new(0, 5), true, false, Default::default()).await.unwrap();
|
||||
assert_eq!(scoped.locations.len(), 1);
|
||||
assert!(seen.lock().is_empty());
|
||||
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
|
||||
assert_eq!(refs.locations.len(), 2);
|
||||
assert_eq!(refs.classified.len(), 2);
|
||||
assert!(refs.classified.iter().all(|r| matches!(r.access, Some(ReferenceAccess::ReadWrite))));
|
||||
assert!(refs.classified.iter().all(|r| matches!(r.kind, ReferenceKind::Field)));
|
||||
assert_eq!(refs.incomplete, None);
|
||||
assert_eq!(s.requested("workspace/executeCommand").len(), 3);
|
||||
assert!(s.requested("textDocument/references").is_empty());
|
||||
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
|
||||
for limit_hit in [true, false] {
|
||||
let skipped = h.root.join("large.java");
|
||||
std::fs::write(&skipped, " ".repeat((1 << 20) + 1)).unwrap();
|
||||
h.mgr.set_candidates_hook(Box::new(move |_, _| ide_lsp::CandidateFiles {
|
||||
files: vec![skipped.clone()],
|
||||
limit_hit,
|
||||
}));
|
||||
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
|
||||
assert_eq!(
|
||||
refs.incomplete,
|
||||
Some(if limit_hit { ReferencesIncomplete::TooManyFiles } else { ReferencesIncomplete::FilesSkipped })
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn failed_java_command_falls_back_to_unclassified_native_references() {
|
||||
for project_wide in [false, true] {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.usages"]});
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
let s = h.launcher.state("jdtls");
|
||||
s.errors.lock().insert("workspace/executeCommand".into(), (-32603, "NoSuchMethodError".into()));
|
||||
*s.responder.lock() = Some(open_files_only(Vec::new()));
|
||||
let (doc, path) = h.open("a.java", "int target;");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
eventually(|| s.docs.lock().len() == 1).await;
|
||||
let refs = h.mgr.references(doc, Pos::new(0, 5), true, project_wide, Default::default()).await.unwrap();
|
||||
assert_eq!(refs.locations.len(), 1);
|
||||
assert_eq!(refs.locations[0].path, path);
|
||||
assert!(refs.classified.is_empty());
|
||||
assert_eq!(s.requested("workspace/executeCommand").len(), 1);
|
||||
assert_eq!(s.requested("textDocument/references").len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn failed_widened_java_command_retries_with_native_references() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.usages"]});
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
let s = h.launcher.state("jdtls");
|
||||
let native = open_files_only(Vec::new());
|
||||
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
|
||||
if method == "workspace/executeCommand" {
|
||||
// The initial query succeeds, but the next extension query fails.
|
||||
s.errors.lock().insert(method.into(), (-32603, "reflection failed".into()));
|
||||
return Some(Value::Array(
|
||||
s.docs
|
||||
.lock()
|
||||
.iter()
|
||||
.flat_map(|(uri, text)| {
|
||||
occurrences(uri, text)
|
||||
.into_iter()
|
||||
.map(|location| json!({"location": location, "kind": "field", "access": "read"}))
|
||||
})
|
||||
.collect(),
|
||||
));
|
||||
}
|
||||
native(s, method, params)
|
||||
}));
|
||||
std::fs::write(h.root.join("b.java"), "target++;").unwrap();
|
||||
grep_candidates(&h);
|
||||
let (doc, _) = h.open("a.java", "int target;");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
eventually(|| s.docs.lock().len() == 1).await;
|
||||
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
|
||||
assert_eq!(refs.locations.len(), 2);
|
||||
assert!(refs.classified.is_empty());
|
||||
assert_eq!(s.requested("workspace/executeCommand").len(), 2);
|
||||
assert_eq!(s.requested("textDocument/references").len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn superseded_java_command_does_not_fall_back() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.usages"]});
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
let s = h.launcher.state("jdtls");
|
||||
let (doc, _) = h.open("a.java", "int target;");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let mgr = Arc::downgrade(&h.mgr);
|
||||
*s.responder.lock() = Some(Arc::new(move |_, method, _| {
|
||||
if method != "workspace/executeCommand" {
|
||||
return None;
|
||||
}
|
||||
mgr.upgrade().unwrap().did_change(doc, 2, &[change(rng(0, 0, 0, 0), " ")], &|| unreachable!());
|
||||
// Invalid extension response after the source version changed.
|
||||
Some(json!({"failed": true}))
|
||||
}));
|
||||
let err = h.mgr.references(doc, Pos::new(0, 5), true, false, Default::default()).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert!(s.requested("textDocument/references").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cancelled_java_command_does_not_fall_back() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.usages"]});
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
let s = h.launcher.state("jdtls");
|
||||
s.errors.lock().insert("workspace/executeCommand".into(), (-32800, "cancelled".into()));
|
||||
let (doc, _) = h.open("a.java", "int target;");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let err = h.mgr.references(doc, Pos::new(0, 5), true, false, Default::default()).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert!(s.requested("textDocument/references").is_empty());
|
||||
}
|
||||
|
||||
/// What each search widened with candidate files reports for the symbol at the start of `doc`.
|
||||
async fn incomplete_reports(h: &Harness, doc: DocId) -> Vec<(&'static str, Option<ReferencesIncomplete>)> {
|
||||
let at = Pos::new(0, 5);
|
||||
@@ -2324,3 +2599,138 @@ async fn external_projects_are_capability_gated_and_follow_lifecycle() {
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn gopls_interactive_command_validates_before_execution_and_applies_edits() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["experimental"] = json!({"interactiveResolveProvider": {"kinds": ["command"]}});
|
||||
caps["executeCommandProvider"] = json!({"commands": ["gopls.implement_interface", "gopls.add_test"]});
|
||||
let h = harness(&[("gopls", caps)]);
|
||||
let (doc, path) = h.open("probe.mk", "type T struct{}\n");
|
||||
h.wait_status("gopls", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("gopls");
|
||||
let server = h.mgr.servers()[0].id;
|
||||
assert_eq!(
|
||||
s.requested("initialize")[0]["capabilities"]["experimental"]["interactiveResolve"],
|
||||
json!({"inputTypes": ["string"]})
|
||||
);
|
||||
let new_file = h.root.join("probe_test.go");
|
||||
let edit = json!({"documentChanges": [{"kind": "create", "uri": uri_of(&new_file)}, {
|
||||
"textDocument": {"uri": uri_of(&path), "version": 1},
|
||||
"edits": [{"range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 0}}, "newText": "// generated\n"}]
|
||||
}]});
|
||||
*s.responder.lock() = Some(Arc::new(move |s, method, p| {
|
||||
if method == "command/resolve" {
|
||||
let valid = p["formAnswers"][0]["value"] == "pkg.I";
|
||||
return Some(if valid {
|
||||
json!({"command": p["command"], "arguments": p["arguments"], "formAnswers": p["formAnswers"]})
|
||||
} else {
|
||||
json!({"command": p["command"], "arguments": p["arguments"], "formFields": [{"id": "interface", "description": "Enter interface", "required": true, "type": {"kind": "string"}, "error": if p["formAnswers"].as_array().is_some_and(|a| !a.is_empty()) { "Unknown interface" } else { "" }}]})
|
||||
});
|
||||
}
|
||||
if method == "workspace/executeCommand" {
|
||||
if p["command"] != "gopls.add_test" {
|
||||
assert_eq!(p["formAnswers"], json!([{"id": "interface", "value": "pkg.I"}]));
|
||||
}
|
||||
let reply: Value = tokio::task::block_in_place(|| {
|
||||
tokio::runtime::Handle::current().block_on(s.peer().request(
|
||||
"workspace/applyEdit",
|
||||
json!({"edit": edit}),
|
||||
None,
|
||||
))
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(reply, json!({"applied": true}));
|
||||
return Some(Value::Null);
|
||||
}
|
||||
None
|
||||
}));
|
||||
let applied = Arc::new(Mutex::new(Vec::new()));
|
||||
let received = applied.clone();
|
||||
h.mgr.set_apply_edit_hook(Box::new(move |edit| {
|
||||
received.lock().push(edit);
|
||||
true
|
||||
}));
|
||||
let command = Command {
|
||||
title: "Implement".into(),
|
||||
command: "gopls.implement_interface".into(),
|
||||
arguments: vec![json!({"location": 1})],
|
||||
};
|
||||
let token = ide_core::CancellationToken::new;
|
||||
let initial = h.mgr.resolve_command(doc, server, command.clone(), vec![], token()).await.unwrap().unwrap();
|
||||
assert_eq!(initial.form_fields[0].description, "Enter interface");
|
||||
let invalid = h
|
||||
.mgr
|
||||
.resolve_command(
|
||||
doc,
|
||||
server,
|
||||
command.clone(),
|
||||
vec![FormAnswer { id: "interface".into(), value: "bad".into() }],
|
||||
token(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(invalid.form_fields[0].error.as_deref(), Some("Unknown interface"));
|
||||
assert!(applied.lock().is_empty());
|
||||
assert!(s.requested("workspace/executeCommand").is_empty());
|
||||
let cancelled = token();
|
||||
cancelled.cancel();
|
||||
let err = h.mgr.resolve_command(doc, server, command.clone(), vec![], cancelled).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
let cancelled = token();
|
||||
cancelled.cancel();
|
||||
let err = h.mgr.execute_action_command(doc, server, command.clone(), vec![], cancelled).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert!(applied.lock().is_empty());
|
||||
assert!(s.requested("workspace/executeCommand").is_empty());
|
||||
let validated = h
|
||||
.mgr
|
||||
.resolve_command(
|
||||
doc,
|
||||
server,
|
||||
command,
|
||||
vec![FormAnswer { id: "interface".into(), value: "pkg.I".into() }],
|
||||
token(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(validated.form_fields.is_empty());
|
||||
h.mgr.execute_action_command(doc, server, validated.command, validated.form_answers, token()).await.unwrap();
|
||||
assert_eq!(applied.lock().len(), 1);
|
||||
let created = h
|
||||
.mgr
|
||||
.execute_action_command(
|
||||
doc,
|
||||
server,
|
||||
Command { title: "Test".into(), command: "gopls.add_test".into(), arguments: vec![] },
|
||||
vec![],
|
||||
token(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(created, vec![new_file]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn interactive_capability_is_scoped_to_gopls() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
let (doc, _) = h.open("probe.mk", "x\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("mock");
|
||||
assert_eq!(s.requested("initialize")[0]["capabilities"]["experimental"], json!({}));
|
||||
let form = h
|
||||
.mgr
|
||||
.resolve_command(
|
||||
doc,
|
||||
h.mgr.servers()[0].id,
|
||||
Command { title: "Run".into(), command: "mock.run".into(), arguments: vec![json!(1)] },
|
||||
vec![],
|
||||
ide_core::CancellationToken::new(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(form.is_none());
|
||||
assert!(s.requested("command/resolve").is_empty());
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Imports from the client filesystem into a remote project, without deployment mappings.
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use ide_ssh::RemoteFs;
|
||||
use std::path::Path;
|
||||
|
||||
/// Copies entries, preserving symlinks and empty folders. Reports skipped special files.
|
||||
pub async fn import_local(fs: &RemoteFs, from: &Path, to: &str, cancel: &CancellationToken) -> IdeResult<Vec<String>> {
|
||||
let mut skipped = Vec::new();
|
||||
import_entry(fs, from, to, cancel, &mut skipped).await?;
|
||||
Ok(skipped)
|
||||
}
|
||||
|
||||
async fn import_entry(
|
||||
fs: &RemoteFs,
|
||||
from: &Path,
|
||||
to: &str,
|
||||
cancel: &CancellationToken,
|
||||
skipped: &mut Vec<String>,
|
||||
) -> IdeResult<()> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if fs.stat(to).await?.is_some() {
|
||||
return Err(IdeError::new(ide_core::error::ErrorKind::AlreadyExists, format!("{to} already exists")));
|
||||
}
|
||||
let meta = tokio::fs::symlink_metadata(from).await?;
|
||||
if meta.is_symlink() {
|
||||
let result = async {
|
||||
let target = tokio::fs::read_link(from).await?;
|
||||
let target = target.to_str().ok_or_else(|| IdeError::invalid("Link target is not valid UTF-8"))?;
|
||||
fs.symlink(target, to).await
|
||||
}
|
||||
.await;
|
||||
if let Err(e) = result {
|
||||
skipped.push(format!("{}: {e}", from.display()));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if !meta.is_file() && !meta.is_dir() {
|
||||
skipped.push(format!("{}: skipped special file", from.display()));
|
||||
return Ok(());
|
||||
}
|
||||
if meta.is_file() {
|
||||
return fs.upload_new(from, to, cancel).await;
|
||||
}
|
||||
fs.create_dir(to).await?;
|
||||
let result = async {
|
||||
let mut entries = tokio::fs::read_dir(from).await?;
|
||||
while let Some(entry) = entries.next_entry().await? {
|
||||
let name = entry.file_name();
|
||||
let name = name.to_str().ok_or_else(|| IdeError::invalid("File name is not valid UTF-8"))?;
|
||||
Box::pin(import_entry(fs, &entry.path(), &ide_ssh::sftp::join(to, name), cancel, skipped)).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
if result.is_err() {
|
||||
let _ = fs.remove(to).await;
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! configurations on run targets ([`target`]).
|
||||
|
||||
pub mod deploy;
|
||||
pub mod import;
|
||||
pub mod mapping;
|
||||
pub mod service;
|
||||
pub mod target;
|
||||
|
||||
@@ -58,6 +58,75 @@ fn no_progress() -> impl FnMut(&str, usize, usize) + Send {
|
||||
|_, _, _| {}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn client_imports_preserve_conflicts_and_report_failure_over_sftp_and_local() {
|
||||
let env = env().await;
|
||||
for sftp in [false, true] {
|
||||
let fs = if sftp { RemoteFs::new(env.session.sftp().await.unwrap()) } else { RemoteFs::Local };
|
||||
let base =
|
||||
if sftp { "/imports".to_owned() } else { env.server_root.join("local").to_string_lossy().into_owned() };
|
||||
fs.mkdir_all(&base).await.unwrap();
|
||||
let to = ide_ssh::sftp::join(&base, "copy");
|
||||
let cancel = CancellationToken::new();
|
||||
std::fs::create_dir_all(env.project.join("empty")).unwrap();
|
||||
ide_remote::import::import_local(&fs, &env.project, &to, &cancel).await.unwrap();
|
||||
assert_eq!(fs.read(&format!("{to}/src/main.py")).await.unwrap(), b"print('hi')\n");
|
||||
assert!(fs.stat(&format!("{to}/empty")).await.unwrap().unwrap().is_dir);
|
||||
let err = ide_remote::import::import_local(&fs, &env.project, &to, &cancel).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::AlreadyExists);
|
||||
let file = format!("{to}/README.md");
|
||||
assert!(fs.upload_new(&env.project.join("src/main.py"), &file, &cancel).await.is_err());
|
||||
assert_eq!(fs.read(&file).await.unwrap(), b"# demo\n");
|
||||
let missing =
|
||||
ide_remote::import::import_local(&fs, &env.project.join("missing"), &format!("{base}/missing"), &cancel)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(missing.kind, ide_core::error::ErrorKind::NotFound);
|
||||
cancel.cancel();
|
||||
let err = ide_remote::import::import_local(&fs, &env.project, &format!("{base}/cancelled"), &cancel)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert!(fs.stat(&format!("{base}/cancelled")).await.unwrap().is_none());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let source = env.project.join("links-tree");
|
||||
std::fs::create_dir_all(&source).unwrap();
|
||||
std::fs::write(source.join("run.sh"), "#!/bin/sh\necho imported\n").unwrap();
|
||||
std::fs::set_permissions(source.join("run.sh"), std::fs::Permissions::from_mode(0o751)).unwrap();
|
||||
std::os::unix::fs::symlink("run.sh", source.join("link")).unwrap();
|
||||
std::os::unix::fs::symlink("missing", source.join("dangling")).unwrap();
|
||||
std::os::unix::fs::symlink(".", source.join("cycle")).unwrap();
|
||||
let socket = std::os::unix::net::UnixListener::bind(source.join("socket")).unwrap();
|
||||
let dest = format!("{base}/links");
|
||||
let skipped =
|
||||
ide_remote::import::import_local(&fs, &source, &dest, &CancellationToken::new()).await.unwrap();
|
||||
assert_eq!(skipped, vec![format!("{}: skipped special file", source.join("socket").display())]);
|
||||
let on_disk = if sftp { env.server_root.join("imports/links") } else { std::path::PathBuf::from(&dest) };
|
||||
for (name, target) in [("link", "run.sh"), ("dangling", "missing"), ("cycle", ".")] {
|
||||
assert_eq!(std::fs::read_link(on_disk.join(name)).unwrap(), std::path::PathBuf::from(target));
|
||||
}
|
||||
assert_eq!(std::fs::metadata(on_disk.join("run.sh")).unwrap().permissions().mode() & 0o777, 0o751);
|
||||
assert_eq!(fs.read(&format!("{dest}/run.sh")).await.unwrap(), b"#!/bin/sh\necho imported\n");
|
||||
assert!(!on_disk.join("socket").exists());
|
||||
let skipped = ide_remote::import::import_local(
|
||||
&fs,
|
||||
&source.join("socket"),
|
||||
&format!("{base}/socket"),
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(skipped.len(), 1);
|
||||
assert!(fs.stat(&format!("{base}/socket")).await.unwrap().is_none());
|
||||
drop(socket);
|
||||
std::fs::remove_dir_all(source).unwrap();
|
||||
}
|
||||
fs.close().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn uploads_compares_syncs_and_downloads() {
|
||||
let env = env().await;
|
||||
|
||||
@@ -687,9 +687,9 @@ fn detect_go(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let mut seen = HashSet::new();
|
||||
for member in crate::go::work_modules(&work) {
|
||||
let dir = root.join(member);
|
||||
let dir = dir.canonicalize().unwrap_or(dir);
|
||||
let dir = dunce::canonicalize(&dir).unwrap_or(dir);
|
||||
if dir.join("go.mod").is_file() && seen.insert(dir.clone()) {
|
||||
let canonical_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
|
||||
let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
|
||||
let rel = dir.strip_prefix(&canonical_root).unwrap_or(&dir).to_path_buf();
|
||||
detect_go_module(&dir, (!rel.as_os_str().is_empty()).then_some(rel), out);
|
||||
}
|
||||
|
||||
@@ -494,7 +494,7 @@ mod tests {
|
||||
fn pathing_jar_runs_with_a_local_jdk() {
|
||||
let Some(home) = std::env::var_os("JAVA_HOME").map(PathBuf::from).or_else(|| {
|
||||
let java = crate::which::find_executable("java", &std::env::var_os("PATH").unwrap_or_default())?;
|
||||
std::fs::canonicalize(java).ok()?.parent()?.parent().map(Path::to_path_buf)
|
||||
dunce::canonicalize(java).ok()?.parent()?.parent().map(Path::to_path_buf)
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -228,8 +228,7 @@ pub fn deployment(root: &Path, base: &Path, config: &RunConfig, resources_only:
|
||||
.filter(|v| !v.trim().is_empty())
|
||||
.ok_or_else(|| invalid("Choose a WAR file or exploded directory"))?;
|
||||
let path = root.join(value);
|
||||
let path = path
|
||||
.canonicalize()
|
||||
let path = dunce::canonicalize(&path)
|
||||
.map_err(|e| invalid(format!("Invalid Tomcat deployment: {} ({e})", path.display())))?;
|
||||
if (kind == "war" && (!path.is_file() || !path.extension().is_some_and(|e| e.eq_ignore_ascii_case("war"))))
|
||||
|| (kind == "directory" && !path.is_dir())
|
||||
@@ -264,13 +263,14 @@ pub fn script_command(home: &Path, windows: bool, verb: &str) -> (String, Vec<St
|
||||
}
|
||||
|
||||
pub fn prepare(root: &Path, cache: &Path, config: &mut RunConfig) -> IdeResult<()> {
|
||||
let home = root
|
||||
.join(config.extras.params.get("tomcatHome").ok_or_else(|| invalid("Choose a Tomcat installation directory"))?)
|
||||
.canonicalize()?;
|
||||
// Batch scripts and their environment variables require ordinary Windows paths.
|
||||
let home = dunce::canonicalize(root.join(
|
||||
config.extras.params.get("tomcatHome").ok_or_else(|| invalid("Choose a Tomcat installation directory"))?,
|
||||
))?;
|
||||
validate_home(&home)?;
|
||||
let base = base_dir(cache, &config.id);
|
||||
fs::create_dir_all(&base)?;
|
||||
let base = base.canonicalize()?;
|
||||
let base = dunce::canonicalize(&base)?;
|
||||
let doc = deployment(root, &base, config, false)?;
|
||||
let context = effective_context(config, &doc);
|
||||
let context = context_name(&context)?;
|
||||
@@ -304,7 +304,7 @@ pub fn prepare(root: &Path, cache: &Path, config: &mut RunConfig) -> IdeResult<(
|
||||
config.env.insert("CATALINA_HOME".into(), home.to_string_lossy().into_owned());
|
||||
config.env.insert("CATALINA_BASE".into(), base.to_string_lossy().into_owned());
|
||||
if let Some(jre) = config.extras.params.get("jre").filter(|s| !s.trim().is_empty()) {
|
||||
let jre = root.join(jre).canonicalize()?;
|
||||
let jre = dunce::canonicalize(root.join(jre))?;
|
||||
config.env.insert("JAVA_HOME".into(), jre.to_string_lossy().into_owned());
|
||||
config.env.insert("JRE_HOME".into(), jre.to_string_lossy().into_owned());
|
||||
} else if let Some(java) = config.env.get("JAVA_HOME").cloned() {
|
||||
@@ -432,7 +432,7 @@ mod tests {
|
||||
assert_eq!(fs::read_to_string(dest.join("WEB-INF/classes/App.class")).unwrap(), "class2");
|
||||
c.extras.params.insert("deployment".into(), "war".into());
|
||||
c.extras.params.insert("deploymentPath".into(), "web app.war".into());
|
||||
assert_eq!(deployment(tmp.path(), &base, &c, false).unwrap(), war.canonicalize().unwrap());
|
||||
assert_eq!(deployment(tmp.path(), &base, &c, false).unwrap(), dunce::canonicalize(&war).unwrap());
|
||||
fs::create_dir_all(tmp.path().join("WebContent")).unwrap();
|
||||
c.extras.params.insert("deployment".into(), "directory".into());
|
||||
c.extras.params.insert("deploymentPath".into(), "WebContent".into());
|
||||
@@ -463,11 +463,22 @@ mod tests {
|
||||
#[test]
|
||||
fn prepares_isolated_base_and_jdwp_only_for_run() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("Tomcat Home");
|
||||
check_prepared_paths(tmp.path());
|
||||
}
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn prepares_plain_windows_paths_from_verbatim_root() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = PathBuf::from(format!(r"\\?\{}", dunce::canonicalize(tmp.path()).unwrap().display()));
|
||||
check_prepared_paths(&root);
|
||||
}
|
||||
fn check_prepared_paths(root: &Path) {
|
||||
let home = root.join("Tomcat Home");
|
||||
fs::create_dir_all(home.join("bin")).unwrap();
|
||||
fs::create_dir_all(home.join("conf")).unwrap();
|
||||
fs::create_dir_all(tmp.path().join("WebRoot")).unwrap();
|
||||
fs::create_dir_all(root.join("WebRoot")).unwrap();
|
||||
fs::write(home.join("bin/catalina.sh"), "").unwrap();
|
||||
fs::write(home.join("bin/catalina.bat"), "").unwrap();
|
||||
archive(
|
||||
&home.join("lib/catalina.jar"),
|
||||
&[("org/apache/catalina/util/ServerInfo.properties", "server.info=Apache Tomcat/10.1")],
|
||||
@@ -486,17 +497,35 @@ mod tests {
|
||||
c.extras.params.insert(k.into(), v.into());
|
||||
}
|
||||
c.env.insert("JAVA_HOME".into(), "/jdk with spaces".into());
|
||||
prepare(tmp.path(), &tmp.path().join("cache"), &mut c).unwrap();
|
||||
let cache = root.join("cache");
|
||||
prepare(root, &cache, &mut c).unwrap();
|
||||
assert_eq!(fs::read_to_string(home.join("conf/server.xml")).unwrap(), server);
|
||||
let base = PathBuf::from(&c.env["CATALINA_BASE"]);
|
||||
assert!(base.join("conf/Catalina/localhost/app.xml").is_file());
|
||||
let context = base.join("conf/Catalina/localhost/app.xml");
|
||||
let doc = dunce::canonicalize(root.join("WebRoot")).unwrap();
|
||||
assert_eq!(fs::read_to_string(&context).unwrap(), context_xml(&doc, false));
|
||||
assert_eq!(c.env["CATALINA_HOME"], dunce::canonicalize(&home).unwrap().to_string_lossy());
|
||||
assert_eq!(base, dunce::canonicalize(base_dir(&cache, &c.id)).unwrap());
|
||||
assert!(c.env["CATALINA_OPTS"].contains("suspend=n,address=127.0.0.1:0"));
|
||||
assert!(c.env["CATALINA_OPTS"].contains("-Xmx256m"));
|
||||
assert!(!c.env.get("JAVA_OPTS").is_some_and(|s| s.contains("jdwp")));
|
||||
assert_eq!(c.env["JRE_HOME"], "/jdk with spaces");
|
||||
let stop = c.extras.stop_command.unwrap();
|
||||
let stop = c.extras.stop_command.as_ref().unwrap();
|
||||
assert!(stop.contains("stop"));
|
||||
let script = if cfg!(windows) { "catalina.bat" } else { "catalina.sh" };
|
||||
assert!(stop.contains(script));
|
||||
|
||||
fs::create_dir_all(root.join("JDK Home")).unwrap();
|
||||
c.extras.params.insert("jre".into(), "JDK Home".into());
|
||||
prepare(root, &cache, &mut c).unwrap();
|
||||
let jre = dunce::canonicalize(root.join("JDK Home")).unwrap();
|
||||
for key in ["JAVA_HOME", "JRE_HOME"] {
|
||||
assert_eq!(c.env[key], jre.to_string_lossy());
|
||||
}
|
||||
assert!(!c.command.contains(r"\\?\"));
|
||||
assert!(c.args.iter().all(|arg| !arg.contains(r"\\?\")));
|
||||
assert!(!c.extras.stop_command.as_ref().unwrap().contains(r"\\?\"));
|
||||
assert!(c.env.values().all(|value| !value.contains(r"\\?\")));
|
||||
assert!(!fs::read_to_string(context).unwrap().contains(r"\\?\"));
|
||||
}
|
||||
}
|
||||
@@ -608,6 +608,21 @@ fn go_work_members_define_configs_including_deep_and_quoted_directories() {
|
||||
assert!(configs.iter().any(|c| c.id == "go:test:module with spaces"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_work_external_member_has_a_plain_absolute_working_directory() {
|
||||
let dir = project(&[
|
||||
("workspace/go.work", "go 1.22\nuse ../external\n"),
|
||||
("external/go.mod", "module example.com/external\ngo 1.22\n"),
|
||||
("external/main.go", "package main\nfunc main() {}"),
|
||||
]);
|
||||
let configs = detect(&dir.path().join("workspace"));
|
||||
let run = configs.iter().find(|c| c.kind == "go" && !c.is_test).unwrap();
|
||||
let cwd = run.cwd.as_deref().unwrap();
|
||||
assert_eq!(cwd, dunce::canonicalize(dir.path().join("external")).unwrap());
|
||||
assert!(cwd.is_absolute());
|
||||
assert!(!cwd.to_string_lossy().starts_with(r"\\?\"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_work_parser_ignores_other_directives_comments_and_malformed_groups() {
|
||||
use ide_run::go::work_modules;
|
||||
|
||||
@@ -735,8 +735,8 @@ fn sh_quote(s: &str) -> String {
|
||||
}
|
||||
|
||||
/// Command typed into a new terminal to activate the project virtualenv
|
||||
/// (PyCharm's Tools › Terminal › "Activate virtualenv"), for the given shell.
|
||||
pub fn terminal_activation(root: &Path, s: &Settings, shell: Option<&str>) -> Option<String> {
|
||||
/// (Tools › Terminal › "Activate virtualenv"). `shell` must be the resolved PTY shell.
|
||||
pub fn terminal_activation(root: &Path, s: &Settings, shell: &str) -> Option<String> {
|
||||
if !s.languages.python.activate_virtualenv {
|
||||
return None;
|
||||
}
|
||||
@@ -744,12 +744,8 @@ pub fn terminal_activation(root: &Path, s: &Settings, shell: Option<&str>) -> Op
|
||||
if std::env::var_os("VIRTUAL_ENV").is_some_and(|v| Path::new(&v) == venv) {
|
||||
return None;
|
||||
}
|
||||
let shell = shell
|
||||
.map(str::to_owned)
|
||||
.or_else(|| std::env::var("SHELL").ok())
|
||||
.or_else(|| std::env::var("COMSPEC").ok())
|
||||
.unwrap_or_default();
|
||||
let name = Path::new(&shell).file_stem().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
|
||||
let name = shell.rsplit(['/', '\\']).next().unwrap_or(shell);
|
||||
let name = Path::new(name).file_stem().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
|
||||
let script = |file: &str| venv.join(bin_dir()).join(file);
|
||||
let line = match name.as_str() {
|
||||
"fish" => format!("source {}", sh_quote(&script("activate.fish").to_string_lossy())),
|
||||
|
||||
@@ -301,8 +301,12 @@ pub fn runtimes(jdks: &[Jdk]) -> Vec<serde_json::Value> {
|
||||
|
||||
/// Stable FNV-1a hash of a path, for per-workspace directories.
|
||||
fn path_key(p: &Path) -> String {
|
||||
text_key(&p.to_string_lossy())
|
||||
}
|
||||
|
||||
fn text_key(text: &str) -> String {
|
||||
let mut h: u64 = 0xcbf29ce484222325;
|
||||
for b in p.to_string_lossy().as_bytes() {
|
||||
for b in text.as_bytes() {
|
||||
h ^= *b as u64;
|
||||
h = h.wrapping_mul(0x100000001b3);
|
||||
}
|
||||
@@ -340,10 +344,15 @@ pub fn configure_jdtls(
|
||||
if !cfg.args.iter().any(|a| a == "-data") {
|
||||
// ECJ builds incrementally: classes compiled without (or with another) Lombok
|
||||
// agent would be kept, so each agent gets its own workspace and a full build.
|
||||
let key = match agent {
|
||||
let mut key = match agent {
|
||||
Some(jar) => format!("{}-{}", path_key(server_root), path_key(jar)),
|
||||
None => path_key(server_root),
|
||||
};
|
||||
if let Some(paths) = cfg.settings.as_ref().and_then(|s| s.pointer("/java/project/sourcePaths")) {
|
||||
// Invisible projects retain a cached resource tree across restarts.
|
||||
// A different source model needs a clean import, including new folders.
|
||||
key.push_str(&format!("-sources-{}", text_key(&paths.to_string())));
|
||||
}
|
||||
let dir = data_dir.join("lsp").join("jdtls").join(key);
|
||||
cfg.args.extend(["-data".to_owned(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
@@ -528,6 +537,26 @@ fn parse_java_version(v: &str) -> Option<u32> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unmanaged_source_models_have_separate_jdtls_workspaces() {
|
||||
let data = tempfile::tempdir().unwrap();
|
||||
let workspace = |paths: Option<serde_json::Value>| {
|
||||
let mut cfg: LanguageServerConfig = toml::from_str("name = 'jdtls'\ncommand = 'jdtls'").unwrap();
|
||||
if let Some(paths) = paths {
|
||||
cfg.settings = Some(json!({"java": {"project": {"sourcePaths": paths}}}));
|
||||
}
|
||||
configure_jdtls(&mut cfg, Path::new("/project"), data.path(), &[], None, None, 25, &[], None);
|
||||
cfg.args.windows(2).find(|a| a[0] == "-data").unwrap()[1].clone()
|
||||
};
|
||||
let inferred = workspace(None);
|
||||
let source = workspace(Some(json!(["src/main/java"])));
|
||||
let tests = workspace(Some(json!(["src/main/java", "src/test/java"])));
|
||||
assert_ne!(inferred, source);
|
||||
assert_ne!(source, tests);
|
||||
assert_eq!(source, workspace(Some(json!(["src/main/java"]))));
|
||||
assert_eq!(inferred, workspace(None), "build-tool projects retain their existing cache key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provisioning_runtime_preserves_implicit_project_jdk() {
|
||||
let data = tempfile::tempdir().unwrap();
|
||||
@@ -688,6 +717,20 @@ mod tests {
|
||||
configure_jdtls(&mut plain, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], None);
|
||||
let data = |c: &LanguageServerConfig| c.args[c.args.iter().position(|a| a == "-data").unwrap() + 1].clone();
|
||||
assert_ne!(data(&cfg), data(&plain), "a separate workspace, so everything is rebuilt with the agent");
|
||||
let patched = Path::new("/managed/lombok-1.18.48-openidea.1.jar");
|
||||
let mut fixed = jdtls();
|
||||
configure_jdtls(
|
||||
&mut fixed,
|
||||
Path::new("/p"),
|
||||
Path::new("/data"),
|
||||
&[],
|
||||
None,
|
||||
None,
|
||||
JDTLS_MIN_JAVA,
|
||||
&[],
|
||||
Some(patched),
|
||||
);
|
||||
assert_ne!(data(&cfg), data(&fixed), "the patch must rebuild classes compiled with the official agent");
|
||||
let before = cfg.clone();
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], Some(jar));
|
||||
assert_eq!(cfg, before, "idempotent");
|
||||
@@ -904,3 +947,100 @@ mod tests {
|
||||
assert_eq!(project_java_version(dir), Some(8));
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs the app-owned JDT LS command bundle, falling back to ordinary LSP on IO failure.
|
||||
pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
|
||||
let extension = data_dir.join("java-usages-1.1.1.jar");
|
||||
let bytes = include_bytes!("../../../plugins/java-usages/openidea-java-usages.jar");
|
||||
if std::fs::read(&extension).is_ok_and(|old| old == bytes) {
|
||||
clean_usages_bundles(data_dir, &extension);
|
||||
return Some(extension);
|
||||
}
|
||||
// Write then rename: another window must never read a partially written jar.
|
||||
let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_nanos();
|
||||
let temporary = data_dir.join(format!("java-usages-{}-{nonce}.tmp", std::process::id()));
|
||||
let result = std::fs::create_dir_all(data_dir)
|
||||
.and_then(|_| std::fs::write(&temporary, bytes))
|
||||
.and_then(|_| std::fs::rename(&temporary, &extension));
|
||||
match result {
|
||||
Ok(()) => {
|
||||
clean_usages_bundles(data_dir, &extension);
|
||||
Some(extension)
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
if std::fs::read(&extension).is_ok_and(|old| old == bytes) {
|
||||
clean_usages_bundles(data_dir, &extension);
|
||||
return Some(extension);
|
||||
}
|
||||
tracing::warn!("Java usages extension unavailable; using standard references: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn clean_usages_bundles(data_dir: &Path, current: &Path) {
|
||||
let Ok(entries) = std::fs::read_dir(data_dir) else { return };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let Some(name) = path.file_name().and_then(|n| n.to_str()) else { continue };
|
||||
let Some(suffix) = name.strip_prefix("java-usages-") else { continue };
|
||||
let numeric = |s: &str| !s.is_empty() && s.bytes().all(|c| c.is_ascii_digit());
|
||||
let old_jar = suffix.strip_suffix(".jar").is_some_and(|v| {
|
||||
let parts: Vec<_> = v.split('.').collect();
|
||||
parts.len() == 3 && parts.into_iter().all(numeric)
|
||||
}) && path != current;
|
||||
// Preserve recent temporary files: another window may still be installing.
|
||||
let stale_temp = suffix
|
||||
.strip_suffix(".tmp")
|
||||
.and_then(|v| v.split_once('-'))
|
||||
.is_some_and(|(pid, nonce)| numeric(pid) && numeric(nonce))
|
||||
&& entry
|
||||
.metadata()
|
||||
.ok()
|
||||
.and_then(|m| m.modified().ok())
|
||||
.and_then(|t| t.elapsed().ok())
|
||||
.is_some_and(|age| age.as_secs() > 24 * 60 * 60);
|
||||
if old_jar || stale_temp {
|
||||
// A running server can hold an old bundle open on Windows.
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod usages_bundle_tests {
|
||||
#[test]
|
||||
fn cleans_old_bundles_and_abandoned_temporary_files_on_install_and_reuse() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for reuse in [false, true] {
|
||||
let old = dir.path().join("java-usages-1.0.0.jar");
|
||||
let stale = dir.path().join("java-usages-123-456.tmp");
|
||||
std::fs::write(&old, b"old").unwrap();
|
||||
std::fs::write(&stale, b"partial").unwrap();
|
||||
let times = std::fs::FileTimes::new()
|
||||
.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(48 * 60 * 60));
|
||||
std::fs::File::options().write(true).open(&stale).unwrap().set_times(times).unwrap();
|
||||
for name in ["java-usages-123-789.tmp", "java-usages-custom.jar", "other.jar", "java-usages-not-ours.tmp"] {
|
||||
std::fs::write(dir.path().join(name), b"keep").unwrap();
|
||||
}
|
||||
let jar = super::usages_bundle(dir.path()).unwrap();
|
||||
assert!(jar.exists());
|
||||
assert!(!old.exists(), "reuse={reuse}");
|
||||
assert!(!stale.exists(), "reuse={reuse}");
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 5);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_the_exact_bundle_and_reuses_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let jar = super::usages_bundle(dir.path()).unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read(&jar).unwrap(),
|
||||
include_bytes!("../../../plugins/java-usages/openidea-java-usages.jar")
|
||||
);
|
||||
assert_eq!(super::usages_bundle(dir.path()), Some(jar));
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
//! result is cached until the manifests (or the relevant settings) change.
|
||||
//!
|
||||
//! Archives are listed as browsable roots (`<archive>!`, see `ide_vfs`): the
|
||||
//! JDK's `src.zip` and the Maven / Gradle dependency jars (sources jars preferred).
|
||||
//! JDK's `src.zip` and the Maven / Gradle dependency jars (source attachments resolved by JDT).
|
||||
|
||||
use crate::exe;
|
||||
use crate::exec::{query, query_in, which};
|
||||
@@ -248,7 +248,7 @@ fn gradle_user_home() -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
/// One `Maven: g:a:v` / `Gradle: g:a:v` group per dependency whose jar is in a
|
||||
/// local repository, its root being the jar (the `-sources.jar` when downloaded).
|
||||
/// local repository, its root being the binary jar so Java classes open through JDT's source provider.
|
||||
pub(crate) fn dependency_libraries(
|
||||
deps: &[BuildDependency],
|
||||
maven_repo: Option<&Path>,
|
||||
@@ -286,7 +286,7 @@ pub(crate) fn maven_jar(repo: &Path, d: &BuildDependency) -> Option<PathBuf> {
|
||||
return None;
|
||||
}
|
||||
let dir = repo.join(d.group.replace('.', "/")).join(&d.artifact).join(&d.version);
|
||||
["-sources.jar", ".jar"]
|
||||
[".jar", "-sources.jar"]
|
||||
.iter()
|
||||
.map(|suffix| dir.join(format!("{}-{}{suffix}", d.artifact, d.version)))
|
||||
.find(|p| p.is_file())
|
||||
@@ -300,7 +300,7 @@ pub(crate) fn gradle_jar(home: &Path, d: &BuildDependency) -> Option<PathBuf> {
|
||||
let dir = home.join("caches/modules-2/files-2.1").join(&d.group).join(&d.artifact).join(&d.version);
|
||||
let mut hashes: Vec<PathBuf> = std::fs::read_dir(dir).ok()?.flatten().map(|e| e.path()).collect();
|
||||
hashes.sort();
|
||||
["-sources.jar", ".jar"].iter().find_map(|suffix| {
|
||||
[".jar", "-sources.jar"].iter().find_map(|suffix| {
|
||||
let file = format!("{}-{}{suffix}", d.artifact, d.version);
|
||||
hashes.iter().map(|h| h.join(&file)).find(|p| p.is_file())
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Lombok for jdtls: ECJ only generates Lombok members when the language
|
||||
//! server's JVM runs `-javaagent:lombok.jar`, so a project using Lombok gets the
|
||||
//! newest jar available, managed (installed by the IDE) or in the Maven / Gradle caches.
|
||||
//! app-provided jar, or falls back to the newest release in the Maven / Gradle caches.
|
||||
|
||||
use crate::home_dir;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -18,7 +18,7 @@ pub enum LombokAgent {
|
||||
Missing,
|
||||
Found {
|
||||
jar: PathBuf,
|
||||
/// `None` for the managed jar (the latest release when installed).
|
||||
/// `None` for the app-provided jar (its version is shown by the tool registry).
|
||||
version: Option<String>,
|
||||
},
|
||||
}
|
||||
@@ -64,7 +64,7 @@ pub fn agent_in_args<'a>(args: impl IntoIterator<Item = &'a str>) -> Option<Path
|
||||
}
|
||||
|
||||
/// The Lombok agent for the project at `root`: the user's own (`own`, from the JVM
|
||||
/// options) wins, then `managed` (the IDE-installed jar, always attached: it is inert
|
||||
/// options) wins, then `managed` (the app-provided jar, always attached: it is inert
|
||||
/// without Lombok on the classpath), then, for a project using Lombok, the build caches
|
||||
/// (`maven_repo`, the configured Maven local repository, else the default one).
|
||||
pub fn lombok_agent(
|
||||
@@ -499,6 +499,23 @@ mod tests {
|
||||
assert_eq!(managed.problem(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_patched_agent_wins_over_project_caches_but_respects_explicit_overrides() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
fs::write(tmp.path().join("pom.xml"), LOMBOK_DEP).unwrap();
|
||||
let repo = tmp.path().join("m2");
|
||||
let cache = repo.join("org/projectlombok/lombok/1.18.48");
|
||||
fs::create_dir_all(&cache).unwrap();
|
||||
fs::write(cache.join("lombok-1.18.48.jar"), b"official agent").unwrap();
|
||||
let patched = PathBuf::from("/managed/lombok-1.18.48-openidea.1.jar");
|
||||
let selected = lombok_agent(tmp.path(), None, Some(patched.clone()), Some(repo.clone()));
|
||||
assert_eq!(selected.jar(), Some(patched.as_path()));
|
||||
assert_eq!(selected.problem(), None);
|
||||
let own = PathBuf::from("/custom/lombok.jar");
|
||||
let selected = lombok_agent(tmp.path(), Some(own.clone()), Some(patched), Some(repo));
|
||||
assert_eq!(selected.jar(), Some(own.as_path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_the_newest_cached_release() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -319,14 +319,40 @@ fn terminal_activation_for_project_venv() {
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut s = Settings::default();
|
||||
assert_eq!(terminal_activation(tmp.path(), &s, Some("/bin/zsh")), None);
|
||||
assert_eq!(terminal_activation(tmp.path(), &s, "/bin/zsh"), None);
|
||||
fake_venv(tmp.path(), ".venv");
|
||||
let line = terminal_activation(tmp.path(), &s, Some("/bin/zsh")).unwrap();
|
||||
let line = terminal_activation(tmp.path(), &s, "/bin/zsh").unwrap();
|
||||
assert!(line.starts_with("source '") && line.ends_with("/activate'"), "{line}");
|
||||
assert_eq!(terminal_activation(tmp.path(), &s, Some("/usr/bin/fish")), None, "no activate.fish");
|
||||
assert_eq!(terminal_activation(tmp.path(), &s, Some("docker")), None, "not a shell");
|
||||
assert_eq!(terminal_activation(tmp.path(), &s, "/usr/bin/fish"), None, "no activate.fish");
|
||||
assert_eq!(terminal_activation(tmp.path(), &s, "docker"), None, "not a shell");
|
||||
s.languages.python.activate_virtualenv = false;
|
||||
assert_eq!(terminal_activation(tmp.path(), &s, Some("/bin/zsh")), None);
|
||||
assert_eq!(terminal_activation(tmp.path(), &s, "/bin/zsh"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_activation_for_windows_shell_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut s = Settings::default();
|
||||
s.languages.python.interpreter = fake_venv(tmp.path(), ".venv with spaces 'quoted'").to_string_lossy().into_owned();
|
||||
let bin = tmp.path().join(".venv with spaces 'quoted'").join(bin_dir());
|
||||
for (shell, script, powershell) in [
|
||||
(r"C:\Program Files\PowerShell\7\pwsh.exe", "Activate.ps1", true),
|
||||
(r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe", "Activate.ps1", true),
|
||||
(r"C:\Windows\System32\cmd.exe", "activate.bat", false),
|
||||
] {
|
||||
assert_eq!(terminal_activation(tmp.path(), &s, shell), None, "missing {script}");
|
||||
let path = bin.join(script);
|
||||
std::fs::write(&path, "").unwrap();
|
||||
let expected = if powershell {
|
||||
format!("& '{}'", path.to_string_lossy().replace('\'', "''"))
|
||||
} else {
|
||||
format!("\"{}\"", path.display())
|
||||
};
|
||||
assert_eq!(terminal_activation(tmp.path(), &s, shell), Some(expected), "{shell}");
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
assert_eq!(terminal_activation(tmp.path(), &s, ""), None);
|
||||
assert_eq!(terminal_activation(tmp.path(), &s, " "), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -514,12 +540,12 @@ fn build_dependencies_resolve_to_local_jars() {
|
||||
std::fs::write(&p, "").unwrap();
|
||||
p
|
||||
};
|
||||
touch(m2.join("com/google/guava/guava/33.0/guava-33.0.jar"));
|
||||
let guava_src = touch(m2.join("com/google/guava/guava/33.0/guava-33.0-sources.jar"));
|
||||
let guava = touch(m2.join("com/google/guava/guava/33.0/guava-33.0.jar"));
|
||||
touch(m2.join("com/google/guava/guava/33.0/guava-33.0-sources.jar"));
|
||||
let junit = touch(m2.join("junit/junit/4.13/junit-4.13.jar"));
|
||||
let files = gradle.join("caches/modules-2/files-2.1/org.slf4j/slf4j-api/2.0.9");
|
||||
touch(files.join("a1b2/slf4j-api-2.0.9.jar"));
|
||||
let slf4j_src = touch(files.join("c3d4/slf4j-api-2.0.9-sources.jar"));
|
||||
let slf4j = touch(files.join("a1b2/slf4j-api-2.0.9.jar"));
|
||||
touch(files.join("c3d4/slf4j-api-2.0.9-sources.jar"));
|
||||
let dep = |gradle: bool, g: &str, a: &str, v: &str| BuildDependency {
|
||||
gradle,
|
||||
group: g.into(),
|
||||
@@ -540,14 +566,14 @@ fn build_dependencies_resolve_to_local_jars() {
|
||||
assert_eq!(
|
||||
shown,
|
||||
[
|
||||
("Maven: com.google.guava:guava:33.0", "maven", "guava-33.0-sources.jar"),
|
||||
("Maven: com.google.guava:guava:33.0", "maven", "guava-33.0.jar"),
|
||||
("Maven: junit:junit:4.13", "maven", "junit-4.13.jar"),
|
||||
("Gradle: org.slf4j:slf4j-api:2.0.9", "gradle", "slf4j-api-2.0.9-sources.jar"),
|
||||
("Gradle: org.slf4j:slf4j-api:2.0.9", "gradle", "slf4j-api-2.0.9.jar"),
|
||||
]
|
||||
);
|
||||
assert_eq!(groups[0].roots[0].path, ide_core::IpcPath::from(ide_vfs::archive_root(&guava_src)));
|
||||
assert_eq!(groups[0].roots[0].path, ide_core::IpcPath::from(ide_vfs::archive_root(&guava)));
|
||||
assert_eq!(groups[1].roots[0].path, ide_core::IpcPath::from(ide_vfs::archive_root(&junit)));
|
||||
assert_eq!(groups[2].roots[0].path, ide_core::IpcPath::from(ide_vfs::archive_root(&slf4j_src)));
|
||||
assert_eq!(groups[2].roots[0].path, ide_core::IpcPath::from(ide_vfs::archive_root(&slf4j)));
|
||||
// A Gradle build also finds jars installed in the Maven local repository (`mavenLocal()`).
|
||||
let groups = dependency_libraries(&[dep(true, "junit", "junit", "4.13")], Some(&m2), Some(&gradle));
|
||||
assert_eq!(groups[0].name, "Gradle: junit:junit:4.13");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Filesystem operations shared by deployment and remote development bootstrap.
|
||||
use crate::sftp::{RemoteEntry, SftpFs};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use russh_sftp::client::SftpSession;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -115,6 +115,50 @@ impl RemoteFs {
|
||||
}
|
||||
}
|
||||
|
||||
/// Exclusive creation keeps imports from overwriting a concurrent copy.
|
||||
pub async fn upload_new(&self, local: &Path, remote: &str, cancel: &CancellationToken) -> IdeResult<()> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match self {
|
||||
Self::Sftp(fs) => fs.upload_new(local, remote, cancel).await,
|
||||
Self::Local => {
|
||||
let mut input = tokio::fs::File::open(local).await?;
|
||||
let mut output = tokio::fs::OpenOptions::new().write(true).create_new(true).open(remote).await?;
|
||||
let result = async {
|
||||
copy_stream(&mut input, &mut output, cancel).await?;
|
||||
#[cfg(unix)]
|
||||
output.set_permissions(input.metadata().await?.permissions()).await?;
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
drop(output);
|
||||
if result.is_err() {
|
||||
let _ = tokio::fs::remove_file(remote).await;
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates the link itself, preserving a relative or dangling target.
|
||||
pub async fn symlink(&self, target: &str, link: &str) -> IdeResult<()> {
|
||||
match self {
|
||||
Self::Sftp(fs) => fs.symlink(target, link).await,
|
||||
#[cfg(unix)]
|
||||
Self::Local => Ok(tokio::fs::symlink(target, link).await?),
|
||||
#[cfg(not(unix))]
|
||||
Self::Local => Err(IdeError::invalid("Cannot create a symbolic link on this client")),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_dir(&self, path: &str) -> IdeResult<()> {
|
||||
match self {
|
||||
Self::Sftp(fs) => fs.create_dir(path).await,
|
||||
Self::Local => Ok(tokio::fs::create_dir(path).await?),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn download(&self, remote: &str, local: &Path) -> IdeResult<()> {
|
||||
match self {
|
||||
Self::Sftp(fs) => fs.download(remote, local).await,
|
||||
@@ -199,6 +243,28 @@ impl RemoteFs {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn copy_stream(
|
||||
input: &mut (impl tokio::io::AsyncRead + Unpin),
|
||||
output: &mut (impl tokio::io::AsyncWrite + Unpin),
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<()> {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => Err(IdeError::cancelled()),
|
||||
result = async {
|
||||
let mut buf = vec![0; 64 * 1024];
|
||||
loop {
|
||||
let len = input.read(&mut buf).await?;
|
||||
if len == 0 { break; }
|
||||
output.write_all(&buf[..len]).await?;
|
||||
}
|
||||
output.flush().await?;
|
||||
Ok(())
|
||||
} => result,
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies without holding the file in memory: deployments can include large archives.
|
||||
async fn copy_file(from: &Path, to: &Path) -> IdeResult<()> {
|
||||
if let Some(parent) = to.parent() {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
//! Remote files over SFTP. Remote paths are POSIX strings.
|
||||
|
||||
use ide_core::{IdeError, IdeResult, error::ErrorKind};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use russh_sftp::client::SftpSession;
|
||||
use russh_sftp::client::error::Error as SftpError;
|
||||
use russh_sftp::protocol::{FileAttributes, StatusCode};
|
||||
use russh_sftp::protocol::{FileAttributes, OpenFlags, StatusCode};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::Path;
|
||||
@@ -168,6 +168,45 @@ impl SftpFs {
|
||||
self.write(remote, &data, mtime).await
|
||||
}
|
||||
|
||||
/// Imports a local file without replacing an existing remote entry.
|
||||
pub async fn upload_new(&self, local: &Path, remote: &str, cancel: &CancellationToken) -> IdeResult<()> {
|
||||
let mut input = tokio::fs::File::open(local).await?;
|
||||
let mut output = self
|
||||
.sftp
|
||||
.open_with_flags(remote, OpenFlags::WRITE | OpenFlags::CREATE | OpenFlags::EXCLUDE)
|
||||
.await
|
||||
.map_err(|e| err(remote, e))?;
|
||||
let result = crate::filesystem::copy_stream(&mut input, &mut output, cancel).await;
|
||||
let closed = output.shutdown().await.map_err(IdeError::from);
|
||||
drop(output);
|
||||
let result = async {
|
||||
result.and(closed)?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = input.metadata().await?.permissions().mode() & 0o7777;
|
||||
self.sftp
|
||||
.set_metadata(remote, FileAttributes { permissions: Some(mode), ..FileAttributes::empty() })
|
||||
.await
|
||||
.map_err(|e| err(remote, e))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
if result.is_err() {
|
||||
let _ = self.sftp.remove_file(remote).await;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn symlink(&self, target: &str, link: &str) -> IdeResult<()> {
|
||||
self.sftp.symlink(target, link).await.map_err(|e| err(link, e))
|
||||
}
|
||||
|
||||
pub async fn create_dir(&self, path: &str) -> IdeResult<()> {
|
||||
self.sftp.create_dir(path).await.map_err(|e| err(path, e))
|
||||
}
|
||||
|
||||
pub async fn download(&self, remote: &str, local: &Path) -> IdeResult<()> {
|
||||
let data = self.read(remote).await?;
|
||||
if let Some(dir) = local.parent() {
|
||||
|
||||
@@ -164,6 +164,7 @@ impl russh_sftp::server::Handler for Sftp {
|
||||
.read(pflags.contains(OpenFlags::READ))
|
||||
.write(pflags.contains(OpenFlags::WRITE))
|
||||
.create(pflags.contains(OpenFlags::CREATE))
|
||||
.create_new(pflags.contains(OpenFlags::EXCLUDE))
|
||||
.truncate(pflags.contains(OpenFlags::TRUNCATE))
|
||||
.open(path)
|
||||
.map_err(code)?;
|
||||
@@ -213,6 +214,11 @@ impl russh_sftp::server::Handler for Sftp {
|
||||
}
|
||||
|
||||
async fn setstat(&mut self, id: u32, path: String, attrs: FileAttributes) -> Result<Status, Self::Error> {
|
||||
#[cfg(unix)]
|
||||
if let Some(mode) = attrs.permissions {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(self.local(&path), std::fs::Permissions::from_mode(mode)).map_err(code)?;
|
||||
}
|
||||
if let Some(t) = attrs.mtime {
|
||||
let time = std::time::UNIX_EPOCH + std::time::Duration::from_secs(t.into());
|
||||
let f = std::fs::File::options().write(true).open(self.local(&path)).map_err(code)?;
|
||||
@@ -255,6 +261,12 @@ impl russh_sftp::server::Handler for Sftp {
|
||||
Ok(ok(id))
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn symlink(&mut self, id: u32, target: String, link: String) -> Result<Status, Self::Error> {
|
||||
std::os::unix::fs::symlink(target, self.local(&link)).map_err(code)?;
|
||||
Ok(ok(id))
|
||||
}
|
||||
|
||||
async fn rename(&mut self, id: u32, oldpath: String, newpath: String) -> Result<Status, Self::Error> {
|
||||
std::fs::rename(self.local(&oldpath), self.local(&newpath)).map_err(code)?;
|
||||
Ok(ok(id))
|
||||
|
||||
@@ -497,7 +497,7 @@ pub fn available_shells() -> Vec<String> {
|
||||
|
||||
/// Picks the shell binary and its arguments. A default (or explicitly chosen but
|
||||
/// argument-less) POSIX shell is started as a login shell, like Terminal.app/IDEA.
|
||||
fn resolve_shell(shell: Option<&str>, args: &[String]) -> (String, Vec<String>) {
|
||||
pub fn resolve_shell(shell: Option<&str>, args: &[String]) -> (String, Vec<String>) {
|
||||
let shell = shell.map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).unwrap_or_else(default_shell);
|
||||
if !args.is_empty() {
|
||||
return (shell, args.to_vec());
|
||||
@@ -808,8 +808,12 @@ mod tests {
|
||||
assert_eq!((shell.as_str(), args), ("/bin/zsh", vec!["-l".to_owned()]));
|
||||
let (_, args) = resolve_shell(Some("/usr/bin/python3"), &[]);
|
||||
assert!(args.is_empty());
|
||||
let (_, args) = resolve_shell(None, &[]);
|
||||
assert_eq!(args, vec!["-l".to_owned()]);
|
||||
for configured in [None, Some(""), Some(" \t ")] {
|
||||
let (shell, args) = resolve_shell(configured, &[]);
|
||||
assert_eq!(shell, default_shell_path());
|
||||
assert_eq!(args, vec!["-l".to_owned()]);
|
||||
}
|
||||
assert_eq!(resolve_shell(Some(" /bin/bash "), &["-i".into()]), ("/bin/bash".into(), vec!["-i".into()]));
|
||||
assert_eq!(shell_title("C:\\Program Files\\PowerShell\\7\\pwsh.exe"), "pwsh");
|
||||
let env = terminal_env(&BTreeMap::from([("TERM".into(), "dumb".into())]));
|
||||
assert_eq!(env["TERM"], "dumb");
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
//! Versioned app-owned plugin jars, shared by tool detection and language-server launches.
|
||||
|
||||
use crate::{Method, ToolSpec};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) fn install(root: &Path, spec: &ToolSpec) -> std::io::Result<PathBuf> {
|
||||
let Method::Bundled { filename, bytes, .. } = spec.method else { unreachable!("bundled tool") };
|
||||
let dir = root.join(spec.name).join("bin");
|
||||
// The agent path participates in the JDT LS workspace key: upgrades must
|
||||
// discard incremental state compiled with the previous agent.
|
||||
let path = dir.join(filename);
|
||||
if std::fs::read(&path).is_ok_and(|old| old == bytes) {
|
||||
return Ok(path);
|
||||
}
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos();
|
||||
let temporary = dir.join(format!(".{filename}-{}-{nonce}.tmp", std::process::id()));
|
||||
let result = std::fs::write(&temporary, bytes).and_then(|_| std::fs::rename(&temporary, &path));
|
||||
if let Err(error) = result {
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
// Another window may have installed the same bytes concurrently.
|
||||
if !std::fs::read(&path).is_ok_and(|old| old == bytes) {
|
||||
tracing::warn!(tool = spec.name, %error, "Bundled plugin unavailable");
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
//! [`tools_bin_dirs`] on the process `PATH` at startup.
|
||||
|
||||
pub mod archive;
|
||||
mod bundled;
|
||||
pub mod jdk;
|
||||
pub mod platform;
|
||||
mod process;
|
||||
@@ -146,7 +147,7 @@ fn managed_bin_dir(root: &Path, spec: &ToolSpec, platform: Platform) -> Option<P
|
||||
Method::PipVenv { .. } => {
|
||||
Some(root.join(spec.name).join("venv").join(if platform.os == Os::Windows { "Scripts" } else { "bin" }))
|
||||
}
|
||||
Method::Rustup { .. } | Method::PipUser { .. } | Method::PipTarget { .. } => None,
|
||||
Method::Bundled { .. } | Method::Rustup { .. } | Method::PipUser { .. } | Method::PipTarget { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -389,9 +390,12 @@ fn is_bundle(command: &str) -> bool {
|
||||
command.ends_with(".jar")
|
||||
}
|
||||
|
||||
/// Path of an installed plugin bundle (`<tools>/<name>/bin/<jar>`), if present.
|
||||
/// Path of an app-provided or installed plugin jar. Embedded jars are materialized on demand.
|
||||
pub fn managed_bundle(app_data: &Path, name: &str) -> Option<PathBuf> {
|
||||
let spec = registry::find(name)?;
|
||||
if matches!(spec.method, Method::Bundled { .. }) {
|
||||
return bundled::install(&tools_dir(app_data), spec).ok();
|
||||
}
|
||||
let jar = spec.commands.first().filter(|c| is_bundle(c))?;
|
||||
let path = tools_dir(app_data).join(spec.name).join("bin").join(jar);
|
||||
path.is_file().then_some(path)
|
||||
@@ -542,6 +546,7 @@ impl Tools {
|
||||
fn method_missing(&self, method: Method) -> Option<String> {
|
||||
let need = |ok: bool, msg: &str| (!ok).then(|| msg.to_string());
|
||||
match method {
|
||||
Method::Bundled { .. } => None,
|
||||
Method::Rustup { .. } => need(self.which("rustup").is_some(), "rustup is required (https://rustup.rs)"),
|
||||
Method::Npm { .. } => need(
|
||||
self.which_any(&["npm", "pnpm"]).is_some(),
|
||||
@@ -604,7 +609,8 @@ impl Tools {
|
||||
};
|
||||
let (status, path, version) = self.detect(spec);
|
||||
let unavailable_reason = self.unavailable_reason(spec);
|
||||
let can_uninstall = status == ToolStatus::Installed;
|
||||
let bundled = matches!(spec.method, Method::Bundled { .. });
|
||||
let can_uninstall = status == ToolStatus::Installed && !bundled;
|
||||
Some(ToolInfo {
|
||||
name: spec.name.to_string(),
|
||||
display_name: spec.display.to_string(),
|
||||
@@ -615,7 +621,7 @@ impl Tools {
|
||||
path: path.map(Into::into),
|
||||
version,
|
||||
install_method: Some(self.install_method(spec).label().to_string()),
|
||||
can_install: unavailable_reason.is_none(),
|
||||
can_install: unavailable_reason.is_none() && !bundled,
|
||||
unavailable_reason,
|
||||
can_uninstall,
|
||||
install_hint,
|
||||
@@ -654,6 +660,12 @@ impl Tools {
|
||||
}
|
||||
|
||||
fn detect(&self, spec: &ToolSpec) -> (ToolStatus, Option<PathBuf>, Option<String>) {
|
||||
if let Method::Bundled { version, .. } = spec.method {
|
||||
return match bundled::install(&self.root, spec) {
|
||||
Ok(path) => (ToolStatus::Installed, Some(path), Some(version.to_owned())),
|
||||
Err(_) => (ToolStatus::Missing, None, None),
|
||||
};
|
||||
}
|
||||
let main = spec.commands[0];
|
||||
let managed = managed_bin_dir(&self.root, spec, self.platform).and_then(|d| self.exe_in(&d, main));
|
||||
if let Some(path) = managed {
|
||||
@@ -782,6 +794,9 @@ impl Tools {
|
||||
let method = self.install_method(spec);
|
||||
emit(InstallEvent::Line { text: format!("Installing {} via {}…", spec.display, method.label()) });
|
||||
match method {
|
||||
Method::Bundled { .. } => {
|
||||
bundled::install(&self.root, spec)?;
|
||||
}
|
||||
Method::Rustup { component } => {
|
||||
let mut c = self.command(self.which("rustup").expect("checked"));
|
||||
c.args(["component", "add", component]);
|
||||
@@ -1188,6 +1203,8 @@ impl Tools {
|
||||
let cancel = CancellationToken::new();
|
||||
let quiet = |_: InstallEvent| {};
|
||||
match self.install_method(spec) {
|
||||
// App-owned resources remain available for every project/window.
|
||||
Method::Bundled { .. } => {}
|
||||
Method::Rustup { component } => {
|
||||
let rustup = self.which("rustup").ok_or_else(|| IdeError::unavailable("rustup not found"))?;
|
||||
let mut c = self.command(rustup);
|
||||
|
||||
@@ -31,6 +31,8 @@ pub enum ReleaseSource {
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Method {
|
||||
/// An app-owned plugin jar, materialized without a network download.
|
||||
Bundled { filename: &'static str, version: &'static str, bytes: &'static [u8] },
|
||||
/// `rustup component add <component>`.
|
||||
Rustup { component: &'static str },
|
||||
/// npm / pnpm packages installed into `<tools>/node_modules`; the first is the primary one.
|
||||
@@ -56,6 +58,7 @@ pub enum Method {
|
||||
impl Method {
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
Method::Bundled { .. } => "Bundled",
|
||||
Method::Rustup { .. } => "rustup",
|
||||
Method::Npm { .. } => "npm",
|
||||
Method::Go { .. } => "go install",
|
||||
@@ -578,15 +581,13 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
display: "Lombok (jdtls agent)",
|
||||
kind: Plugin,
|
||||
commands: &["lombok.jar"],
|
||||
// Newer than the Lombok a project pins: old ones fail inside current ECJ.
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::MavenCentral { group: "org.projectlombok", artifact: "lombok" },
|
||||
assets: &[
|
||||
any_arch(Mac, "lombok-*.jar"),
|
||||
any_arch(Linux, "lombok-*.jar"),
|
||||
any_arch(Windows, "lombok-*.jar"),
|
||||
],
|
||||
locate: &["lombok.jar"],
|
||||
// Equinox removed getModuleClassLoader(boolean), breaking lombok.config lookup.
|
||||
// Return to Maven Central once an official release includes lombok#4059.
|
||||
// Source commit, build instructions and checksum: plugins/lombok/README.md.
|
||||
method: Method::Bundled {
|
||||
filename: "lombok-1.18.48-openidea.1.jar",
|
||||
version: "1.18.48-openidea.1",
|
||||
bytes: include_bytes!("../../../plugins/lombok/lombok-1.18.48-openidea.1.jar"),
|
||||
},
|
||||
fallback: None,
|
||||
version: V,
|
||||
|
||||
@@ -434,7 +434,6 @@ mod tests {
|
||||
assert_eq!(d.version, "1.18.48");
|
||||
assert_eq!(d.name, "lombok-1.18.48.jar");
|
||||
assert_eq!(d.url, "https://repo1.maven.org/maven2/org/projectlombok/lombok/1.18.48/lombok-1.18.48.jar");
|
||||
assert!(select_asset(&[d.name.as_str()], find("lombok").unwrap().asset_rules(), LINUX).is_some());
|
||||
assert!(maven_pick("g", "a", "<metadata/>").is_err());
|
||||
assert!(maven_pick("g", "a", "<release>../x</release>").is_err());
|
||||
}
|
||||
|
||||
@@ -43,6 +43,61 @@ fn find<'a>(list: &'a [ToolInfo], name: &str) -> &'a ToolInfo {
|
||||
list.iter().find(|t| t.name == name).unwrap_or_else(|| panic!("{name} not listed"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundled_lombok_replaces_legacy_installs_on_every_platform_without_downloads() {
|
||||
for os in [Os::Mac, Os::Linux, Os::Windows] {
|
||||
for arch in [platform::Arch::Arm64, platform::Arch::X64] {
|
||||
let env = Env::new();
|
||||
let legacy = env.root.join("lombok/bin/lombok.jar");
|
||||
fs::create_dir_all(legacy.parent().unwrap()).unwrap();
|
||||
fs::write(&legacy, b"old official agent").unwrap();
|
||||
fs::write(env.root.join("lombok").join(MANIFEST), r#"{"version":"1.18.48"}"#).unwrap();
|
||||
let tools = Tools::with_paths(env.root.clone(), OsString::new(), Platform { os, arch });
|
||||
let info = tools.info("lombok", &[]).unwrap();
|
||||
let path = managed_bundle(env.root.parent().unwrap(), "lombok").unwrap();
|
||||
assert_eq!(info.status, ToolStatus::Installed);
|
||||
assert_eq!(info.version.as_deref(), Some("1.18.48-openidea.1"));
|
||||
assert_eq!(info.path, Some(path.clone().into()));
|
||||
assert_eq!(path.file_name().unwrap(), "lombok-1.18.48-openidea.1.jar");
|
||||
assert!(!info.can_install && !info.can_uninstall);
|
||||
assert_eq!(tools.unavailable_reason(registry::find("lombok").unwrap()), None);
|
||||
assert_eq!(fs::read(&legacy).unwrap(), b"old official agent", "other windows may still use it");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundled_lombok_is_available_offline_and_repairs_missing_or_corrupt_files() {
|
||||
let env = Env::new();
|
||||
let data = env.root.parent().unwrap();
|
||||
let agent = managed_bundle(data, "lombok").unwrap();
|
||||
let checksum = include_str!("../../../plugins/lombok/SHA256SUMS").split_whitespace().next().unwrap();
|
||||
assert_eq!(sources::sha256_file(&agent).unwrap(), checksum);
|
||||
for contents in [None, Some(b"incomplete jar".as_slice())] {
|
||||
if let Some(contents) = contents {
|
||||
fs::write(&agent, contents).unwrap();
|
||||
} else {
|
||||
fs::remove_file(&agent).unwrap();
|
||||
}
|
||||
assert_eq!(managed_bundle(data, "lombok"), Some(agent.clone()));
|
||||
assert_eq!(sources::sha256_file(&agent).unwrap(), checksum);
|
||||
}
|
||||
assert_eq!(fs::read_dir(agent.parent().unwrap()).unwrap().count(), 1, "no temporary jars left behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_windows_get_the_same_complete_bundled_lombok() {
|
||||
let env = Env::new();
|
||||
let data = env.root.parent().unwrap();
|
||||
std::thread::scope(|scope| {
|
||||
let windows: Vec<_> = (0..8).map(|_| scope.spawn(|| managed_bundle(data, "lombok").unwrap())).collect();
|
||||
let paths: Vec<_> = windows.into_iter().map(|window| window.join().unwrap()).collect();
|
||||
assert!(paths.iter().all(|path| path == &paths[0]));
|
||||
let checksum = include_str!("../../../plugins/lombok/SHA256SUMS").split_whitespace().next().unwrap();
|
||||
assert_eq!(sources::sha256_file(&paths[0]).unwrap(), checksum);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_parsing() {
|
||||
assert_eq!(parse_version("rust-analyzer 1.85.0 (4d91de4e 2025-02-17)").as_deref(), Some("1.85.0"));
|
||||
|
||||
@@ -348,6 +348,55 @@ fn run_raw_env_once(
|
||||
Ok(Output { stdout: out.stdout, stderr: out.stderr, code: out.status.code() })
|
||||
}
|
||||
|
||||
/// Captures binary/NUL-delimited read output while allowing cancellation to kill git.
|
||||
pub(crate) fn run_cancellable(root: &Path, args: &[&str], cancel: &CancellationToken) -> IdeResult<Output> {
|
||||
let out = run_cancellable_raw(root, args, cancel)?;
|
||||
if out.code == Some(0) { Ok(out) } else { Err(failure(args, &out.stderr, &out.stdout, out.code)) }
|
||||
}
|
||||
|
||||
/// Cancellable capture preserving exit codes for commands with documented non-error states.
|
||||
pub(crate) fn run_cancellable_raw(root: &Path, args: &[&str], cancel: &CancellationToken) -> IdeResult<Output> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let mut cmd = command(root)?;
|
||||
cmd.args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
let mut session = CommandSession::start(&mut cmd);
|
||||
let mut child = cmd.spawn().map_err(spawn_error)?;
|
||||
let capture = |mut pipe: Box<dyn Read + Send>| {
|
||||
std::thread::spawn(move || {
|
||||
let mut bytes = Vec::new();
|
||||
pipe.read_to_end(&mut bytes).map(|_| bytes)
|
||||
})
|
||||
};
|
||||
let stdout = capture(Box::new(child.stdout.take().expect("piped stdout")));
|
||||
let stderr = capture(Box::new(child.stderr.take().expect("piped stderr")));
|
||||
let status = loop {
|
||||
if cancel.is_cancelled() {
|
||||
kill(&mut child);
|
||||
let _ = child.wait();
|
||||
let _ = stdout.join();
|
||||
let _ = stderr.join();
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
let join = |thread: std::thread::JoinHandle<std::io::Result<Vec<u8>>>| {
|
||||
thread.join().map_err(|_| IdeError::internal("git output reader panicked"))?.map_err(IdeError::from)
|
||||
};
|
||||
let out = Output { stdout: join(stdout)?, stderr: join(stderr)?, code: status.code() };
|
||||
session.finish(status.success(), &String::from_utf8_lossy(&out.stderr));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Runs git and maps a non-zero exit status to an error carrying git's message.
|
||||
pub(crate) fn run(root: &Path, args: &[&str], stdin: Option<&[u8]>) -> IdeResult<Output> {
|
||||
let out = run_raw(root, args, stdin)?;
|
||||
|
||||
@@ -0,0 +1,521 @@
|
||||
//! Selection-scoped revision → working-tree comparison over the existing root registry.
|
||||
use crate::{ChangeKind, Repos, cli, ops};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, IpcPath};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CompareScope {
|
||||
pub repositories: Vec<IpcPath>,
|
||||
/// Selected content outside registered repositories; workspace parents expand to their skipped children.
|
||||
pub skipped_paths: Vec<IpcPath>,
|
||||
pub single_file: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WorkingTreeChange {
|
||||
pub path: String,
|
||||
pub kind: ChangeKind,
|
||||
pub old_path: Option<String>,
|
||||
pub added: u32,
|
||||
pub removed: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RepositoryComparison {
|
||||
pub root: IpcPath,
|
||||
/// Resolved commit, so opening a diff later uses the same left side as the listing.
|
||||
pub revision: Option<String>,
|
||||
pub files: Vec<WorkingTreeChange>,
|
||||
pub error: Option<String>,
|
||||
/// The requested revision does not resolve to a commit in this repository.
|
||||
#[serde(default)]
|
||||
pub missing_revision: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CompareResult {
|
||||
pub repositories: Vec<RepositoryComparison>,
|
||||
pub skipped_paths: Vec<IpcPath>,
|
||||
}
|
||||
|
||||
fn normalized(path: &Path) -> PathBuf {
|
||||
dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
|
||||
}
|
||||
|
||||
fn comparison_children(path: &Path) -> Vec<PathBuf> {
|
||||
std::fs::read_dir(path)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter(|entry| entry.file_name() != ".git" && entry.file_name() != ".openidea")
|
||||
.map(|entry| entry.path())
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl Repos {
|
||||
pub fn compare_scope(&self, paths: &[PathBuf]) -> CompareScope {
|
||||
let paths: Vec<_> = paths.iter().map(|p| normalized(p)).collect();
|
||||
let repositories = self
|
||||
.all()
|
||||
.iter()
|
||||
.filter(|r| {
|
||||
let root = normalized(r.root());
|
||||
paths.iter().any(|p| {
|
||||
root.starts_with(p)
|
||||
|| self.at_root(p).or_else(|| self.for_path(p)).is_some_and(|owner| owner.root() == r.root())
|
||||
})
|
||||
})
|
||||
.map(|r| IpcPath(r.root().to_path_buf()))
|
||||
.collect();
|
||||
let mut skipped = std::collections::BTreeSet::new();
|
||||
for path in &paths {
|
||||
if self.at_root(path).or_else(|| self.for_path(path)).is_some() {
|
||||
continue;
|
||||
}
|
||||
if self.all().iter().any(|r| r.root().starts_with(path)) {
|
||||
for child in comparison_children(path) {
|
||||
if self.has_outside_content(&child) {
|
||||
skipped.insert(child);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
skipped.insert(path.clone());
|
||||
}
|
||||
}
|
||||
let skipped_paths = skipped
|
||||
.into_iter()
|
||||
.map(|mut path| {
|
||||
if path.is_dir() {
|
||||
path.push("");
|
||||
}
|
||||
IpcPath(path)
|
||||
})
|
||||
.collect();
|
||||
CompareScope { repositories, skipped_paths, single_file: paths.len() == 1 && !paths[0].is_dir() }
|
||||
}
|
||||
|
||||
fn has_outside_content(&self, path: &Path) -> bool {
|
||||
if self.at_root(path).or_else(|| self.for_path(path)).is_some() {
|
||||
return false;
|
||||
}
|
||||
!self.all().iter().any(|r| r.root().starts_with(path))
|
||||
|| comparison_children(path).iter().any(|child| self.has_outside_content(child))
|
||||
}
|
||||
|
||||
pub fn compare_paths(
|
||||
&self,
|
||||
paths: &[PathBuf],
|
||||
revision: &str,
|
||||
repositories: Option<&[PathBuf]>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<CompareResult> {
|
||||
if revision.trim().is_empty() || revision.starts_with('-') {
|
||||
return Err(IdeError::invalid("invalid revision"));
|
||||
}
|
||||
let scope = self.compare_scope(paths);
|
||||
let paths: Vec<_> = paths.iter().map(|p| normalized(p)).collect();
|
||||
let mut result = CompareResult { repositories: Vec::new(), skipped_paths: scope.skipped_paths };
|
||||
for root in scope.repositories {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if repositories.is_some_and(|roots| !roots.iter().any(|r| normalized(r) == normalized(&root.0))) {
|
||||
continue;
|
||||
}
|
||||
let repo = self.at_root(&root.0).expect("scope comes from registry");
|
||||
let _scope =
|
||||
crate::ExecutionScope::enter(repo.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let mut missing_revision = false;
|
||||
let mut compare = || -> IdeResult<(String, Vec<WorkingTreeChange>)> {
|
||||
// Worktree comparisons must not run repository-defined clean/process filters
|
||||
// in Restricted Mode. External diff and textconv are disabled below as well.
|
||||
let mut overrides = Vec::new();
|
||||
if !crate::execution_allowed() {
|
||||
let config = cli::run_cancellable(repo.root(), &["config", "--null", "--list"], cancel)?;
|
||||
for record in config.stdout_str().split('\0') {
|
||||
let key = record.split('\n').next().unwrap_or_default();
|
||||
if key.starts_with("filter.")
|
||||
&& (key.ends_with(".clean") || key.ends_with(".process") || key.ends_with(".required"))
|
||||
{
|
||||
overrides.push("-c".to_owned());
|
||||
overrides.push(format!("{key}={}", if key.ends_with(".required") { "false" } else { "" }));
|
||||
}
|
||||
}
|
||||
}
|
||||
let run = |args: &[&str]| {
|
||||
let mut full: Vec<&str> = overrides.iter().map(String::as_str).collect();
|
||||
full.extend_from_slice(args);
|
||||
cli::run_cancellable(repo.root(), &full, cancel)
|
||||
};
|
||||
// --quiet documents exit 1 for an unresolved revision; other failures keep their diagnostics.
|
||||
let resolve_args =
|
||||
["rev-parse", "--verify", "--quiet", "--end-of-options", &format!("{revision}^{{commit}}")];
|
||||
let resolved = cli::run_cancellable_raw(repo.root(), &resolve_args, cancel)?;
|
||||
if resolved.code != Some(0) {
|
||||
missing_revision = resolved.code == Some(1);
|
||||
return Err(cli::failure(&resolve_args, &resolved.stderr, &resolved.stdout, resolved.code));
|
||||
}
|
||||
let resolved = resolved.stdout_str().trim().to_owned();
|
||||
// Disable textconv/external diff; these are also safe in untrusted projects.
|
||||
let names =
|
||||
run(&["diff", "--name-status", "-z", "-M", "--no-ext-diff", "--no-textconv", &resolved, "--"])?;
|
||||
let stats = run(&[
|
||||
"diff",
|
||||
"--numstat",
|
||||
"-z",
|
||||
"--no-renames",
|
||||
"--no-ext-diff",
|
||||
"--no-textconv",
|
||||
&resolved,
|
||||
"--",
|
||||
])?;
|
||||
let stats: std::collections::HashMap<_, _> = ops::parse_numstat(&stats.stdout_str())
|
||||
.into_iter()
|
||||
.map(|(path, added, removed)| (path, (added, removed)))
|
||||
.collect();
|
||||
let mut files = Vec::new();
|
||||
let contains = |rel: &str| {
|
||||
let absolute = repo.root().join(rel);
|
||||
// Nested clones contribute their own files, never the enclosing repo's entries.
|
||||
let own = self.at_root(&absolute).or_else(|| self.for_path(&absolute));
|
||||
own.is_some_and(|r| r.root() == repo.root()) && paths.iter().any(|p| absolute.starts_with(p))
|
||||
};
|
||||
for mut file in ops::parse_name_status(&names.stdout_str()) {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let new_in = contains(&file.path);
|
||||
let old_in = file.old_path.as_deref().is_some_and(contains);
|
||||
if !new_in && !old_in {
|
||||
continue;
|
||||
}
|
||||
let original = file.path.clone();
|
||||
if file.old_path.is_some() && new_in != old_in {
|
||||
if old_in {
|
||||
file.path = file.old_path.take().unwrap();
|
||||
file.kind = ChangeKind::Deleted;
|
||||
} else {
|
||||
file.old_path = None;
|
||||
file.kind = ChangeKind::Added;
|
||||
}
|
||||
}
|
||||
let count = |path: &str| stats.get(path).copied().unwrap_or_default();
|
||||
let (added, removed) = match &file.old_path {
|
||||
Some(old) => (count(&original).0, count(old).1),
|
||||
None => count(&file.path),
|
||||
};
|
||||
files.push(WorkingTreeChange {
|
||||
path: file.path,
|
||||
kind: file.kind,
|
||||
old_path: file.old_path,
|
||||
added,
|
||||
removed,
|
||||
});
|
||||
}
|
||||
if files.iter().any(|f| f.kind == ChangeKind::Renamed) {
|
||||
let renamed =
|
||||
run(&["diff", "--numstat", "-z", "-M", "--no-ext-diff", "--no-textconv", &resolved, "--"])?;
|
||||
let indexes: std::collections::HashMap<_, _> = files
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, f)| f.kind == ChangeKind::Renamed)
|
||||
.map(|(index, f)| (f.path.clone(), index))
|
||||
.collect();
|
||||
let mut records =
|
||||
renamed.stdout_str().split('\0').map(str::to_owned).collect::<Vec<_>>().into_iter();
|
||||
while let Some(record) = records.next() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let fields: Vec<_> = record.splitn(3, '\t').collect();
|
||||
if fields.len() == 3 && fields[2].is_empty() {
|
||||
let _old = records.next();
|
||||
if let Some(path) = records.next()
|
||||
&& let Some(index) = indexes.get(&path)
|
||||
{
|
||||
let file = &mut files[*index];
|
||||
file.added = fields[0].parse().unwrap_or(0);
|
||||
file.removed = fields[1].parse().unwrap_or(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let untracked = run(&["ls-files", "--others", "--exclude-standard", "-z"])?;
|
||||
for path in untracked.stdout_str().split('\0').filter(|p| !p.is_empty() && contains(p)) {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let absolute = repo.root().join(path);
|
||||
// Match the existing diff viewer's large/binary-file policy without loading large files for counts.
|
||||
let added = if std::fs::metadata(&absolute).is_ok_and(|m| m.len() <= 10 * 1024 * 1024) {
|
||||
let bytes = std::fs::read(&absolute).unwrap_or_default();
|
||||
if bytes.contains(&0) {
|
||||
0
|
||||
} else {
|
||||
(bytes.iter().filter(|b| **b == b'\n').count()
|
||||
+ usize::from(!bytes.is_empty() && bytes.last() != Some(&b'\n')))
|
||||
as u32
|
||||
}
|
||||
} else {
|
||||
0
|
||||
};
|
||||
files.push(WorkingTreeChange {
|
||||
path: path.to_owned(),
|
||||
kind: ChangeKind::Untracked,
|
||||
old_path: None,
|
||||
added,
|
||||
removed: 0,
|
||||
});
|
||||
}
|
||||
files.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
Ok((resolved, files))
|
||||
};
|
||||
let comparison = match compare() {
|
||||
Ok((revision, files)) => {
|
||||
RepositoryComparison { root, revision: Some(revision), files, error: None, missing_revision: false }
|
||||
}
|
||||
Err(_) if cancel.is_cancelled() => return Err(IdeError::cancelled()),
|
||||
Err(e) => RepositoryComparison {
|
||||
root,
|
||||
revision: None,
|
||||
files: Vec::new(),
|
||||
error: (!missing_revision).then_some(e.message),
|
||||
missing_revision,
|
||||
},
|
||||
};
|
||||
result.repositories.push(comparison);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::process::Command;
|
||||
|
||||
fn git(root: &Path, args: &[&str]) {
|
||||
let output = Command::new("git").current_dir(root).args(args).output().unwrap();
|
||||
assert!(output.status.success(), "{args:?}: {}", String::from_utf8_lossy(&output.stderr));
|
||||
}
|
||||
|
||||
fn write(root: &Path, path: &str, text: &str) {
|
||||
let path = root.join(path);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
fn init(root: &Path, branch: &str) {
|
||||
std::fs::create_dir_all(root).unwrap();
|
||||
git(root, &["init", "-q", "-b", branch]);
|
||||
git(root, &["config", "user.name", "Test"]);
|
||||
git(root, &["config", "user.email", "[email protected]"]);
|
||||
write(root, "src/文件 name.txt", "old\n");
|
||||
write(root, "src/move.txt", "move\n");
|
||||
write(root, "other/stable.txt", "stable\n");
|
||||
git(root, &["add", "."]);
|
||||
git(root, &["commit", "-qm", "initial"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subtree_union_worktree_untracked_and_rename_boundaries() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = normalized(temp.path());
|
||||
init(&root, "main");
|
||||
git(&root, &["switch", "-qc", "feature"]);
|
||||
git(&root, &["mv", "src/move.txt", "other/moved.txt"]);
|
||||
git(&root, &["commit", "-qm", "move out"]);
|
||||
write(&root, "src/文件 name.txt", "old\nnew\n");
|
||||
write(&root, "src/untracked space 中文.txt", "new\nfile\n");
|
||||
write(&root, "other/stable.txt", "changed\n");
|
||||
let repos = Repos::discover(&root, &|_| false).unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let result = repos.compare_paths(&[root.join("src")], "main", None, &cancel).unwrap();
|
||||
assert_eq!(result.repositories.len(), 1);
|
||||
let files = &result.repositories[0].files;
|
||||
assert_eq!(files.len(), 3, "{files:?}");
|
||||
let moved = files.iter().find(|f| f.path == "src/move.txt").unwrap();
|
||||
assert_eq!(moved.kind, ChangeKind::Deleted);
|
||||
assert_eq!((moved.added, moved.removed), (0, 1));
|
||||
assert!(moved.old_path.is_none());
|
||||
let changed = files.iter().find(|f| f.path == "src/文件 name.txt").unwrap();
|
||||
assert_eq!((changed.added, changed.removed), (1, 0));
|
||||
let untracked = files.iter().find(|f| f.path == "src/untracked space 中文.txt").unwrap();
|
||||
assert_eq!((untracked.kind, untracked.added), (ChangeKind::Untracked, 2));
|
||||
let union = repos
|
||||
.compare_paths(&[root.join("src"), root.join("other"), root.join("src")], "main", None, &cancel)
|
||||
.unwrap();
|
||||
assert_eq!(union.repositories[0].files.len(), 4);
|
||||
let rename = union.repositories[0].files.iter().find(|f| f.path == "other/moved.txt").unwrap();
|
||||
assert_eq!(rename.kind, ChangeKind::Renamed);
|
||||
assert_eq!(rename.old_path.as_deref(), Some("src/move.txt"));
|
||||
assert_eq!((rename.added, rename.removed), (0, 0));
|
||||
let into = repos.compare_paths(&[root.join("other")], "main", None, &cancel).unwrap();
|
||||
assert_eq!(
|
||||
into.repositories[0].files.iter().find(|f| f.path == "other/moved.txt").unwrap().kind,
|
||||
ChangeKind::Added
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_roots_missing_revision_loose_paths_and_empty_results() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = normalized(temp.path());
|
||||
for name in ["client", "server", "admin"] {
|
||||
init(&root.join(name), if name == "admin" { "trunk" } else { "main" });
|
||||
}
|
||||
write(&root, "loose/readme.txt", "not git\n");
|
||||
write(&root.join("client"), "src/new.txt", "client\n");
|
||||
write(&root.join("server"), "src/文件 name.txt", "server\n");
|
||||
let repos = Repos::discover(&root, &|_| false).unwrap();
|
||||
let scope = repos.compare_scope(std::slice::from_ref(&root));
|
||||
assert_eq!(scope.repositories.len(), 3);
|
||||
assert_eq!(scope.skipped_paths, [IpcPath(root.join("loose"))]);
|
||||
assert!(!scope.single_file);
|
||||
assert!(repos.compare_scope(&[root.join("client/src/文件 name.txt")]).single_file);
|
||||
let cancel = CancellationToken::new();
|
||||
let result = repos.compare_paths(&[root.clone(), root.join("loose")], "main", None, &cancel).unwrap();
|
||||
assert_eq!(result.repositories.len(), 3);
|
||||
assert_eq!(result.repositories.iter().filter(|r| r.missing_revision).count(), 1);
|
||||
assert!(result.repositories[0].missing_revision, "admin lacks main");
|
||||
assert!(result.repositories[0].error.is_none());
|
||||
assert_eq!(result.repositories[1].files.len(), 1);
|
||||
assert_eq!(result.repositories[2].files.len(), 1);
|
||||
assert_eq!(result.skipped_paths, [IpcPath(root.join("loose"))]);
|
||||
let filtered =
|
||||
repos.compare_paths(std::slice::from_ref(&root), "main", Some(&[root.join("server")]), &cancel).unwrap();
|
||||
assert_eq!(filtered.repositories.len(), 1);
|
||||
assert_eq!(filtered.repositories[0].root.0, root.join("server"));
|
||||
let empty = repos.compare_paths(&[root.join("server/other")], "main", None, &cancel).unwrap();
|
||||
assert!(empty.repositories[0].files.is_empty());
|
||||
let loose = repos.compare_paths(&[root.join("loose")], "main", None, &cancel).unwrap();
|
||||
assert!(loose.repositories.is_empty());
|
||||
assert_eq!(loose.skipped_paths, [IpcPath(root.join("loose"))]);
|
||||
cancel.cancel();
|
||||
assert!(repos.compare_paths(&[root], "main", None, &cancel).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_repositories_are_not_reported_twice_and_binary_counts_are_zero() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = normalized(temp.path());
|
||||
init(&root, "main");
|
||||
init(&root.join("nested"), "main");
|
||||
write(&root.join("nested"), "src/new.txt", "nested\n");
|
||||
std::fs::write(root.join("src/image.bin"), [0, 1, 2]).unwrap();
|
||||
let repos = Repos::discover(&root, &|_| false).unwrap();
|
||||
let result = repos.compare_paths(std::slice::from_ref(&root), "main", None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(result.repositories.len(), 2);
|
||||
assert_eq!(result.repositories[0].files.len(), 1);
|
||||
assert_eq!(result.repositories[0].files[0].added, 0);
|
||||
assert_eq!(result.repositories[1].files.len(), 1);
|
||||
let nested = repos.compare_paths(&[root.join("nested")], "main", None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(nested.repositories.len(), 1);
|
||||
assert_eq!(nested.repositories.iter().map(|r| r.files.len()).sum::<usize>(), 1);
|
||||
}
|
||||
#[test]
|
||||
fn skipped_children_only_report_content_outside_repositories() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = normalized(temp.path());
|
||||
init(&root.join("services/server"), "main");
|
||||
init(&root.join("client"), "main");
|
||||
write(&root, ".openidea/state.json", "{}");
|
||||
write(&root, ".git/config", "ignored metadata");
|
||||
let repos = Repos::discover(&root, &|_| false).unwrap();
|
||||
assert!(repos.compare_scope(std::slice::from_ref(&root)).skipped_paths.is_empty());
|
||||
write(&root, "services/notes.txt", "loose nested content");
|
||||
write(&root, "loose/readme.txt", "loose");
|
||||
write(&root, "readme.txt", "loose file");
|
||||
let scope = repos.compare_scope(&[root.clone(), root.join("loose")]);
|
||||
assert_eq!(
|
||||
scope.skipped_paths,
|
||||
[IpcPath(root.join("loose")), IpcPath(root.join("readme.txt")), IpcPath(root.join("services")),]
|
||||
);
|
||||
assert!(scope.skipped_paths[0].0.to_string_lossy().ends_with(std::path::MAIN_SEPARATOR));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_revision_is_typed_and_other_errors_keep_only_the_message() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = normalized(temp.path());
|
||||
init(&root, "main");
|
||||
let repos = Repos::discover(&root, &|_| false).unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let result = repos.compare_paths(std::slice::from_ref(&root), "missing-revision", None, &cancel).unwrap();
|
||||
assert!(result.repositories[0].missing_revision);
|
||||
assert!(result.repositories[0].error.is_none());
|
||||
std::fs::write(root.join(".git/config"), "[broken").unwrap();
|
||||
let result = repos.compare_paths(&[root], "main", None, &cancel).unwrap();
|
||||
assert!(!result.repositories[0].missing_revision);
|
||||
let error = result.repositories[0].error.as_deref().unwrap();
|
||||
assert!(error.contains("bad config"), "{error}");
|
||||
assert!(!error.starts_with("Internal:"), "{error}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn untracked_read_and_metadata_failures_leave_files_with_zero_counts() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = normalized(temp.path());
|
||||
init(&root, "main");
|
||||
// Reading a directory fails after successful metadata; a dangling link fails metadata.
|
||||
symlink(root.join("src"), root.join("unreadable")).unwrap();
|
||||
symlink(root.join("vanished"), root.join("missing")).unwrap();
|
||||
write(&root, "new.txt", "still counted\n");
|
||||
let repos = Repos::discover(&root, &|_| false).unwrap();
|
||||
let result = repos.compare_paths(&[root], "main", None, &CancellationToken::new()).unwrap();
|
||||
let repo = &result.repositories[0];
|
||||
assert!(repo.error.is_none(), "{repo:?}");
|
||||
assert_eq!(repo.files.len(), 3);
|
||||
for name in ["unreadable", "missing"] {
|
||||
let file = repo.files.iter().find(|f| f.path == name).unwrap();
|
||||
assert_eq!((file.kind, file.added, file.removed), (ChangeKind::Untracked, 0, 0));
|
||||
}
|
||||
assert_eq!(repo.files.iter().find(|f| f.path == "new.txt").unwrap().added, 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn restricted_comparison_does_not_execute_repository_commands() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = normalized(temp.path());
|
||||
init(&root, "main");
|
||||
let script = root.join(".git/marker.sh");
|
||||
let marker = root.join(".git/executed");
|
||||
std::fs::write(&script, "#!/bin/sh\ntouch .git/executed\n").unwrap();
|
||||
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let script = script.to_str().unwrap();
|
||||
for key in [
|
||||
"core.fsmonitor",
|
||||
"filter.marker.clean",
|
||||
"filter.marker.process",
|
||||
"diff.marker.command",
|
||||
"diff.marker.textconv",
|
||||
] {
|
||||
git(&root, &["config", key, script]);
|
||||
}
|
||||
git(&root, &["config", "filter.marker.required", "true"]);
|
||||
write(&root, ".gitattributes", "*.txt filter=marker diff=marker\n");
|
||||
write(&root, "src/文件 name.txt", "changed\n");
|
||||
write(&root, "new.txt", "untracked\n");
|
||||
let repos = Repos::discover(&root, &|_| false).unwrap();
|
||||
for repo in repos.all() {
|
||||
repo.set_execution_allowed(false);
|
||||
}
|
||||
let result = repos.compare_paths(std::slice::from_ref(&root), "main", None, &CancellationToken::new()).unwrap();
|
||||
assert!(result.repositories[0].error.is_none(), "{result:?}");
|
||||
assert_eq!(result.repositories[0].files.len(), 3);
|
||||
assert!(!marker.exists(), "Restricted Mode executed a repository command");
|
||||
// Prove the fixture's fsmonitor hook is active when the shared wrapper is bypassed.
|
||||
git(&root, &["ls-files"]);
|
||||
assert!(marker.exists(), "control invocation did not run fsmonitor");
|
||||
}
|
||||
}
|
||||
@@ -453,6 +453,7 @@ pub struct ChangelistState {
|
||||
mod blame;
|
||||
pub mod changelists;
|
||||
mod cli;
|
||||
mod compare;
|
||||
mod diff;
|
||||
mod history;
|
||||
mod ignore;
|
||||
@@ -464,6 +465,7 @@ mod refs;
|
||||
mod remotes;
|
||||
mod repo;
|
||||
mod roots;
|
||||
pub use compare::{CompareResult, CompareScope, RepositoryComparison, WorkingTreeChange};
|
||||
pub mod shelf;
|
||||
mod status;
|
||||
pub use index_writes::is_own_index_write;
|
||||
|
||||
@@ -3,7 +3,7 @@ use encoding_rs::{Encoding, UTF_8, UTF_16BE, UTF_16LE};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::borrow::Cow;
|
||||
|
||||
/// File charset plus an optional reversible ASCII representation (for properties).
|
||||
/// File charset plus an optional ASCII representation (for properties).
|
||||
/// The host supplies conversion functions so Git and documents share one codec.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct TextEncoding {
|
||||
|
||||
@@ -1555,6 +1555,14 @@ fn restricted_reads_ignore_executable_repository_configuration() {
|
||||
assert!(!repo.log(&LogQuery::default()).unwrap().is_empty());
|
||||
repo.merge_versions(&f.path("a.txt"), encoding_rs::UTF_8).unwrap();
|
||||
assert!(!f.path("execution.marker").exists());
|
||||
let repos = ide_vcs::Repos::discover(&f.dir, &|_| false).unwrap();
|
||||
for r in repos.all() {
|
||||
r.set_execution_allowed(false);
|
||||
}
|
||||
let compared =
|
||||
repos.compare_paths(std::slice::from_ref(&f.dir), "HEAD", None, &ide_core::CancellationToken::new()).unwrap();
|
||||
assert!(compared.repositories.iter().all(|r| r.error.is_none()));
|
||||
assert!(!f.path("execution.marker").exists());
|
||||
// Positive control: the same filter really executes without restriction.
|
||||
f.git(&["-c", "core.fsmonitor=false", "diff", "--no-ext-diff", "--no-textconv"]);
|
||||
assert!(f.path("execution.marker").exists());
|
||||
|
||||
@@ -0,0 +1,505 @@
|
||||
//! Disk comparisons use the same excludes and layered ignore files as the project tree.
|
||||
use crate::{EntryKind, ExcludeMatcher, rules::GitignoreStack};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DirectoryCompareStatus {
|
||||
LeftOnly,
|
||||
RightOnly,
|
||||
Different,
|
||||
Equal,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DirectoryCompareEntry {
|
||||
pub path: String,
|
||||
pub status: DirectoryCompareStatus,
|
||||
pub left_kind: Option<EntryKind>,
|
||||
pub right_kind: Option<EntryKind>,
|
||||
#[specta(optional)]
|
||||
pub left_link: Option<String>,
|
||||
#[specta(optional)]
|
||||
pub right_link: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DirectoryCompareProgress {
|
||||
pub scanned: u32,
|
||||
pub compared: u32,
|
||||
pub total: Option<u32>,
|
||||
pub bytes_read: f64,
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
kind: EntryKind,
|
||||
size: u64,
|
||||
link: Option<PathBuf>,
|
||||
}
|
||||
|
||||
fn check(cancel: &CancellationToken) -> IdeResult<()> {
|
||||
if cancel.is_cancelled() { Err(IdeError::cancelled()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
struct Rules {
|
||||
base: PathBuf,
|
||||
excludes: ExcludeMatcher,
|
||||
ignore: GitignoreStack,
|
||||
}
|
||||
|
||||
impl Rules {
|
||||
fn new(root: &Path, project: Option<&Path>, excludes: &[String]) -> Self {
|
||||
Self {
|
||||
base: project.filter(|p| root.starts_with(p)).unwrap_or(root).to_path_buf(),
|
||||
excludes: ExcludeMatcher::new(excludes),
|
||||
ignore: GitignoreStack::new(root),
|
||||
}
|
||||
}
|
||||
|
||||
fn excluded(&self, path: &Path, dir: bool) -> bool {
|
||||
path.file_name().is_some_and(|n| n == ".git")
|
||||
|| self.excludes.is_excluded(path.strip_prefix(&self.base).unwrap_or(path))
|
||||
|| self.ignore.is_ignored(path, dir)
|
||||
}
|
||||
}
|
||||
|
||||
fn scan(
|
||||
root: &Path,
|
||||
rules: &Rules,
|
||||
cancel: &CancellationToken,
|
||||
progress: &mut DirectoryCompareProgress,
|
||||
emit: &impl Fn(DirectoryCompareProgress),
|
||||
) -> IdeResult<BTreeMap<String, Entry>> {
|
||||
if !fs::metadata(root)?.is_dir() {
|
||||
return Err(IdeError::invalid(format!("{} is not a directory", root.display())));
|
||||
}
|
||||
let mut result = BTreeMap::new();
|
||||
let mut pending = vec![root.to_path_buf()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
check(cancel)?;
|
||||
for item in fs::read_dir(dir)? {
|
||||
check(cancel)?;
|
||||
let path = item?.path();
|
||||
let meta = fs::symlink_metadata(&path)?;
|
||||
if rules.excluded(&path, meta.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let kind = if meta.file_type().is_symlink() {
|
||||
EntryKind::Symlink
|
||||
} else if meta.is_dir() {
|
||||
pending.push(path.clone());
|
||||
EntryKind::Dir
|
||||
} else if meta.is_file() {
|
||||
EntryKind::File
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let rel = path.strip_prefix(root).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let rel = ide_core::ipc_path::to_ipc(rel);
|
||||
let link = if kind == EntryKind::Symlink { Some(fs::read_link(&path)?) } else { None };
|
||||
result.insert(rel.clone(), Entry { kind, size: meta.len(), link });
|
||||
progress.scanned += 1;
|
||||
progress.path = rel;
|
||||
emit(progress.clone());
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn hash(
|
||||
path: &Path,
|
||||
cancel: &CancellationToken,
|
||||
progress: &mut DirectoryCompareProgress,
|
||||
emit: &impl Fn(DirectoryCompareProgress),
|
||||
) -> IdeResult<gix::hash::ObjectId> {
|
||||
let mut file = fs::File::open(path)?;
|
||||
let mut hash = gix::hash::hasher(gix::hash::Kind::Sha256);
|
||||
let mut buffer = [0; 64 * 1024];
|
||||
loop {
|
||||
check(cancel)?;
|
||||
let len = file.read(&mut buffer)?;
|
||||
if len == 0 {
|
||||
break;
|
||||
}
|
||||
hash.update(&buffer[..len]);
|
||||
progress.bytes_read += len as f64;
|
||||
emit(progress.clone());
|
||||
}
|
||||
hash.try_finalize().map_err(|e| IdeError::internal(e.to_string()))
|
||||
}
|
||||
|
||||
/// Size checks avoid reading unequal files. Equal-sized files are hashed in bounded,
|
||||
/// cancellable chunks; symlinks compare their link text and are never traversed.
|
||||
pub fn compare_directories(
|
||||
left: &Path,
|
||||
right: &Path,
|
||||
project: Option<&Path>,
|
||||
excludes: &[String],
|
||||
cancel: &CancellationToken,
|
||||
emit: impl Fn(DirectoryCompareProgress),
|
||||
) -> IdeResult<Vec<DirectoryCompareEntry>> {
|
||||
check(cancel)?;
|
||||
let mut progress = DirectoryCompareProgress::default();
|
||||
emit(progress.clone());
|
||||
let l = scan(left, &Rules::new(left, project, excludes), cancel, &mut progress, &emit)?;
|
||||
let r = scan(right, &Rules::new(right, project, excludes), cancel, &mut progress, &emit)?;
|
||||
let mut paths: Vec<_> = l.keys().chain(r.keys()).cloned().collect();
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
progress.total = Some(paths.len() as u32);
|
||||
let mut rows = BTreeMap::new();
|
||||
for path in paths {
|
||||
check(cancel)?;
|
||||
progress.path.clone_from(&path);
|
||||
let status = match (l.get(&path), r.get(&path)) {
|
||||
(Some(_), None) => DirectoryCompareStatus::LeftOnly,
|
||||
(None, Some(_)) => DirectoryCompareStatus::RightOnly,
|
||||
(Some(a), Some(b)) => {
|
||||
let equal = a.kind == b.kind
|
||||
&& match a.kind {
|
||||
EntryKind::Dir => true,
|
||||
EntryKind::Symlink => a.link == b.link,
|
||||
EntryKind::File => {
|
||||
a.size == b.size
|
||||
&& hash(&left.join(&path), cancel, &mut progress, &emit)?
|
||||
== hash(&right.join(&path), cancel, &mut progress, &emit)?
|
||||
}
|
||||
};
|
||||
if equal { DirectoryCompareStatus::Equal } else { DirectoryCompareStatus::Different }
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
rows.insert(
|
||||
path.clone(),
|
||||
DirectoryCompareEntry {
|
||||
path: path.clone(),
|
||||
status,
|
||||
left_kind: l.get(&path).map(|e| e.kind),
|
||||
right_kind: r.get(&path).map(|e| e.kind),
|
||||
left_link: l.get(&path).and_then(|e| e.link.as_ref()).map(|p| p.to_string_lossy().into_owned()),
|
||||
right_link: r.get(&path).and_then(|e| e.link.as_ref()).map(|p| p.to_string_lossy().into_owned()),
|
||||
},
|
||||
);
|
||||
progress.compared += 1;
|
||||
emit(progress.clone());
|
||||
}
|
||||
let changed: Vec<_> =
|
||||
rows.values().filter(|r| r.status != DirectoryCompareStatus::Equal).map(|r| r.path.clone()).collect();
|
||||
for path in changed {
|
||||
for parent in Path::new(&path).ancestors().skip(1) {
|
||||
if let Some(row) = rows.get_mut(&ide_core::ipc_path::to_ipc(parent))
|
||||
&& row.status == DirectoryCompareStatus::Equal
|
||||
{
|
||||
row.status = DirectoryCompareStatus::Different;
|
||||
}
|
||||
}
|
||||
}
|
||||
check(cancel)?;
|
||||
Ok(rows.into_values().collect())
|
||||
}
|
||||
|
||||
/// Merges a subtree without following links inside the comparison roots. Existing files
|
||||
/// require explicit overwrite; directory merges preserve destination-only entries.
|
||||
pub fn copy_merge(
|
||||
from: &Path,
|
||||
to: &Path,
|
||||
overwrite: bool,
|
||||
project: Option<&Path>,
|
||||
excludes: &[String],
|
||||
roots: (&Path, &Path),
|
||||
) -> IdeResult<()> {
|
||||
fn resolve(path: &Path) -> IdeResult<PathBuf> {
|
||||
if path.exists() {
|
||||
return Ok(dunce::canonicalize(path)?);
|
||||
}
|
||||
let parent = path.parent().ok_or_else(|| IdeError::invalid("copy requires an absolute path"))?;
|
||||
Ok(resolve(parent)?.join(path.file_name().ok_or_else(|| IdeError::invalid("missing file name"))?))
|
||||
}
|
||||
if !from.is_absolute() || !to.is_absolute() {
|
||||
return Err(IdeError::invalid("copy requires absolute paths"));
|
||||
}
|
||||
if !from.starts_with(roots.0) || !to.starts_with(roots.1) {
|
||||
return Err(IdeError::invalid("copy paths must belong to the comparison roots"));
|
||||
}
|
||||
let source = resolve(from)?;
|
||||
let target = resolve(to)?;
|
||||
if source.starts_with(&target) || target.starts_with(&source) {
|
||||
return Err(IdeError::invalid("cannot copy overlapping paths"));
|
||||
}
|
||||
for parent in to.ancestors().skip(1) {
|
||||
// The user explicitly selected this root; aliases above it (e.g. /tmp
|
||||
// on macOS) are valid. Links inside the copied subtree are not followed.
|
||||
if to == roots.1 || parent == roots.1 {
|
||||
break;
|
||||
}
|
||||
if fs::symlink_metadata(parent).is_ok_and(|m| m.file_type().is_symlink()) {
|
||||
return Err(IdeError::invalid("cannot copy through a destination symlink"));
|
||||
}
|
||||
}
|
||||
let source_base = project.filter(|p| from.starts_with(p)).or(Some(roots.0));
|
||||
let target_base = project.filter(|p| to.starts_with(p)).or(Some(roots.1));
|
||||
let rules = Rules::new(from, source_base, excludes);
|
||||
let target_rules = Rules::new(to, target_base, excludes);
|
||||
let mut pending = vec![(from.to_path_buf(), to.to_path_buf())];
|
||||
while let Some((src, dst)) = pending.pop() {
|
||||
let meta = fs::symlink_metadata(&src)?;
|
||||
if rules.excluded(&src, meta.is_dir()) || target_rules.excluded(&dst, meta.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let existing = fs::symlink_metadata(&dst).ok();
|
||||
let merge = meta.is_dir() && existing.as_ref().is_some_and(|m| m.is_dir());
|
||||
if existing.is_some() && !merge && !overwrite {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, dst.display().to_string()).into());
|
||||
}
|
||||
if meta.is_dir() {
|
||||
if existing.is_some() && !merge {
|
||||
crate::delete(&dst)?;
|
||||
}
|
||||
fs::create_dir_all(&dst)?;
|
||||
for entry in fs::read_dir(&src)? {
|
||||
let entry = entry?;
|
||||
pending.push((entry.path(), dst.join(entry.file_name())));
|
||||
}
|
||||
} else {
|
||||
if let Some(parent) = dst.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
// Stage the complete file before touching its destination.
|
||||
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let temp = dst.with_file_name(format!(".openidea-copy-{}-{id}", std::process::id()));
|
||||
let mut staged = false;
|
||||
let result: IdeResult<()> = (|| {
|
||||
#[cfg(windows)]
|
||||
if meta.file_type().is_symlink() {
|
||||
use std::os::windows::fs::{FileTypeExt, symlink_dir, symlink_file};
|
||||
let target = fs::read_link(&src)?;
|
||||
if meta.file_type().is_symlink_dir() {
|
||||
symlink_dir(target, &temp)?;
|
||||
} else {
|
||||
symlink_file(target, &temp)?;
|
||||
}
|
||||
} else {
|
||||
crate::copy(&src, &temp)?;
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
crate::copy(&src, &temp)?;
|
||||
staged = true;
|
||||
// Recheck after staging: another writer may have created the target.
|
||||
if fs::symlink_metadata(&dst).is_ok() {
|
||||
if !overwrite {
|
||||
return Err(
|
||||
std::io::Error::new(std::io::ErrorKind::AlreadyExists, dst.display().to_string()).into()
|
||||
);
|
||||
}
|
||||
crate::delete(&dst)?;
|
||||
}
|
||||
fs::rename(&temp, &dst)?;
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(error) = &result
|
||||
&& (staged || error.kind != ide_core::error::ErrorKind::AlreadyExists)
|
||||
{
|
||||
let _ = crate::delete_permanently(&temp);
|
||||
}
|
||||
result?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::error::ErrorKind;
|
||||
|
||||
fn put(root: &Path, path: &str, content: &[u8]) {
|
||||
let path = root.join(path);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, content).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_add_delete_modify_equal_binary_unicode_empty_and_type_conflicts() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let left = tmp.path().join("left");
|
||||
let right = tmp.path().join("right");
|
||||
put(&left, "子目录/仅左.txt", b"left");
|
||||
put(&right, "only-right", b"right");
|
||||
for (path, a, b) in [
|
||||
("same", b"same".as_slice(), b"same".as_slice()),
|
||||
("binary", &[0, 255, 10], &[0, 254, 10]),
|
||||
("size", b"a", b"bb"),
|
||||
("conflict", b"file", b""),
|
||||
] {
|
||||
put(&left, path, a);
|
||||
if path == "conflict" {
|
||||
put(&right, "conflict/child", b"child");
|
||||
} else {
|
||||
put(&right, path, b);
|
||||
}
|
||||
}
|
||||
fs::create_dir(left.join("empty")).unwrap();
|
||||
fs::create_dir(right.join("empty")).unwrap();
|
||||
let rows = compare_directories(&left, &right, None, &[], &CancellationToken::new(), |_| {}).unwrap();
|
||||
let status = |path| rows.iter().find(|r| r.path == path).unwrap().status;
|
||||
assert_eq!(status("same"), DirectoryCompareStatus::Equal);
|
||||
assert_eq!(status("empty"), DirectoryCompareStatus::Equal);
|
||||
for path in ["binary", "size", "conflict"] {
|
||||
assert_eq!(status(path), DirectoryCompareStatus::Different);
|
||||
}
|
||||
assert_eq!(status("子目录/仅左.txt"), DirectoryCompareStatus::LeftOnly);
|
||||
assert_eq!(status("only-right"), DirectoryCompareStatus::RightOnly);
|
||||
assert_eq!(status("conflict/child"), DirectoryCompareStatus::RightOnly);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applies_project_anchored_excludes_and_layered_ignores() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let left = tmp.path().join("left");
|
||||
let right = tmp.path().join("right");
|
||||
for root in [&left, &right] {
|
||||
put(root, "nested/node_modules/x", b"ignored");
|
||||
put(root, "target/x", b"ignored");
|
||||
put(root, ".git/config", b"ignored");
|
||||
put(root, "generated/x", b"ignored");
|
||||
put(root, ".gitignore", b"*.log\n");
|
||||
put(root, "nested/debug.log", b"ignored");
|
||||
put(root, "kept", b"kept");
|
||||
}
|
||||
let excludes = ["**/node_modules", "**/target", "/left/generated", "/right/generated"].map(String::from);
|
||||
let rows =
|
||||
compare_directories(&left, &right, Some(tmp.path()), &excludes, &CancellationToken::new(), |_| {}).unwrap();
|
||||
assert!(
|
||||
rows.iter()
|
||||
.all(|r| !["node_modules", "target", ".git/", "generated", ".log"].iter().any(|p| r.path.contains(p)))
|
||||
);
|
||||
assert!(rows.iter().any(|r| r.path == "kept"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_stops_before_scan_during_scan_and_during_hashing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let left = tmp.path().join("left");
|
||||
let right = tmp.path().join("right");
|
||||
put(&left, "big", &vec![1; 1024 * 1024]);
|
||||
put(&right, "big", &vec![1; 1024 * 1024]);
|
||||
for phase in 0..3 {
|
||||
let cancel = CancellationToken::new();
|
||||
if phase == 0 {
|
||||
cancel.cancel();
|
||||
}
|
||||
let result = compare_directories(&left, &right, None, &[], &cancel, |p| {
|
||||
if phase == 1 && p.scanned > 0 || phase == 2 && p.bytes_read > 0.0 {
|
||||
cancel.cancel();
|
||||
}
|
||||
});
|
||||
assert_eq!(result.unwrap_err().kind, ErrorKind::Cancelled);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn size_mismatches_are_not_hashed_and_directory_status_tracks_children() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let left = tmp.path().join("left");
|
||||
let right = tmp.path().join("right");
|
||||
put(&left, "nested/file", b"a");
|
||||
put(&right, "nested/file", b"ab");
|
||||
let bytes = std::cell::Cell::new(0.0);
|
||||
let rows =
|
||||
compare_directories(&left, &right, None, &[], &CancellationToken::new(), |p| bytes.set(p.bytes_read))
|
||||
.unwrap();
|
||||
assert_eq!(bytes.get(), 0.0);
|
||||
assert!(rows.iter().all(|r| r.status == DirectoryCompareStatus::Different));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merges_copies_with_explicit_overwrite_and_keeps_destination_only_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let left = tmp.path().join("left");
|
||||
let right = tmp.path().join("right");
|
||||
put(&left, "file", b"new");
|
||||
put(&left, "target/ignored", b"ignored");
|
||||
put(&right, "file", b"old");
|
||||
put(&right, "keep", b"keep");
|
||||
assert_eq!(
|
||||
copy_merge(&left, &right, false, None, &["target".into()], (&left, &right)).unwrap_err().kind,
|
||||
ErrorKind::AlreadyExists
|
||||
);
|
||||
assert_eq!(fs::read(right.join("file")).unwrap(), b"old");
|
||||
copy_merge(&left, &right, true, None, &["target".into()], (&left, &right)).unwrap();
|
||||
assert_eq!(fs::read(right.join("file")).unwrap(), b"new");
|
||||
assert_eq!(fs::read(right.join("keep")).unwrap(), b"keep");
|
||||
assert!(!right.join("target").exists());
|
||||
for (from, to) in [(&left, left.clone()), (&left, left.join("child")), (&right, tmp.path().to_path_buf())] {
|
||||
assert_eq!(
|
||||
copy_merge(from, &to, true, None, &[], (tmp.path(), tmp.path())).unwrap_err().kind,
|
||||
ErrorKind::InvalidInput
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subtree_copy_keeps_excludes_anchored_to_each_comparison_root() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let left = tmp.path().join("left");
|
||||
let right = tmp.path().join("right");
|
||||
put(&left, "sub/build/keep", b"included below sub");
|
||||
put(&left, "sub/protected", b"do not overwrite");
|
||||
put(&right, "sub/protected", b"keep destination");
|
||||
put(&right, ".gitignore", b"sub/protected\n");
|
||||
copy_merge(&left.join("sub"), &right.join("sub"), true, None, &["/build".into()], (&left, &right)).unwrap();
|
||||
assert_eq!(fs::read(right.join("sub/build/keep")).unwrap(), b"included below sub");
|
||||
assert_eq!(fs::read(right.join("sub/protected")).unwrap(), b"keep destination");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirmed_copy_replaces_file_directory_type_conflicts() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let left = tmp.path().join("left");
|
||||
let right = tmp.path().join("right");
|
||||
put(&left, "file", b"file");
|
||||
put(&right, "file/child", b"old directory");
|
||||
put(&left, "tree/child", b"new directory");
|
||||
put(&right, "tree", b"old file");
|
||||
for path in ["file", "tree"] {
|
||||
copy_merge(&left.join(path), &right.join(path), true, None, &[], (&left, &right)).unwrap();
|
||||
}
|
||||
assert_eq!(fs::read(right.join("file")).unwrap(), b"file");
|
||||
assert_eq!(fs::read(right.join("tree/child")).unwrap(), b"new directory");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlinks_compare_link_text_and_are_not_followed_when_copying() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let left = tmp.path().join("left");
|
||||
let right = tmp.path().join("right");
|
||||
fs::create_dir(&left).unwrap();
|
||||
fs::create_dir(&right).unwrap();
|
||||
symlink(".", left.join("loop")).unwrap();
|
||||
symlink("missing", right.join("loop")).unwrap();
|
||||
let rows = compare_directories(&left, &right, None, &[], &CancellationToken::new(), |_| {}).unwrap();
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0].status, DirectoryCompareStatus::Different);
|
||||
copy_merge(&left.join("loop"), &right.join("copied"), false, None, &[], (&left, &right)).unwrap();
|
||||
assert_eq!(fs::read_link(right.join("copied")).unwrap(), PathBuf::from("."));
|
||||
symlink(&right, tmp.path().join("alias")).unwrap();
|
||||
assert_eq!(
|
||||
copy_merge(&left.join("loop"), &tmp.path().join("alias/new"), true, None, &[], (tmp.path(), tmp.path()))
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ErrorKind::InvalidInput
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -62,20 +62,19 @@ pub fn decode_properties_escapes(text: &str) -> String {
|
||||
}
|
||||
|
||||
/// Serializes displayed properties text as ASCII, using uppercase UTF-16 units.
|
||||
/// Existing ASCII Unicode escapes retain their spelling and meaning on disk.
|
||||
pub fn encode_properties_ascii(text: &str) -> String {
|
||||
use std::fmt::Write;
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut rest = text;
|
||||
while let Some(c) = rest.chars().next() {
|
||||
let current = rest;
|
||||
rest = &rest[c.len_utf8()..];
|
||||
if c == '\\' {
|
||||
if rest.starts_with('\\') {
|
||||
out.push_str("\\\\");
|
||||
rest = &rest[1..];
|
||||
} else if unicode_character(current).is_some() || rest.chars().next().is_some_and(|next| !next.is_ascii()) {
|
||||
// Keep a literal backslash from swallowing a generated escape,
|
||||
// or becoming a Unicode escape on the next load.
|
||||
} else if rest.chars().next().is_some_and(|next| !next.is_ascii()) {
|
||||
// Keep a literal backslash from swallowing a generated escape.
|
||||
out.push_str("\\u005C");
|
||||
} else {
|
||||
out.push(c);
|
||||
@@ -387,13 +386,32 @@ mod tests {
|
||||
for text in ["plain=ASCII\r\n", r"escaped=\\u0041", r"bad=\u12xz", r"bad=\uD800"] {
|
||||
assert_eq!(encode_properties_ascii(text), text);
|
||||
}
|
||||
for text in ["你好😀", "\0", "\\中", "\\\\中", "\\\\\\😀", r"\u0041", r"\\u0041", r"\uD83D\uDE00"] {
|
||||
for text in ["你好😀", "\0", "\\中", "\\\\中", "\\\\\\😀", r"\\u0041"] {
|
||||
let ascii = encode_properties_ascii(text);
|
||||
assert!(ascii.is_ascii());
|
||||
assert_eq!(decode_properties_escapes(&ascii), text, "{ascii}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn properties_ascii_escapes_are_not_escaped_again() {
|
||||
for text in [
|
||||
r"test.key2=\u4F60\u597D",
|
||||
r"test.key3=\u4f60\u597d",
|
||||
r"ascii=\u0041\u005C\u000A",
|
||||
r"emoji=\uD83D\uDE00",
|
||||
r"slashes=\\u4F60 \\\u4F60 \\\\u4F60",
|
||||
r"bad=\u123 \u12xz \uu0041 \uD800 \uDC00",
|
||||
] {
|
||||
assert_eq!(encode_properties_ascii(text), text, "{text}");
|
||||
}
|
||||
let mixed = "raw=\\u4f60\\u597d; native=你好😀";
|
||||
let expected = r"raw=\u4f60\u597d; native=\u4F60\u597D\uD83D\uDE00";
|
||||
assert_eq!(encode_properties_ascii(mixed), expected);
|
||||
assert_eq!(encode_properties_ascii(expected), expected);
|
||||
assert_eq!(decode_properties_escapes(expected), "raw=你好; native=你好😀");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn properties_line_terminator_escapes_survive_an_edit() {
|
||||
let source = r"key=one\u000Atwo\u000Dthree";
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod archive;
|
||||
mod bytes;
|
||||
mod compare;
|
||||
mod encoding;
|
||||
mod ops;
|
||||
mod rules;
|
||||
@@ -20,6 +21,9 @@ pub use archive::{
|
||||
read_archive_entry, split_archive_path,
|
||||
};
|
||||
pub use bytes::{ByteRange, FileProbe, MAX_RANGE_LEN, base64, image_mime, probe, read_data_url, read_range};
|
||||
pub use compare::{
|
||||
DirectoryCompareEntry, DirectoryCompareProgress, DirectoryCompareStatus, compare_directories, copy_merge,
|
||||
};
|
||||
use encoding::SNIFF_LEN;
|
||||
pub use encoding::{
|
||||
LARGE_FILE_THRESHOLD, MAX_OPEN_SIZE, READ_ONLY_THRESHOLD, decode_properties_escapes, encode,
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
use super::{ProjectRoots, RootKind};
|
||||
use ide_core::settings::ProjectStructureSettings;
|
||||
use std::path::{Component, Path};
|
||||
|
||||
/// Source paths for jdtls's unmanaged project, relative to its workspace folder.
|
||||
/// Maven, Gradle and Eclipse own their source model; other layouts retain jdtls inference.
|
||||
pub fn unmanaged_java_source_paths(
|
||||
project: &Path,
|
||||
server_root: &Path,
|
||||
settings: &ProjectStructureSettings,
|
||||
) -> Option<Vec<String>> {
|
||||
if ["pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts", ".project"]
|
||||
.iter()
|
||||
.any(|name| server_root.join(name).is_file())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let roots = ProjectRoots::compute(Vec::new(), settings);
|
||||
let mut paths: Vec<String> = roots
|
||||
.roots
|
||||
.iter()
|
||||
.filter(|r| matches!(r.kind, RootKind::Source | RootKind::Test))
|
||||
.filter(|r| Path::new(&r.path).components().all(|c| matches!(c, Component::Normal(_))))
|
||||
.filter_map(|r| {
|
||||
let absolute = project.join(&r.path);
|
||||
let relative = absolute.strip_prefix(server_root).ok()?;
|
||||
let path = relative.to_string_lossy().replace('\\', "/");
|
||||
Some(if path.is_empty() { ".".into() } else { path })
|
||||
})
|
||||
.collect();
|
||||
if paths.is_empty() {
|
||||
// jdtls can infer the package directory itself as a source root. Give
|
||||
// conventional layouts an unambiguous base without guessing other layouts.
|
||||
paths = ["src/main/java", "src/test/java"]
|
||||
.into_iter()
|
||||
.filter(|p| server_root.join(p).is_dir())
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
if paths.is_empty() && server_root.join("src").is_dir() {
|
||||
paths.push("src".into());
|
||||
}
|
||||
}
|
||||
(!paths.is_empty()).then_some(paths)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn marked_sources_and_tests_are_relative_to_the_server() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let settings = ProjectStructureSettings {
|
||||
source_roots: vec!["./app/generated/".into(), "other/src".into(), "../outside".into()],
|
||||
test_roots: vec!["app/tests".into()],
|
||||
resource_roots: vec!["app/resources".into()],
|
||||
excluded: vec!["app/out".into()],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
unmanaged_java_source_paths(dir.path(), &dir.path().join("app"), &settings),
|
||||
Some(vec!["generated".into(), "tests".into()])
|
||||
);
|
||||
let settings = ProjectStructureSettings { source_roots: vec![".".into()], ..Default::default() };
|
||||
assert_eq!(unmanaged_java_source_paths(dir.path(), dir.path(), &settings), Some(vec![".".into()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conventional_layouts_and_other_unmarked_projects() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let settings = ProjectStructureSettings::default();
|
||||
assert_eq!(unmanaged_java_source_paths(root, root, &settings), None);
|
||||
std::fs::create_dir_all(root.join("src")).unwrap();
|
||||
assert_eq!(unmanaged_java_source_paths(root, root, &settings), Some(vec!["src".into()]));
|
||||
std::fs::create_dir_all(root.join("src/main/java")).unwrap();
|
||||
std::fs::create_dir_all(root.join("src/test/java")).unwrap();
|
||||
assert_eq!(
|
||||
unmanaged_java_source_paths(root, root, &settings),
|
||||
Some(vec!["src/main/java".into(), "src/test/java".into()])
|
||||
);
|
||||
let settings = ProjectStructureSettings { source_roots: vec!["custom".into()], ..settings };
|
||||
assert_eq!(unmanaged_java_source_paths(root, root, &settings), Some(vec!["custom".into()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ant_projects_use_unmanaged_source_roots() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::write(root.join("build.xml"), "<project/>\n").unwrap();
|
||||
std::fs::create_dir_all(root.join("src/com/acme")).unwrap();
|
||||
let settings = ProjectStructureSettings::default();
|
||||
assert_eq!(unmanaged_java_source_paths(root, root, &settings), Some(vec!["src".into()]));
|
||||
let settings = ProjectStructureSettings { source_roots: vec!["src".into(), "generated".into()], ..settings };
|
||||
assert_eq!(unmanaged_java_source_paths(root, root, &settings), Some(vec!["generated".into(), "src".into()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_projects_keep_their_build_model() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let settings = ProjectStructureSettings { source_roots: vec!["custom".into()], ..Default::default() };
|
||||
for marker in
|
||||
["pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts", ".project"]
|
||||
{
|
||||
std::fs::write(root.join(marker), "").unwrap();
|
||||
assert_eq!(unmanaged_java_source_paths(root, root, &settings), None, "{marker}");
|
||||
std::fs::remove_file(root.join(marker)).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,11 @@
|
||||
|
||||
mod detect;
|
||||
mod gradle;
|
||||
mod java;
|
||||
mod maven;
|
||||
|
||||
pub use detect::{affects_roots, detect};
|
||||
pub use java::unmanaged_java_source_paths;
|
||||
|
||||
use ide_core::settings::ProjectStructureSettings;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -641,6 +641,57 @@ fn properties_conversion_uses_displayed_utf16_and_survives_reload() {
|
||||
assert!(!f.docs.is_dirty(doc.id).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn properties_pasted_escapes_survive_save_and_decode_on_reload() {
|
||||
let pasted = "test.key1=Hello\ntest.key2=\\u4F60\\u597D\ntest.key3=\\u4f60\\u597d\n";
|
||||
let displayed = "test.key1=Hello\ntest.key2=你好\ntest.key3=你好\n";
|
||||
for encoding in ["utf-8", "iso-8859-1", "utf-16le"] {
|
||||
for eol in ["\n", "\r\n"] {
|
||||
let f = fixture();
|
||||
let path = f.root.join("test_zh_CN.properties");
|
||||
let source = pasted.replace('\n', eol);
|
||||
fs::write(&path, ide_vfs::encode(&source, encoding, encoding == "utf-16le").unwrap()).unwrap();
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.native_to_ascii = true;
|
||||
defaults.properties_fallback = encoding.into();
|
||||
f.docs.set_file_defaults(defaults.clone());
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!(doc.text, displayed);
|
||||
|
||||
f.docs.replace_all(doc.id, pasted).unwrap();
|
||||
f.docs.save(doc.id).unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), source.as_bytes(), "{encoding} {eol:?}");
|
||||
assert_eq!(f.docs.snapshot(doc.id).unwrap().text, pasted);
|
||||
assert!(!f.docs.is_dirty(doc.id).unwrap());
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
assert_eq!(f.docs.snapshot(doc.id).unwrap().text, pasted, "own saves do not reload");
|
||||
|
||||
f.docs.close(doc.id);
|
||||
let reopened = f.docs.open(&path).unwrap();
|
||||
assert_eq!(reopened.text, displayed);
|
||||
// An edit followed by its inverse preserves the original escape casing.
|
||||
f.docs.replace_all(reopened.id, pasted).unwrap();
|
||||
f.docs.replace_all(reopened.id, displayed).unwrap();
|
||||
f.docs.save(reopened.id).unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), source.as_bytes());
|
||||
|
||||
let external = format!("{source}test.key4=\\uD83D\\uDE00{eol}");
|
||||
fs::write(&path, &external).unwrap();
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
assert_eq!(f.docs.snapshot(reopened.id).unwrap().text, format!("{displayed}test.key4=😀\n"));
|
||||
defaults.native_to_ascii = false;
|
||||
f.docs.set_file_defaults(defaults.clone());
|
||||
f.docs.reload_properties();
|
||||
assert_eq!(f.docs.snapshot(reopened.id).unwrap().text, external.replace("\r\n", "\n"));
|
||||
defaults.native_to_ascii = true;
|
||||
f.docs.set_file_defaults(defaults);
|
||||
f.docs.reload_properties();
|
||||
assert_eq!(f.docs.snapshot(reopened.id).unwrap().text, format!("{displayed}test.key4=😀\n"));
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), external);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn properties_toggle_reloads_only_clean_properties_and_pins_dirty_codec() {
|
||||
let f = fixture();
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
/** Docking agent conversations between the editor and the Agents tool window by drag & drop. */
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
|
||||
const TASK = {
|
||||
id: "t1",
|
||||
title: "Repro task",
|
||||
status: "ready" as const,
|
||||
isolation: "local" as const,
|
||||
provider: "codex",
|
||||
model: null,
|
||||
cwd: "/dev/acme-api",
|
||||
branch: null,
|
||||
base: null,
|
||||
baseCommit: null,
|
||||
error: null,
|
||||
createdMs: 0,
|
||||
updatedMs: 0,
|
||||
config: [],
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
};
|
||||
|
||||
/** Seeds one task in the agents store (no backend in plain-browser mode) and docks it. */
|
||||
async function seedAndDock(page: Page) {
|
||||
await page.evaluate(async (task) => {
|
||||
// Paths go through variables: knip can't resolve these browser-absolute URLs.
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const store = await import(storePath);
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
providers: [],
|
||||
tasks: new Map([[task.id, task]]),
|
||||
unread: new Set(),
|
||||
docked: null,
|
||||
});
|
||||
store.dockTask(task.id);
|
||||
}, TASK);
|
||||
await page.locator("span[title='Repro task']").first().waitFor();
|
||||
}
|
||||
|
||||
test("drags the docked conversation back onto the editor", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
await page.getByRole("tree", { name: "Project" }).waitFor();
|
||||
// An editor pane, so the session tab has a content drop target to land on.
|
||||
await page.getByRole("treeitem", { name: "README.md", exact: true }).dblclick();
|
||||
await page.getByRole("tab", { name: "README.md" }).waitFor();
|
||||
await seedAndDock(page);
|
||||
|
||||
const title = page.locator("span[title='Repro task']").first();
|
||||
const to = await page.getByRole("tabpanel").first().boundingBox();
|
||||
const from = await title.boundingBox();
|
||||
await page.mouse.move(from!.x + from!.width / 2, from!.y + from!.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(to!.x + to!.width / 2, to!.y + to!.height / 2, { steps: 10 });
|
||||
await page.mouse.up();
|
||||
|
||||
await expect(page.getByRole("tab", { name: "Repro task" })).toBeVisible();
|
||||
await expect(page.getByRole("tree", { name: "Agent tasks" })).toBeVisible();
|
||||
});
|
||||
|
||||
test("drags the docked conversation back onto the empty editor", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
await page.getByRole("tree", { name: "Project" }).waitFor();
|
||||
// Docking closes the session tab; with no other tabs the editor is empty and
|
||||
// must still take the drop (regression: the empty state had no drop target).
|
||||
await seedAndDock(page);
|
||||
await expect(page.locator("[data-editor-area] [role='tabpanel']")).toHaveCount(0);
|
||||
|
||||
const title = page.locator("span[title='Repro task']").first();
|
||||
const to = await page.getByText("Drop files here to open them").boundingBox();
|
||||
const from = await title.boundingBox();
|
||||
await page.mouse.move(from!.x + from!.width / 2, from!.y + from!.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(to!.x + to!.width / 2, to!.y + to!.height / 2, { steps: 10 });
|
||||
await page.mouse.up();
|
||||
|
||||
await expect(page.getByRole("tab", { name: "Repro task" })).toBeVisible();
|
||||
});
|
||||
|
||||
test("docks a session tab dropped on the tool window", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
await page.getByRole("tree", { name: "Project" }).waitFor();
|
||||
await page.getByRole("treeitem", { name: "README.md", exact: true }).dblclick();
|
||||
await page.getByRole("tab", { name: "README.md" }).waitFor();
|
||||
await page.evaluate(async (task) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const modelPath = "/src/features/agents/model.ts";
|
||||
const contributionsPath = "/src/workbench/contributions.ts";
|
||||
const store = await import(storePath);
|
||||
const { TOOL_WINDOW } = await import(modelPath);
|
||||
const { toolWindowService } = await import(contributionsPath);
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
providers: [],
|
||||
tasks: new Map([[task.id, task]]),
|
||||
unread: new Set(),
|
||||
docked: null,
|
||||
});
|
||||
toolWindowService().show(TOOL_WINDOW, true);
|
||||
store.openTask(task.id);
|
||||
}, TASK);
|
||||
await page.getByRole("tab", { name: "Repro task" }).waitFor();
|
||||
|
||||
const tab = page.getByRole("tab", { name: "Repro task" });
|
||||
const to = await page.getByRole("tree", { name: "Agent tasks" }).boundingBox();
|
||||
const from = await tab.boundingBox();
|
||||
await page.mouse.move(from!.x + from!.width / 2, from!.y + from!.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(to!.x + to!.width / 2, to!.y + to!.height / 2, { steps: 10 });
|
||||
await page.mouse.up();
|
||||
|
||||
// Docked: the tab closes and the tool window gives itself to the conversation.
|
||||
await expect(page.getByRole("tab", { name: "Repro task" })).toHaveCount(0);
|
||||
await expect(page.getByRole("tree", { name: "Agent tasks" })).toHaveCount(0);
|
||||
await expect(page.locator("span[title='Repro task']").first()).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"languages": [
|
||||
"xml",
|
||||
"html",
|
||||
"vue",
|
||||
"svelte",
|
||||
"css",
|
||||
"java",
|
||||
"rust",
|
||||
"typescript",
|
||||
"python",
|
||||
"csharp",
|
||||
"sql",
|
||||
"clojure",
|
||||
"erlang",
|
||||
"bat",
|
||||
"ocaml",
|
||||
"fsharp",
|
||||
"haskell",
|
||||
"lua",
|
||||
"cmake",
|
||||
"powershell",
|
||||
"julia",
|
||||
"ruby"
|
||||
],
|
||||
"markers": [
|
||||
{
|
||||
"start": "region Name",
|
||||
"end": "endregion",
|
||||
"name": "Name"
|
||||
},
|
||||
{
|
||||
"start": "region要折叠的内容",
|
||||
"end": "endregion",
|
||||
"name": "要折叠的内容"
|
||||
},
|
||||
{
|
||||
"start": "#region \"Quoted name\"",
|
||||
"end": "#endregion",
|
||||
"name": "Quoted name"
|
||||
},
|
||||
{
|
||||
"start": "REGION Mixed case",
|
||||
"end": "ENDREGION",
|
||||
"name": "Mixed case"
|
||||
},
|
||||
{
|
||||
"start": "region",
|
||||
"end": "endregion",
|
||||
"name": ""
|
||||
},
|
||||
{
|
||||
"start": "<editor-fold desc=\"Head 内容\">",
|
||||
"end": "</editor-fold>",
|
||||
"name": "Head 内容"
|
||||
},
|
||||
{
|
||||
"start": "<editor-fold>",
|
||||
"end": "</editor-fold>",
|
||||
"name": ""
|
||||
}
|
||||
],
|
||||
"invalid": [
|
||||
"regional Name",
|
||||
"regions.push(x)",
|
||||
"endregionFoo",
|
||||
"<editor-folder>",
|
||||
"</editor-folder>",
|
||||
"the region below",
|
||||
"region_name",
|
||||
"<editor-fold",
|
||||
"</editor-fold"
|
||||
]
|
||||
}
|
||||
@@ -32,12 +32,13 @@ resolveAdditionalTextEditsSupport = true
|
||||
|
||||
[language-servers.initialization-options.settings.java]
|
||||
autobuild = { enabled = true }
|
||||
contentProvider = { preferred = "fernflower" }
|
||||
contentProvider = { preferred = "fernflowerContentProvider" }
|
||||
maven = { downloadSources = true, updateSnapshots = false }
|
||||
eclipse = { downloadSources = true }
|
||||
references = { includeDecompiledSources = true }
|
||||
signatureHelp = { enabled = true }
|
||||
configuration = { updateBuildConfiguration = "automatic" }
|
||||
project = { referencedLibraries = ["lib/**/*.jar"] }
|
||||
# Generated code (implement methods, getters, toString…) indents like the editor (`indent` above).
|
||||
format = { insertSpaces = true, tabSize = 4 }
|
||||
# Calls complete as `name()` with the caret inside and parameter info, not guessed arguments;
|
||||
|
||||
@@ -3,6 +3,9 @@ name = "Svelte"
|
||||
extensions = ["svelte"]
|
||||
block-comment = ["<!--", "-->"]
|
||||
indent = { tab-size = 2, insert-spaces = true }
|
||||
# No Svelte mode ships with @codemirror/language-data; the HTML mode already
|
||||
# parses <script> as TypeScript and <style> as CSS, so components get highlighted.
|
||||
ui-mode = "HTML"
|
||||
|
||||
[[language-servers]]
|
||||
name = "svelte-language-server"
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.29",
|
||||
"version": "0.1.32",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
Manifest-Version: 1.0
|
||||
Bundle-ManifestVersion: 2
|
||||
Bundle-Name: OpenIDEA Java usages
|
||||
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
|
||||
Bundle-Version: 1.1.1
|
||||
Bundle-RequiredExecutionEnvironment: JavaSE-21
|
||||
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
|
||||
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
|
||||
org.eclipse.lsp4j
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
# Semantic Java usages
|
||||
|
||||
The app-owned OSGi command `openidea.java.usages` returns `{location, kind, access}`.
|
||||
`kind` retains field/getter/setter/unknown identity for compatibility. Optional
|
||||
`access` is read/write/readWrite/unknown. Missing access metadata is unknown;
|
||||
old servers and ordinary LSP locations remain visible under either filter.
|
||||
An absent or failing extension command uses standard LSP references, without access
|
||||
classification or toolbar controls. This includes errors during scope widening.
|
||||
The Rust bridge logs the failure once per project session. Cancelled requests and
|
||||
changed source documents remain cancelled and do not start a fallback search.
|
||||
No global `includeAccessors` preference is changed.
|
||||
|
||||
## Search plan and access semantics
|
||||
|
||||
For source fields on the verified JDT LS implementation, a single plan merges
|
||||
field, native getter/setter, native builder and explicit Lombok Accessors targets.
|
||||
Targets are deduplicated by JDT element identity before search, retaining native
|
||||
search scope and ranges. Builder results remain unknown. The optimized native
|
||||
plan is guarded by SHA-256 of ReferencesHandler.class:
|
||||
`31ff5a10c7d69d58c6a9b619ef17e3ec41b11b545751ba428618a76cc1341064`
|
||||
(JDT LS 1.63.0.202610191322). Different implementations, non-field selections and
|
||||
library/decompiled selections retain native discovery plus deduplicated category
|
||||
searches. This conservative fallback preserves coverage when the server changes;
|
||||
it does not promise the same speedup on unverified versions.
|
||||
|
||||
SearchEngine resolves exact targets. A query-local syntax AST per referenced source
|
||||
file supplies expression context without another reference search: simple field
|
||||
assignment is write, compound assignment/increment is readWrite, ordinary field
|
||||
use is read. Writing an array element or a receiver's member reads the array or
|
||||
receiver field. Getter/setter call expressions are read/write respectively.
|
||||
Method references, declarations, unavailable/changed source, and unclassified
|
||||
search targets remain unknown. No call text or get/set prefix classifies a usage.
|
||||
Explicit `@Accessors` is resolved to JDT method signatures as in the prior bundle.
|
||||
|
||||
For larger result sets, a query-local AST range index avoids repeating NodeFinder
|
||||
traversals. It indexes only requested exact AST ranges and verified invocation
|
||||
selector-to-call-end spans; duplicate, recovered, malformed or uncontained ranges
|
||||
fall back to NodeFinder. Method references do not get invocation aliases. Source
|
||||
snapshot checks remain per result, and the index is discarded after the query.
|
||||
There is no cross-request cache or binding-resolution shortcut.
|
||||
|
||||
Popup and Find share persisted read/write toolbar switches. Both initially show;
|
||||
turning the last one off automatically enables the other. Unknown and readWrite
|
||||
entries survive both single-access modes. Filtered-out selections are not previewed.
|
||||
Exact original ranges and access metadata survive transfer to Find. Closing or
|
||||
superseding a popup request prevents late responses from reopening it.
|
||||
|
||||
The interaction and primary-field/secondary-accessor design were checked against
|
||||
[JetBrains IntelliJ Community e992ff4](https://github.com/JetBrains/intellij-community/tree/e992ff4750b4c36afe2caadfa8b191a8f36fb7a2):
|
||||
`LombokFieldFindUsagesHandlerFactory`, `LombokReadWriteAccessDetector`,
|
||||
`UsageFilteringRuleStateRWAware`, `ReadAccessFilteringRule`, and
|
||||
`WriteAccessFilteringRule`. This implementation does not copy those sources and
|
||||
is not a claim of full IntelliJ feature parity.
|
||||
|
||||
## Rebuild and delivery
|
||||
|
||||
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
|
||||
`java-usages-1.1.1.jar`, and added alongside existing initialization bundles.
|
||||
Users need no compiler, Maven or Python. Manifest/install version must change
|
||||
when replacing the bundle because OSGi caches bundles.
|
||||
|
||||
Build dependency: [JDT LS 1.63.0 build 202610191322](https://download.eclipse.org/jdtls/milestones/1.63.0/jdt-language-server-1.63.0-202610191322.tar.gz).
|
||||
Use its shipped ECJ and plugin jars, with Java 25; emitted bytecode targets Java 21.
|
||||
The build uses sorted inputs and fixed zip timestamps and does not resolve Maven
|
||||
artifacts. Check the extracted distribution against `build-dependencies.sha256`
|
||||
from its root (`sha256sum -c /path/to/build-dependencies.sha256`). Build twice
|
||||
and compare SHA-256. The 1.1.1 output is
|
||||
`1e569939cba22c7db6e2c9b53de2a4c10ccaabe762a51427119a04af3d974ae4`.
|
||||
|
||||
```sh
|
||||
export PATH=/path/to/jdk25/bin:$PATH
|
||||
python3 plugins/java-usages/build.py /path/to/jdtls
|
||||
```
|
||||
|
||||
## Manual upgrades
|
||||
|
||||
Rebuilding on a JDT LS upgrade is manual. Updating JDT LS or compiling the app does
|
||||
not rebuild this jar. A maintainer must:
|
||||
|
||||
1. Obtain the intended JDT LS distribution and verify its provenance and plugin hashes.
|
||||
Update `build-dependencies.sha256` for the reviewed distribution.
|
||||
2. Review the internal APIs listed below. Check `ReferencesHandler.class` against
|
||||
the native-plan fingerprint; update the guarded plan only after reviewing changes.
|
||||
3. Bump the bundle version in `MANIFEST.MF` and the installed filename in
|
||||
`crates/ide-sdk/src/java.rs` so OSGi does not reuse the old cached bundle.
|
||||
4. Run `build.py` with that distribution and JDK 25 as shown above. Build twice and
|
||||
compare hashes, then run both real-server harnesses and the desktop checks below.
|
||||
5. Commit the reviewed source, dependency inventory, version changes and rebuilt jar
|
||||
together. Test the current and newly supported JDT LS versions before release.
|
||||
|
||||
## Real server verification
|
||||
|
||||
```sh
|
||||
python3 plugins/java-usages/tests/verify.py /path/to/jdtls /path/to/lombok.jar
|
||||
python3 plugins/java-usages/tests/read-write.py /path/to/jdtls /path/to/lombok.jar > /tmp/read-write.json
|
||||
OPENIDEA_USAGES_INDEX_STRESS=1 python3 plugins/java-usages/tests/read-write.py /path/to/jdtls /path/to/lombok.jar > /tmp/read-write-indexed.json
|
||||
```
|
||||
|
||||
The harnesses select the JDT LS configuration for the current platform. The first
|
||||
verifies category coverage, standard-reference inclusion, boolean/fluent/prefix/chain
|
||||
naming, overloads, inheritance and includeAccessors=false. The second checks
|
||||
structural read/write cases, interface and inherited calls, nested same-line calls,
|
||||
method references, receiver/array reads and a real cancellation response (`-32800`).
|
||||
|
||||
Use the actual desktop app to check read/write toggles, mutual toggle behavior,
|
||||
Find transfer, persistence and unfiltered non-Java counts with the same fixture.
|
||||
|
||||
## Review and manual reproduction
|
||||
|
||||
See [the English reproduction guide](tests/REPRODUCE.md) for a small Java/Lombok
|
||||
fixture, before/after behavior and desktop verification steps.
|
||||
|
||||
## Internal API compatibility
|
||||
|
||||
This is an app-owned JDT LS extension, not a standard LSP feature. It uses:
|
||||
|
||||
- `org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler` and the
|
||||
`org.eclipse.jdt.ls.core.delegateCommandHandler` extension point.
|
||||
- `ReferencesHandler.findReferences` and `search`; the optimized plan also
|
||||
reflects its private `getBuilderName(IField)` on the fingerprinted version.
|
||||
- `JavaLanguageServerPlugin.getPreferencesManager` and the returned preference
|
||||
objects (`isIncludeAccessors`).
|
||||
- `JDTUtils.resolveTypeRoot`, `findElementAtSelection`.
|
||||
- `org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil`.
|
||||
- Public JDT model/DOM APIs for exact target identity and source-expression context.
|
||||
|
||||
The fingerprint protects native target discovery, not all binary compatibility.
|
||||
A server update that breaks linkage or command execution falls back to standard
|
||||
references in the Rust bridge. Results remain visible without classification.
|
||||
Rebuild and run the real-server and desktop tests when changing the distribution.
|
||||
The current read/write implementation was tested on JDT LS 1.63.0.202610191322
|
||||
with Lombok 1.18.48 and Java 25. It is not certified for every milestone.
|
||||
|
||||
## Boundaries
|
||||
|
||||
- `lombok.config`-only naming, unusual generic spellings, custom capitalization or
|
||||
ambiguous annotations retain the prior limitations; no speculative mapping.
|
||||
- Method references are conservatively unknown rather than asserted immediate reads/writes.
|
||||
- Constructor initialization is outside this product change.
|
||||
- Internal JDT APIs still require compatibility testing on updates; guarded native
|
||||
planning is intentionally limited to a verified implementation.
|
||||
- Packaged desktop/macOS WebKit and the user's own project require separate testing.
|
||||
@@ -0,0 +1,110 @@
|
||||
beebede8db065fe1b72909ecc66bb49acda618901635d86c25fce14a5915e37e plugins/ch.qos.logback.classic_1.6.3.jar
|
||||
a6967a28c8b086dee75a694d2f6fb8830c71153539866d7d8af065c9b6df91e0 plugins/ch.qos.logback.core_1.6.3.jar
|
||||
2cbd119bf1961c28788310963dc80ba65f58cdeec1dd139c8bdb1240faa2c36f plugins/com.google.gson_2.14.0.jar
|
||||
cbfc3906b19b8f55dd7cfd6dfe0aa4532e834250d7f080bd8d211a3e246b59cb plugins/com.google.guava.failureaccess_1.0.3.jar
|
||||
796d8e28ac64e83a47c4c5935a8fecc4682650a04bbdead738ef0f5a3a0e6c46 plugins/com.google.guava_33.7.1.jre.jar
|
||||
3b3864f5b449e9c3c24b16861524b622b086563f44e0cd8384c8efc5a6052f82 plugins/com.sun.jna.platform_5.19.1.jar
|
||||
467b2990d4f406e7d41f7a989f89df257767ca11d566f844560e2ab8d09f6433 plugins/com.sun.jna_5.19.1.v20260612-1000.jar
|
||||
85fb03fc054cdf4efca8efd9b6712bbb418e1ab98241c4539c8585bbc23e1b8a plugins/jakarta.annotation-api_1.3.5.jar
|
||||
a852b0971c589491e24334bd77e92760c048d2c102fc4c68e582e1cd53130f84 plugins/jakarta.inject.jakarta.inject-api_1.0.5.jar
|
||||
2506fb25a748d4a5e5ec549d8bb063889d0f213e9cfbd6fd6fcbdc93b4f35bbb plugins/jakarta.servlet-api_6.2.0.M2.jar
|
||||
cbf2aa09c14441d2ddea7096f60b738b3aee7f08fbf98f5f91e2ca48b08fff4a plugins/org.apache.ant_1.10.18.v20260906-1000.jar
|
||||
8f7f8605d68e15bf32db61ec94eac6fdafc51b1bdbe1e0e0802b57d23f387792 plugins/org.apache.commons.cli_1.11.0.jar
|
||||
78a5d732fbd715e2d10bd7150d2f8030bae57267f8aacc5c88f642cb6c2e5d3f plugins/org.apache.commons.commons-codec_1.22.1.jar
|
||||
69e5c9fa35da7a51a5fd2099dfe56a2d8d32cf233e2f6d770e796146440263f4 plugins/org.apache.commons.lang3_3.20.0.jar
|
||||
c5bd887c8fd5ec4cd563249e7552bb1a1a1ca57e05a1f1ef8425a7b7b7bd2fbe plugins/org.apache.felix.scr_2.2.18.jar
|
||||
c375b6d5b71efe179e5763a6d83fcf10e303c0bf82031310a46769727ac90da0 plugins/org.commonmark.ext-gfm-tables_0.30.1.jar
|
||||
9b0d20064975a17e876fcb4b599c6b3667f46a7739ed61e2f06c96f44b50629f plugins/org.commonmark_0.30.1.jar
|
||||
a6a16f8f2b6977a10f951ab4ff46b155e4e20dd8c2fcd2cb835b74d90f30b456 plugins/org.eclipse.ant.core_3.7.1100.v20260831-0701.jar
|
||||
61c479b6544db7eeebb5ba796051c092032d03a5136295baabd72a233baef29c plugins/org.eclipse.buildship.compat_3.1.13.v20260923-0232-s.jar
|
||||
213baab808816e0661acd61a5382a8f120923288212defbd189b4ee6540ecce1 plugins/org.eclipse.buildship.core_3.1.13.v20260923-0232-s.jar
|
||||
e75b07863128a076989d15e815d63a49cab772a338f1f0444d007bef3fa94601 plugins/org.eclipse.compare.core_3.8.900.v20260731-0809.jar
|
||||
01425989976dccd56d348b207e11239b3d8bf572f7b7ef12dbd29eb39c40205e plugins/org.eclipse.core.commands_3.13.100.v20260902-1129.jar
|
||||
a63b488fb9d5382fbb3b8bae0951f1da5fd3a20211aa6814c7e8c1e21d2ffc78 plugins/org.eclipse.core.contenttype_3.9.1000.v20260921-1824.jar
|
||||
06a18236ae181659e1e5499d912d68de527720686f1f51dab632d3e298e32b78 plugins/org.eclipse.core.expressions_3.9.700.v20260710-0925.jar
|
||||
422a33041ea01954f48ff3969e2c6d96e64831b3e372202a4d2a914282e3ffd9 plugins/org.eclipse.core.filebuffers_3.9.0.v20261010-1449.jar
|
||||
d0f5e3fb7cd17bb8daebc684311198138e380e089292477f12d2dfbb4c8a30a8 plugins/org.eclipse.core.filesystem_1.12.0.v20260927-0940.jar
|
||||
941b3c5feeba4ec0a949a8a94ff10283b2505813fa736c9e6345f146ae1b7e8a plugins/org.eclipse.core.jobs_3.15.900.v20260604-0622.jar
|
||||
6e7a8db7d87a44bb35924bb345ddf0d9372413e3fee2edd842b50ed630ec254f plugins/org.eclipse.core.net_1.5.900.v20260507-0401.jar
|
||||
e22d47e2e68713a74bfacd134dc01b1aa904a1b429769241483e058de166acea plugins/org.eclipse.core.resources_3.25.0.v20261010-1447.jar
|
||||
0947f29f5c5b7d234e3b735de2d00d33ae6e3ee428a61bb818f9c0fe2b809735 plugins/org.eclipse.core.runtime_3.35.100.v20260910-1515.jar
|
||||
553f09a59f2662fa4a3bbc94e84bd83221c1c6fb532d81b57010162fb47460a6 plugins/org.eclipse.core.variables_3.6.900.v20260602-0702.jar
|
||||
a4e87f5e883e6c864783dc8148e9f915c3e7a9e3e0e26acf6b82210d1134ed79 plugins/org.eclipse.debug.core_3.24.100.v20261009-1915.jar
|
||||
fd353398835107608f554779a6e91891725efb94e0f57559d0ab3cea4b6156c7 plugins/org.eclipse.equinox.app_1.7.600.v20251211-1038.jar
|
||||
28749ec64dac9d0e20e00becc3d5f9daccb5637455c9c546ab07be324011ef84 plugins/org.eclipse.equinox.common_3.21.100.v20260829-1451.jar
|
||||
9beeb1098a3da89a470c547aa840dea0d240d144138a5ba7b9ceedb84ed301ab plugins/org.eclipse.equinox.frameworkadmin.equinox_1.3.500.v20260928-0506.jar
|
||||
f2b956930b8383d708f1fe9df92938bffbe2e129082d4fd0b3d5f59c20a5c9f0 plugins/org.eclipse.equinox.frameworkadmin_2.3.600.v20260306-0554.jar
|
||||
8e889f92718fb8c612dd358265da2c94738bbc08b46473b81cad36f1177a8235 plugins/org.eclipse.equinox.launcher.cocoa.macosx.aarch64_1.2.1700.v20260913-1737.jar
|
||||
347674eb3d3d4000c184573618241141297fb9586c8f65ebdbacace59b8c81a2 plugins/org.eclipse.equinox.launcher.cocoa.macosx.x86_64_1.2.1700.v20260913-1737.jar
|
||||
57e8a4b46906751e214dfa8fab1e02462c40ad4e51f2226d9ef70af5f0941ccb plugins/org.eclipse.equinox.launcher.gtk.linux.aarch64_1.2.1700.v20260913-1737.jar
|
||||
d0e7418232627c53288e566728d24d1578650514152992b87f82a5d982429606 plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.2.1700.v20260913-1737.jar
|
||||
aa8c31a082b25b87f75008548f6544379174c98091934fb8399e3f917a0445f1 plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.3.200.v20260913-1737.jar
|
||||
9b3b1da60813ac5fa09dd5c198f1884be7076d0a5daec54faa3f351a787e34b7 plugins/org.eclipse.equinox.launcher_1.8.0.v20260804-1928.jar
|
||||
fd04e81a28ab32b6bb073286eb293c44b760176fcf1e35ef15614d62df820f86 plugins/org.eclipse.equinox.preferences_3.12.100.v20251111-0704.jar
|
||||
9b149d3367d33fc1f9a19d3f87c425ecf9fc235ee748b3cf200ec387169b042b plugins/org.eclipse.equinox.registry_3.12.700.v20260830-1519.jar
|
||||
60388d163f70329c39a9cf4e32389ec4fba8dc80ae5518d97cd0be2ebb971510 plugins/org.eclipse.equinox.security.linux_1.2.0.v20260914-1851.jar
|
||||
a8408d4bcdc70e019d2d89ed8b1b0413eb74ea73e74fa3d064b7401643539797 plugins/org.eclipse.equinox.security.macosx_1.102.500.v20250521-0414.jar
|
||||
cf9668c1d1e481059366abc2719468aa52e1276475cf9c32d4d10f57b34d7182 plugins/org.eclipse.equinox.security.win32_1.3.0.v20240419-2334.jar
|
||||
91b74719f9c1a130193407808fe5daab3b92431efbf30b8f886f1ff5e97f468f plugins/org.eclipse.equinox.security_1.4.700.v20250622-1644.jar
|
||||
1a24a3c0fb01ad71f97432d5c2b364d9868b5a5ebd99a1308aacb1a2c03c47da plugins/org.eclipse.equinox.simpleconfigurator.manipulator_2.3.700.v20260306-0556.jar
|
||||
d250938d3715529a9822fcdf46ad2f5de39720558d7195b5c1a8713af00bcd13 plugins/org.eclipse.equinox.simpleconfigurator_1.5.700.v20251111-1031.jar
|
||||
db9a4e856bb4728a2719df544b0f2ccef52b54ebf4e643a417fdb471f85703c1 plugins/org.eclipse.equinox.spi_1.0.0.v20261009-1945.jar
|
||||
7615ee7abdd14695957a52864c57869018dc10ddaac80d3cd24b6a97e05d0d9f plugins/org.eclipse.jdt.apt.core_3.8.1000.v20261012-1009.jar
|
||||
ea365808514a22c2e5a1a3fe0b9c07b88a371094d5d5716d31906a8818d56b2a plugins/org.eclipse.jdt.apt.pluggable.core_1.4.800.v20260930-1106.jar
|
||||
f667bb3666d9875a2309fa2447a19e6cdd960281473bd7125a22c5a435246d21 plugins/org.eclipse.jdt.core.compiler.batch_3.46.200.v20261008-1115.jar
|
||||
a6d0f8fabd64c248c37c463789a1a13f801252b68b0a4f4808c207677b5cae17 plugins/org.eclipse.jdt.core.javac_1.0.0.z20260430-1959.jar
|
||||
8ea98fcbecbd89f311849e448f4c4274a2aba5e15cfcdcad29951330c40e0ee8 plugins/org.eclipse.jdt.core.manipulation_1.26.0.v20261009-1526.jar
|
||||
70b4bb168aab096ee7f33da7b72f470f4172fe3e18e80289dd89cf344937ed22 plugins/org.eclipse.jdt.core_3.48.0.v20261007-1246.jar
|
||||
12113df750bb22f7ef0dd3f044f7c334feecd55ddb56b9340529899c55f5893b plugins/org.eclipse.jdt.debug_3.27.0.v20261012-1250.jar
|
||||
f140fad97dc5c452af0cb0f87ed3c6c83ff518f1dda49a43b8b9bec07f17d0fd plugins/org.eclipse.jdt.junit.core_3.16.0.v20261008-2002.jar
|
||||
4ea3fe4a12a0e1e8b10b7ce3f577a0ff4f5115c6a5e40364c53b8b329a8505b0 plugins/org.eclipse.jdt.junit.runtime_3.8.200.v20260911-1643.jar
|
||||
8b928263817f5dd0a9210a8842682903f779dc83253fea501591e150e5303095 plugins/org.eclipse.jdt.launching_3.25.0.v20261010-0421.jar
|
||||
6e5e5e39d82e9ac04925e8b3f432ef6fe81284441e99952d2f720779c9e2831b plugins/org.eclipse.jdt.ls.core_1.63.0.202610191322.jar
|
||||
666cc544f8a63e41d2dc8e6f3626071214027e4f698dea5bf36137f85477bba4 plugins/org.eclipse.jdt.ls.filesystem_1.63.0.202610191322.jar
|
||||
792f7df214d4ab5e4915ac1805922d44de61ebb880f1fc4881ecd4ecfdca6aca plugins/org.eclipse.jdt.ls.logback.appender_1.63.0.202610191322.jar
|
||||
9647feb0524bf763c878e12ab878a684102b81cccb3f77feecbec709d54f9bbb plugins/org.eclipse.lsp4j.jsonrpc_1.0.0.v20260209-1721.jar
|
||||
ccd78893facc6bfcc359d56cba05d3d5b85eb41e4c40d4b4215ca45db5f416d9 plugins/org.eclipse.lsp4j_1.0.0.v20260209-1721.jar
|
||||
a5d6bdc3e6f5017f19375697c7a5929fbc83f5734f35d5ed4540c7b2c843d4bb plugins/org.eclipse.ltk.core.refactoring_3.17.0.v20261010-1449.jar
|
||||
69d1b41401686fd99337e1ddd8aeec309255ae464393ca19a8025c85bfae6601 plugins/org.eclipse.m2e.apt.core_2.3.200.20260815-0704.jar
|
||||
34872f7712dffca0b39804708c0c1b58f2f2576e27cb7176b92a1ea437d384e6 plugins/org.eclipse.m2e.core_2.8.0.20260815-0704.jar
|
||||
8c3fa36fe9f62ace897b0196df8e6bba6a50610c186f6689ada5f386a8b223b1 plugins/org.eclipse.m2e.jdt_2.5.300.20260813-1359.jar
|
||||
5c5b419a101210127f21fa7d37bd2605b90f96efe9d3e91ea31099fb243dec8e plugins/org.eclipse.m2e.maven.runtime_3.9.1601.20260722-2149.jar
|
||||
53376fa2d7bfd2d5166806e74af9576ee3f8f1c1ac916e2cb4d2bb0c3e72c02f plugins/org.eclipse.m2e.workspace.cli_0.4.0.jar
|
||||
20e09b8f88845480b6ad0b89ac001679b6713592cd0ee4bd78cdb326172eee62 plugins/org.eclipse.osgi.compatibility.state_1.3.100.v20260909-1123.jar
|
||||
fe66fd0b071bebc7e1a122be571ed8ecde373d2966fa6b1e161a899b3c7a054d plugins/org.eclipse.osgi_3.25.0.v20261008-2211.jar
|
||||
2714e0c7548a0c23ab99d4e84b68d3e67419bbd6b295efda15d881e7cb173a1c plugins/org.eclipse.search.core_3.17.0.v20261010-1449.jar
|
||||
0ca3b552c867619285b8ae36c7defdd6c0f013e692643d433fd111796da55f19 plugins/org.eclipse.text_3.14.900.v20261012-1310.jar
|
||||
c6c2b8593cd39c279e74e7055cbd146d39dc6f16011961b4928b92728d32d00d plugins/org.eclipse.xtext.xbase.lib_2.44.0.v20260824-1228.jar
|
||||
ea7a53f8b7966039c6f7d54f462cbbaaad38a5e313a4e7d9125fa39640988725 plugins/org.gradle.toolingapi_9.7.1.v20260923-0232-s.jar
|
||||
5d66b6a4a680755cb6ed7cb104fa7835ef644667586ff0737adeb977c39ecdbc plugins/org.hamcrest_3.0.0.jar
|
||||
e9d8c856856680427f096d156f02a414289985c930998fcb519ce5be39b42003 plugins/org.jsoup_1.23.2.jar
|
||||
3efac657139b0b8024748e937e3e1dba71fbdf69fb526c60f504a3fb5490381b plugins/org.junit_4.13.2.v20240929-1000.jar
|
||||
ed825d10ab1399c8c0cb669e688cf0c8c82629b4c8399b58352b68e92ca10fcb plugins/org.objectweb.asm_9.10.1.jar
|
||||
0653852deab5c6f6e9c84e3aa8f72e72b9ce7dfaf7a6431f3d80f6f9d7a433ad plugins/org.osgi.service.component_1.5.1.202212101352.jar
|
||||
43c7c870710e363405d422da653cce0d798a4537f76e4930f79bceadd3a55345 plugins/org.osgi.service.prefs_1.1.2.202109301733.jar
|
||||
208819c7c71690c15a6bb8b187474e7f9d0147946b680182a62b9f222ae014ec plugins/org.osgi.util.function_1.2.0.202109301733.jar
|
||||
7053c57e7d7d88fec6b90979a3af125e1d2bb847268a328a2f1ed65ad0a4c185 plugins/org.osgi.util.promise_1.3.0.202212101352.jar
|
||||
7e1446499b359675d8aabe6af2de86b85e72ae8a2a932c0b40d0e5ba57097439 plugins/slf4j.api_2.0.20.jar
|
||||
3970dab20b4deb8380ed9656392f289f3f3c2ee882d8c3942f1b5b486284620d plugins/wrapped.com.jetbrains.intellij.java.java-decompiler-engine_253.29346.240.jar
|
||||
65d87386b7e926c0b6fb330a8d2eb6a987f5949634f7574731c0a3c2329d5629 plugins/wrapped.com.vladsch.flexmark.flexmark-ext-emoji_0.64.8.jar
|
||||
7a350f43f858da8f4a230552607ced119aeaf97484ca11ce4cd792e1e41e5bf7 plugins/wrapped.com.vladsch.flexmark.flexmark-ext-gfm-strikethrough_0.64.8.jar
|
||||
7a424dae7df0ee86200a08e163d9d1d8f63cd7a1a0c980b84ccbec029571fb4e plugins/wrapped.com.vladsch.flexmark.flexmark-ext-ins_0.64.8.jar
|
||||
75a2e7168145f799a039832708aa0bc277a954c4a367f58711ccd6b9b7e7d04e plugins/wrapped.com.vladsch.flexmark.flexmark-ext-superscript_0.64.8.jar
|
||||
dbe6355ea9e04731d534d3d4151870f83684c7a44c87d541a2c53ef5ee2c4fa4 plugins/wrapped.com.vladsch.flexmark.flexmark-ext-tables_0.64.8.jar
|
||||
91ae2f77e832d20607fad5b7f407d438ca3f16ac032b4f14956e4e7eb3a60931 plugins/wrapped.com.vladsch.flexmark.flexmark-ext-wikilink_0.64.8.jar
|
||||
0b650a4b47d29ffe0a08802c5d58e2270f733ce5443420c0e8904cfa1605964f plugins/wrapped.com.vladsch.flexmark.flexmark-html2md-converter_0.64.8.jar
|
||||
74bab2d767f48f930471c9a72a0c3b89e9073549ad3754e6b7f83f09585463bc plugins/wrapped.com.vladsch.flexmark.flexmark-jira-converter_0.64.8.jar
|
||||
1c7d205afeef618760a5fa907d579835df625ee258cbebd49813f14c2254a535 plugins/wrapped.com.vladsch.flexmark.flexmark-util-ast_0.64.8.jar
|
||||
9179310212700753a4ecdc7aa057a04591b9cfdb089787a248e8269c34740310 plugins/wrapped.com.vladsch.flexmark.flexmark-util-builder_0.64.8.jar
|
||||
796b9acec9af0fa290725a14be8a3fc1d6fe7a9cb518a13f67124b5172a3485b plugins/wrapped.com.vladsch.flexmark.flexmark-util-collection_0.64.8.jar
|
||||
20458c20bc72808e1718ff8f1652272bbb32f62ddaecb2e9a0ddc84d77fd7283 plugins/wrapped.com.vladsch.flexmark.flexmark-util-data_0.64.8.jar
|
||||
b59fbc922e3604442ff6aae1c6b83220245ba4c3f89d38870bc28c982b69d01d plugins/wrapped.com.vladsch.flexmark.flexmark-util-dependency_0.64.8.jar
|
||||
b6073ee177aa2476d64787f9ec813fdb881943d402c195df0631ba672bfb1311 plugins/wrapped.com.vladsch.flexmark.flexmark-util-format_0.64.8.jar
|
||||
c892e6cdbba715c55462decbe1c83cec432548cf2877cfd0715975c44dfab55c plugins/wrapped.com.vladsch.flexmark.flexmark-util-html_0.64.8.jar
|
||||
1726c33ee95f77cfadc58c8ad27949ed72653f4045fbc399aff62827b44c7fcd plugins/wrapped.com.vladsch.flexmark.flexmark-util-misc_0.64.8.jar
|
||||
cd0f9212530aa73f67de94d080018b2c3a3a55d41050d3abb4be8afb69989be0 plugins/wrapped.com.vladsch.flexmark.flexmark-util-options_0.64.8.jar
|
||||
340167af15da00e3ae5fb89d6b44751abfd648951bb6d2e05c48287d9f9e70c9 plugins/wrapped.com.vladsch.flexmark.flexmark-util-sequence_0.64.8.jar
|
||||
a8fad4a006411d020624c7539e6145e97920067844acddc10b019a178a680948 plugins/wrapped.com.vladsch.flexmark.flexmark-util-visitor_0.64.8.jar
|
||||
792c13bc5536704fc0bfba9120e5bac712843a7ae6da6104b1392b382feaf63d plugins/wrapped.com.vladsch.flexmark.flexmark-util_0.64.8.jar
|
||||
a2ec63056bcfe8c4babc62f13f5f49b502fccccf7c011b5d4ba7dd93f4d09393 plugins/wrapped.com.vladsch.flexmark.flexmark_0.64.8.jar
|
||||
482b6aade7b0320e28db530a22f1382b3d30addf26a5ffd55a347f5c32f6dfc2 plugins/wrapped.org.jetbrains.annotations_24.0.1.jar
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Reproducible bundle build: python3 build.py /path/to/jdtls (JDT LS 1.63.0, Java 25; target Java 21)."""
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
|
||||
root = pathlib.Path(__file__).resolve().parent
|
||||
plugins = pathlib.Path(sys.argv[1]).resolve() / 'plugins'
|
||||
with tempfile.TemporaryDirectory() as out:
|
||||
subprocess.run(['java', '-cp', str(plugins / '*'),
|
||||
'org.eclipse.jdt.internal.compiler.batch.Main', '-21', '-proc:none',
|
||||
'-classpath', os.pathsep.join(str(p) for p in sorted(plugins.glob('*.jar'))),
|
||||
'-d', out, *[str(p) for p in sorted((root / 'src').rglob('*.java'))]], check=True)
|
||||
with zipfile.ZipFile(root / 'openidea-java-usages.jar', 'w', zipfile.ZIP_DEFLATED) as jar:
|
||||
files = {'META-INF/MANIFEST.MF': root / 'MANIFEST.MF', 'plugin.xml': root / 'plugin.xml'}
|
||||
files.update({str(p.relative_to(out)): p for p in pathlib.Path(out).rglob('*.class')})
|
||||
for name, path in sorted(files.items()):
|
||||
jar.writestr(zipfile.ZipInfo(name, (2026, 1, 1, 0, 0, 0)), path.read_bytes())
|
||||
Бінарний файл не відображається.
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<plugin>
|
||||
<extension point="org.eclipse.jdt.ls.core.delegateCommandHandler">
|
||||
<delegateCommandHandler class="ai.openidea.usages.UsagesCommand">
|
||||
<command id="openidea.java.usages"/>
|
||||
</delegateCommandHandler>
|
||||
</extension>
|
||||
</plugin>
|
||||
@@ -0,0 +1,146 @@
|
||||
package ai.openidea.usages;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.eclipse.core.runtime.IProgressMonitor;
|
||||
import org.eclipse.core.runtime.OperationCanceledException;
|
||||
import org.eclipse.jdt.core.*;
|
||||
import org.eclipse.jdt.core.dom.*;
|
||||
import org.eclipse.jdt.ls.core.internal.JDTUtils;
|
||||
import org.eclipse.lsp4j.Location;
|
||||
|
||||
/** Structural access context for already semantically bound search results.
|
||||
* One syntax parse per source file per query; no second reference search.
|
||||
*/
|
||||
final class UsageAccess {
|
||||
private record Parsed(ICompilationUnit unit, String source, CompilationUnit tree, Map<Long, ASTNode> exactNodes) {}
|
||||
private final Map<String, Parsed> files = new HashMap<>();
|
||||
private final IProgressMonitor monitor;
|
||||
private final Map<String, List<Location>> requests = new HashMap<>();
|
||||
UsageAccess(IProgressMonitor monitor, Map<Location, String> results) {
|
||||
this.monitor = monitor;
|
||||
results.forEach((location, kind) -> {
|
||||
if (!kind.equals("unknown")) requests.computeIfAbsent(location.getUri(), k -> new ArrayList<>()).add(location);
|
||||
});
|
||||
}
|
||||
|
||||
private static long rangeKey(int start, int length) { return ((long) start << 32) | (length & 0xffffffffL); }
|
||||
|
||||
private Map<Long, ASTNode> index(CompilationUnit tree, String uri) {
|
||||
List<Location> locations = requests.get(uri);
|
||||
// A few lookups do not justify traversing an entire file. Index exact AST
|
||||
// and selector-to-call-end ranges; all other ranges retain NodeFinder.
|
||||
if (locations == null || locations.size() < 16) return Map.of();
|
||||
var wanted = new HashSet<Long>();
|
||||
for (Location location : locations) {
|
||||
var range = location.getRange();
|
||||
int start = tree.getPosition(range.getStart().getLine() + 1, range.getStart().getCharacter());
|
||||
int end = tree.getPosition(range.getEnd().getLine() + 1, range.getEnd().getCharacter());
|
||||
if (start >= 0 && end > start) wanted.add(rangeKey(start, end - start));
|
||||
}
|
||||
Map<Long, ASTNode> nodes = new HashMap<>();
|
||||
tree.accept(new ASTVisitor(true) {
|
||||
int visited;
|
||||
@Override public void preVisit(ASTNode node) {
|
||||
if ((visited++ & 127) == 0 && monitor.isCanceled()) throw new OperationCanceledException();
|
||||
int start = node.getStartPosition();
|
||||
long end = (long) start + node.getLength();
|
||||
add(rangeKey(start, node.getLength()), node);
|
||||
// JDT method matches may start at the selector (after receiver)
|
||||
// and end after the arguments. That span is covered by this call,
|
||||
// but not by any of its children. It is not a method reference.
|
||||
SimpleName name = node instanceof MethodInvocation call ? call.getName() :
|
||||
node instanceof SuperMethodInvocation call ? call.getName() : null;
|
||||
if (name != null && end <= Integer.MAX_VALUE && name.getLength() > 0 &&
|
||||
(name.getFlags() & (ASTNode.MALFORMED | ASTNode.RECOVERED)) == 0 &&
|
||||
name.getStartPosition() >= start && end > (long) name.getStartPosition() + name.getLength())
|
||||
add(rangeKey(name.getStartPosition(), (int) (end - name.getStartPosition())), node);
|
||||
}
|
||||
private void add(long key, ASTNode node) {
|
||||
if (!wanted.contains(key)) return;
|
||||
if (nodes.containsKey(key)) {
|
||||
if (nodes.get(key) != node) nodes.put(key, null);
|
||||
return;
|
||||
}
|
||||
boolean contained = true;
|
||||
for (ASTNode parent = node; parent != null; parent = parent.getParent()) {
|
||||
if ((parent.getFlags() & (ASTNode.MALFORMED | ASTNode.RECOVERED)) != 0 ||
|
||||
parent.getStartPosition() > node.getStartPosition() ||
|
||||
(long) parent.getStartPosition() + parent.getLength() < (long) node.getStartPosition() + node.getLength()) {
|
||||
contained = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
nodes.put(key, contained ? node : null);
|
||||
}
|
||||
});
|
||||
return nodes;
|
||||
}
|
||||
|
||||
String classify(Location location, String kind) {
|
||||
if (kind.equals("unknown")) return "unknown";
|
||||
if (monitor.isCanceled()) throw new OperationCanceledException();
|
||||
try {
|
||||
String uri = location.getUri();
|
||||
if (!files.containsKey(uri)) {
|
||||
Parsed parsed = null;
|
||||
ITypeRoot root = JDTUtils.resolveTypeRoot(uri);
|
||||
if (root instanceof ICompilationUnit unit && unit.getResource() != null) {
|
||||
String source = unit.getBuffer().getContents();
|
||||
ASTParser parser = ASTParser.newParser(AST.getJLSLatest());
|
||||
parser.setSource(source.toCharArray());
|
||||
parser.setCompilerOptions(unit.getJavaProject().getOptions(true));
|
||||
// SearchEngine has already resolved the target identity. Here only
|
||||
// expression structure is needed; do not resolve the project again.
|
||||
CompilationUnit tree = (CompilationUnit) parser.createAST(monitor);
|
||||
parsed = new Parsed(unit, source, tree, index(tree, uri));
|
||||
}
|
||||
files.put(uri, parsed);
|
||||
}
|
||||
Parsed file = files.get(uri);
|
||||
if (file == null || !file.source.equals(file.unit.getBuffer().getContents())) return "unknown";
|
||||
var range = location.getRange();
|
||||
int start = file.tree.getPosition(range.getStart().getLine() + 1, range.getStart().getCharacter());
|
||||
int end = file.tree.getPosition(range.getEnd().getLine() + 1, range.getEnd().getCharacter());
|
||||
if (start < 0 || end < start) return "unknown";
|
||||
ASTNode node = file.exactNodes.get(rangeKey(start, end - start));
|
||||
if (node == null) node = NodeFinder.perform(file.tree, start, end - start);
|
||||
if (node == null || (node.getFlags() & (ASTNode.MALFORMED | ASTNode.RECOVERED)) != 0) return "unknown";
|
||||
if (kind.equals("getter") || kind.equals("setter")) {
|
||||
for (ASTNode p = node; p != null; p = p.getParent()) {
|
||||
if (p instanceof MethodReference) return "unknown";
|
||||
if (p instanceof MethodInvocation || p instanceof SuperMethodInvocation)
|
||||
return kind.equals("getter") ? "read" : "write";
|
||||
if (p instanceof Statement || p instanceof BodyDeclaration) break;
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
if (!(node instanceof SimpleName name) || name.isDeclaration()) return "unknown";
|
||||
ASTNode expression = node;
|
||||
while (true) {
|
||||
ASTNode parent = expression.getParent();
|
||||
if (parent instanceof QualifiedName q && q.getName() == expression ||
|
||||
parent instanceof FieldAccess f && f.getName() == expression ||
|
||||
parent instanceof SuperFieldAccess f && f.getName() == expression ||
|
||||
parent instanceof ParenthesizedExpression p && p.getExpression() == expression) {
|
||||
expression = parent;
|
||||
} else break;
|
||||
}
|
||||
ASTNode parent = expression.getParent();
|
||||
if (parent instanceof Assignment a && a.getLeftHandSide() == expression)
|
||||
return a.getOperator() == Assignment.Operator.ASSIGN ? "write" : "readWrite";
|
||||
if (parent instanceof PostfixExpression) return "readWrite";
|
||||
if (parent instanceof PrefixExpression p && (p.getOperator() == PrefixExpression.Operator.INCREMENT ||
|
||||
p.getOperator() == PrefixExpression.Operator.DECREMENT)) return "readWrite";
|
||||
return "read";
|
||||
} catch (OperationCanceledException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
// A missing/changed/unparseable document must remain visible, never guessed.
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package ai.openidea.usages;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.eclipse.core.runtime.IProgressMonitor;
|
||||
import org.eclipse.jdt.core.*;
|
||||
import org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil;
|
||||
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
|
||||
import org.eclipse.jdt.ls.core.internal.JDTUtils;
|
||||
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
|
||||
import org.eclipse.jdt.ls.core.internal.handlers.ReferencesHandler;
|
||||
import org.eclipse.lsp4j.*;
|
||||
|
||||
/** Classifies search results using JDT method identities, never reference text. */
|
||||
public final class UsagesCommand implements IDelegateCommandHandler {
|
||||
@Override
|
||||
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) throws Exception {
|
||||
String uri = (String) arguments.get(0);
|
||||
int line = ((Number) arguments.get(1)).intValue();
|
||||
int column = ((Number) arguments.get(2)).intValue();
|
||||
boolean declarations = Boolean.TRUE.equals(arguments.get(3));
|
||||
var preferences = JavaLanguageServerPlugin.getPreferencesManager();
|
||||
var handler = new ReferencesHandler(preferences);
|
||||
var params = new ReferenceParams(new TextDocumentIdentifier(uri), new Position(line, column), new ReferenceContext(declarations));
|
||||
Map<Location, String> results = new LinkedHashMap<>();
|
||||
ITypeRoot root = JDTUtils.resolveTypeRoot(uri);
|
||||
IJavaElement selected = root == null ? null :
|
||||
JDTUtils.findElementAtSelection(root, line, column, preferences, monitor);
|
||||
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
|
||||
boolean accessors = preferences.getPreferences().isIncludeAccessors();
|
||||
SearchPlan plan = new SearchPlan();
|
||||
// Only replace native target discovery for the exact implementation verified by
|
||||
// integration tests. New server implementations retain their full native behavior.
|
||||
if (selected instanceof IField field && root instanceof ICompilationUnit &&
|
||||
root.getResource() != null && NATIVE_PLAN_SUPPORTED) {
|
||||
plan.add(field, "field", declarations);
|
||||
if (accessors) {
|
||||
plan.add(GetterSetterUtil.getGetter(field), "getter", false);
|
||||
plan.add(GetterSetterUtil.getSetter(field), "setter", false);
|
||||
addNativeBuilderTargets(handler, field, plan);
|
||||
addConfiguredAccessors(field, plan);
|
||||
}
|
||||
} else {
|
||||
// Includes non-fields, library/decompiled roots, and unverified JDT LS builds.
|
||||
for (var location : handler.findReferences(params, monitor)) results.put(location, "unknown");
|
||||
if (selected instanceof IField field) {
|
||||
plan.add(field, "field", declarations);
|
||||
if (accessors) {
|
||||
plan.add(GetterSetterUtil.getGetter(field), "getter", false);
|
||||
plan.add(GetterSetterUtil.getSetter(field), "setter", false);
|
||||
addConfiguredAccessors(field, plan);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (var target : plan.targets.values()) {
|
||||
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
|
||||
add(handler, target.element, target.kind(), target.declarations, results, monitor);
|
||||
}
|
||||
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
|
||||
List<Map<String, Object>> response = new ArrayList<>();
|
||||
UsageAccess access = new UsageAccess(monitor, results);
|
||||
results.forEach((location, kind) -> response.add(Map.of("location", location, "kind", kind, "access", access.classify(location, kind))));
|
||||
return response;
|
||||
}
|
||||
|
||||
/** Resolve explicit Lombok @Accessors naming, then search exact JDT method identities.
|
||||
* Configuration-file-only naming is deliberately not guessed.
|
||||
*/
|
||||
private static void addConfiguredAccessors(IField field, SearchPlan plan) throws Exception {
|
||||
Boolean fluent = null;
|
||||
boolean configured = false;
|
||||
String[] prefixes = null;
|
||||
// Field annotations override enclosing type annotations, as Lombok does.
|
||||
List<IAnnotatable> owners = new ArrayList<>();
|
||||
owners.add(field);
|
||||
for (IType type = field.getDeclaringType(); type != null; type = type.getDeclaringType()) owners.add(type);
|
||||
for (IAnnotatable owner : owners) {
|
||||
for (IAnnotation annotation : owner.getAnnotations()) {
|
||||
String name = annotation.getElementName();
|
||||
if (!name.equals("Accessors") && !name.equals("lombok.experimental.Accessors")) continue;
|
||||
String[][] resolved = field.getDeclaringType().resolveType(name);
|
||||
if (!name.equals("lombok.experimental.Accessors") && (resolved == null || resolved.length != 1 ||
|
||||
!resolved[0][0].equals("lombok.experimental") || !resolved[0][1].equals("Accessors"))) continue;
|
||||
configured = true;
|
||||
for (IMemberValuePair pair : annotation.getMemberValuePairs()) {
|
||||
if (pair.getMemberName().equals("fluent") && fluent == null && pair.getValue() instanceof Boolean value) fluent = value;
|
||||
if (pair.getMemberName().equals("prefix") && prefixes == null) {
|
||||
Object value = pair.getValue();
|
||||
if (value instanceof String prefix) prefixes = new String[] { prefix };
|
||||
else if (value instanceof Object[] values) {
|
||||
prefixes = new String[values.length];
|
||||
for (int i = 0; i < values.length; i++) prefixes[i] = (String) values[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!configured) return;
|
||||
String name = field.getElementName();
|
||||
if (prefixes != null && prefixes.length > 0) {
|
||||
String stripped = null;
|
||||
for (String prefix : prefixes) {
|
||||
if (prefix.isEmpty()) { stripped = name; break; }
|
||||
if (!name.startsWith(prefix) || name.length() == prefix.length()) continue;
|
||||
char next = name.charAt(prefix.length());
|
||||
if (Character.isLetter(prefix.charAt(prefix.length() - 1)) && Character.isLowerCase(next)) continue;
|
||||
stripped = Character.toLowerCase(next) + name.substring(prefix.length() + 1);
|
||||
break;
|
||||
}
|
||||
if (stripped == null) return;
|
||||
name = stripped;
|
||||
}
|
||||
String signature = field.getTypeSignature();
|
||||
String getterName = name;
|
||||
String setterName = name;
|
||||
if (!Boolean.TRUE.equals(fluent)) {
|
||||
boolean bool = signature.equals(Signature.SIG_BOOLEAN);
|
||||
String base = name;
|
||||
if (bool && base.startsWith("is") && base.length() > 2 && Character.isUpperCase(base.charAt(2))) base = base.substring(2);
|
||||
String capital = Character.toUpperCase(base.charAt(0)) + base.substring(1);
|
||||
getterName = (bool ? "is" : "get") + capital;
|
||||
setterName = "set" + capital;
|
||||
}
|
||||
for (IMethod method : field.getDeclaringType().getMethods()) {
|
||||
if (Flags.isStatic(method.getFlags()) != Flags.isStatic(field.getFlags())) continue;
|
||||
if (method.getElementName().equals(getterName) && method.getNumberOfParameters() == 0 && method.getReturnType().equals(signature)) {
|
||||
plan.add(method, "getter", false);
|
||||
} else if (method.getElementName().equals(setterName) && method.getNumberOfParameters() == 1 && method.getParameterTypes()[0].equals(signature) && setterReturnType(method)) {
|
||||
plan.add(method, "setter", false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final boolean NATIVE_PLAN_SUPPORTED = nativePlanSupported();
|
||||
|
||||
private static boolean nativePlanSupported() {
|
||||
// JDT LS 1.63.0.202610191322 ReferencesHandler.class. Fingerprinting guards
|
||||
// against silently dropping new native search targets in future versions.
|
||||
try (var stream = ReferencesHandler.class.getResourceAsStream("ReferencesHandler.class")) {
|
||||
if (stream == null) return false;
|
||||
String digest = java.util.HexFormat.of().formatHex(
|
||||
java.security.MessageDigest.getInstance("SHA-256").digest(stream.readAllBytes()));
|
||||
return digest.equals("31ff5a10c7d69d58c6a9b619ef17e3ec41b11b545751ba428618a76cc1341064");
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void addNativeBuilderTargets(ReferencesHandler handler, IField field, SearchPlan plan) throws Exception {
|
||||
// Reuse the verified server's own builder naming (including custom names).
|
||||
var resolver = ReferencesHandler.class.getDeclaredMethod("getBuilderName", IField.class);
|
||||
resolver.setAccessible(true);
|
||||
String name = (String) resolver.invoke(handler, field);
|
||||
IType builder = field.getJavaProject().findType(name);
|
||||
if (builder == null) return;
|
||||
for (IMethod method : builder.getMethods()) {
|
||||
String[] parameters = method.getParameterTypes();
|
||||
if (parameters.length == 1 && field.getElementName().equals(method.getElementName()) &&
|
||||
field.getTypeSignature().equals(parameters[0])) plan.add(method, "unknown", false);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class SearchTarget {
|
||||
final IJavaElement element;
|
||||
final java.util.Set<String> kinds = new java.util.HashSet<>();
|
||||
boolean declarations;
|
||||
SearchTarget(IJavaElement element) { this.element = element; }
|
||||
String kind() { return kinds.size() == 1 ? kinds.iterator().next() : "unknown"; }
|
||||
}
|
||||
|
||||
private static final class SearchPlan {
|
||||
final Map<IJavaElement, SearchTarget> targets = new LinkedHashMap<>();
|
||||
void add(IJavaElement element, String kind, boolean declarations) {
|
||||
if (element == null) return;
|
||||
SearchTarget target = targets.computeIfAbsent(element, SearchTarget::new);
|
||||
if (!kind.equals("unknown")) target.kinds.add(kind);
|
||||
target.declarations |= declarations;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean setterReturnType(IMethod method) throws JavaModelException {
|
||||
String result = method.getReturnType();
|
||||
if (result.equals(Signature.SIG_VOID)) return true;
|
||||
String name = Signature.toString(Signature.getTypeErasure(result));
|
||||
IType owner = method.getDeclaringType();
|
||||
if (name.equals(owner.getFullyQualifiedName())) return true;
|
||||
String[][] resolved = owner.resolveType(name);
|
||||
return resolved != null && resolved.length == 1 &&
|
||||
(resolved[0][0].isEmpty() ? resolved[0][1] : resolved[0][0] + "." + resolved[0][1]).equals(owner.getFullyQualifiedName());
|
||||
}
|
||||
|
||||
private static void add(ReferencesHandler handler, IJavaElement element, String kind, boolean declarations,
|
||||
Map<Location, String> results, IProgressMonitor monitor) throws Exception {
|
||||
if (element == null) return;
|
||||
List<Location> locations = new ArrayList<>();
|
||||
handler.search(element, locations, monitor, declarations);
|
||||
for (var location : locations) {
|
||||
if (kind.equals("unknown")) { results.putIfAbsent(location, kind); continue; }
|
||||
String previous = results.get(location);
|
||||
results.put(location, previous == null || previous.equals("unknown") || previous.equals(kind) ? kind : "unknown");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
# Reproduce Java usage access filtering
|
||||
|
||||
## Small fixture
|
||||
|
||||
Use [ReadWrite.java](ReadWrite.java), a 24-line Java/Lombok fixture. It contains
|
||||
ordinary `@Data`, explicit fluent `@Accessors`, direct field reads/writes,
|
||||
compound updates, nested calls, inherited/interface calls and method references.
|
||||
Its line positions are assertions in `read-write.py`; keep them stable.
|
||||
|
||||
For manual testing, create a Java project with Lombok 1.18.48 on its classpath
|
||||
and copy this file into its source directory as `Bean.java`. For Maven, use JDK
|
||||
21 or later and this minimal `pom.xml`:
|
||||
|
||||
```xml
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>example</groupId><artifactId>usage-access</artifactId><version>1.0</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId><artifactId>lombok</artifactId>
|
||||
<version>1.18.48</version><scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build><plugins><plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.14.1</version>
|
||||
<configuration><release>21</release><annotationProcessorPaths><path>
|
||||
<groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.48</version>
|
||||
</path></annotationProcessorPaths></configuration>
|
||||
</plugin></plugins></build>
|
||||
</project>
|
||||
```
|
||||
|
||||
Open the project in OpenIDEA, allow JDT LS import/indexing to finish and verify
|
||||
there are no Java error diagnostics. Leave `java.references.includeAccessors`
|
||||
enabled. Invoke Show Usages on the **declaration** of `Bean.count` (Cmd-click on
|
||||
macOS, or the corresponding navigation action). Use the declaration to avoid
|
||||
navigating from a reference to its definition instead.
|
||||
|
||||
## Before and after
|
||||
|
||||
On unmodified main, the references appear together and cannot be filtered by
|
||||
read/write access. Standard LSP references provide locations without this metadata.
|
||||
With this change, both toolbar buttons are initially selected:
|
||||
|
||||
| Expression | Access | Read only | Write only |
|
||||
| ---------------------------------------- | ---------- | --------- | ---------- |
|
||||
| `b.count` in an initializer | Read | Visible | Hidden |
|
||||
| `b.count = 1` | Write | Hidden | Visible |
|
||||
| `b.count += 2`, `b.count++`, `--b.count` | Read/write | Visible | Visible |
|
||||
| `b.getCount()` | Read | Visible | Hidden |
|
||||
| `b.setCount(...)` | Write | Hidden | Visible |
|
||||
| `b::getCount`, `b::setCount` | Unknown | Visible | Visible |
|
||||
|
||||
The two references in `b.setCount(b.getCount())` remain distinct even on one
|
||||
line. Inherited and interface calls are included. Selecting `Fluent.score`
|
||||
also includes `score()` and `score(int)` by method identity. `b.items[0] = 1`
|
||||
reads `items`; it writes an element, not the field holding the array.
|
||||
|
||||
Turn off Show write accesses to inspect reads. Turn it back on and turn off Show
|
||||
read accesses to inspect writes. Turning off the last enabled switch enables the
|
||||
other. Move the results to Find: filters and original location metadata remain
|
||||
available. Reopen the popup to check persistence. Unknown results must stay
|
||||
visible in either mode. English tooltips are "Show read accesses" and "Show write
|
||||
accesses"; the icons are vendored JetBrains resources, not a claim of complete UI
|
||||
parity.
|
||||
|
||||
## Automated server evidence and desktop checks
|
||||
|
||||
The harness creates an Eclipse project with the same fixture, loads the actual
|
||||
Lombok agent and extension, imports it in JDT LS, asserts semantic results and
|
||||
checks cancellation. No Maven download is needed for this harness.
|
||||
|
||||
```sh
|
||||
export PATH=/path/to/jdk25/bin:$PATH
|
||||
python3 plugins/java-usages/tests/read-write.py /path/to/jdtls /path/to/lombok.jar > /tmp/read-write.json
|
||||
```
|
||||
|
||||
Then launch the desktop app with `pnpm tauri dev` and open the same Java/Lombok
|
||||
fixture. Check Read only, Write only, both toggles and Open in Find Window. The
|
||||
chosen mode and exact source ranges must survive transfer. Select a Java access
|
||||
mode, then run a non-Java search: it must show a plain count and no access toolbar.
|
||||
Repeat Java usages in a project with a marked source root. Confirm import and
|
||||
indexing have completed before comparing results.
|
||||
|
||||
For a desktop before/after demonstration use separate builds of the base and PR
|
||||
with this same fixture, settings and import completion state.
|
||||
|
||||
## Scope and performance interpretation
|
||||
|
||||
This does not classify constructor initialization. Method references stay unknown,
|
||||
and `lombok.config`-only naming or unusual signatures may remain unmapped.
|
||||
See the parent README for internal API compatibility and conservative fallback.
|
||||
|
||||
A true no-feature timing baseline must omit this bundle entirely while retaining
|
||||
the same Lombok agent, then call `textDocument/references` directly. Compare the
|
||||
same query position, settings, server/compiler, fixture and import state. Measure
|
||||
cold first queries separately from warmed samples. RPC timings exclude UI and
|
||||
Rust orchestration. Fluent/prefixed fields may return fewer locations natively;
|
||||
those timings are not equal-workload comparisons and cannot establish a semantic
|
||||
speedup. Counter-instrumented runs must be separate from timing runs.
|
||||
@@ -0,0 +1,24 @@
|
||||
import lombok.*;
|
||||
import lombok.experimental.Accessors;
|
||||
interface Counter { int getCount(); void setCount(int value); }
|
||||
@Data class Bean implements Counter { public int count; public Bean next; public int[] items; }
|
||||
class Child extends Bean {}
|
||||
@Data @Accessors(fluent=true, chain=true) class Fluent { public int score; }
|
||||
class Use {
|
||||
void uses(Bean b, Child c, Counter i, Fluent f) {
|
||||
int read = b.count; // read
|
||||
b.count = 1; // write
|
||||
b.count += 2; // readWrite
|
||||
b.count++; // readWrite
|
||||
--b.count; // readWrite
|
||||
b.setCount(b.getCount()); // setter write, getter read; nested invocation ranges
|
||||
c.setCount(c.getCount()); // inherited
|
||||
i.setCount(i.getCount()); // interface
|
||||
java.util.function.IntSupplier ref = b::getCount; // unknown
|
||||
java.util.function.IntConsumer writeRef = b::setCount; // unknown
|
||||
f.score = f.score(); // field write, fluent read
|
||||
f.score(f.score()); // fluent setter write, getter read
|
||||
b.items[0] = 1; // reading array field, writing element
|
||||
b.next.count = 2; // reading receiver field, writing count
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Run actual JDT LS + Lombok integration test. Arguments: jdtls home, lombok jar."""
|
||||
import os
|
||||
import hashlib
|
||||
import zipfile
|
||||
import json
|
||||
import pathlib
|
||||
import platform
|
||||
import queue
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
home, lombok = map(lambda p: pathlib.Path(p).resolve(), sys.argv[1:3])
|
||||
bundle = pathlib.Path(__file__).resolve().parents[1] / 'openidea-java-usages.jar'
|
||||
work = pathlib.Path(tempfile.mkdtemp(prefix='openidea-usages-'))
|
||||
config = work / 'config'
|
||||
config.mkdir()
|
||||
system, machine = platform.system(), platform.machine().lower()
|
||||
config_name = {'Windows': 'config_win', 'Darwin': 'config_mac'}.get(system, 'config_linux')
|
||||
config_names = ([config_name + '_arm'] if machine in ('arm64', 'aarch64') else []) + [config_name]
|
||||
config_source = next(home / name / 'config.ini' for name in config_names
|
||||
if (home / name / 'config.ini').is_file())
|
||||
(config / 'config.ini').write_bytes(config_source.read_bytes())
|
||||
project = work / 'project'
|
||||
project.mkdir()
|
||||
(project / 'src').mkdir()
|
||||
(project / '.project').write_text('<projectDescription><name>accessors</name><buildSpec><buildCommand><name>org.eclipse.jdt.core.javabuilder</name></buildCommand></buildSpec><natures><nature>org.eclipse.jdt.core.javanature</nature></natures></projectDescription>')
|
||||
(project / '.classpath').write_text(f'<classpath><classpathentry kind="src" path="src"/><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="lib" path="{lombok}"/><classpathentry kind="output" path="bin"/></classpath>')
|
||||
source = (pathlib.Path(__file__).parent / 'ReadWrite.java').read_text()
|
||||
index_stress = os.environ.get('OPENIDEA_USAGES_INDEX_STRESS') == '1'
|
||||
if index_stress:
|
||||
# Keep the original nested/method-reference cases, but cross the index threshold
|
||||
# for both standard and fluent accessors without changing their expected rows.
|
||||
source = source[:-len(' }\n}\n')] + (' b.getCount(); b.setCount(0); f.score(); f.score(0);' * 12) + '\n }\n}\n'
|
||||
source += 'class More extends Bean { void calls() { super.setCount(super.getCount()); } }\n'
|
||||
file = project / 'src/Bean.java'
|
||||
file.write_text(source)
|
||||
log = (work / 'stderr.log').open('w')
|
||||
proc = subprocess.Popen(['java', f'-javaagent:{lombok}', '-Declipse.application=org.eclipse.jdt.ls.core.id1', '-Dosgi.bundles.defaultStartLevel=4', '-Declipse.product=org.eclipse.jdt.ls.core.product', '-Xmx1G', '--add-modules=ALL-SYSTEM', '--add-opens', 'java.base/java.util=ALL-UNNAMED', '--add-opens', 'java.base/java.lang=ALL-UNNAMED', '-jar', str(next((home/'plugins').glob('org.eclipse.equinox.launcher_*.jar'))), '-configuration', str(config), '-data', str(work/'metadata')], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log)
|
||||
messages = queue.Queue()
|
||||
lock = threading.Lock()
|
||||
def send(message):
|
||||
data = json.dumps(message).encode()
|
||||
with lock:
|
||||
proc.stdin.write(f'Content-Length: {len(data)}\r\n\r\n'.encode() + data)
|
||||
proc.stdin.flush()
|
||||
def read():
|
||||
while True:
|
||||
headers = {}
|
||||
while True:
|
||||
line = proc.stdout.readline()
|
||||
if not line: return
|
||||
if line == b'\r\n': break
|
||||
k,v = line.decode().split(':', 1)
|
||||
headers[k.lower()] = v.strip()
|
||||
message = json.loads(proc.stdout.read(int(headers['content-length'])))
|
||||
if 'method' in message and 'id' in message:
|
||||
send({'jsonrpc':'2.0', 'id':message['id'], 'result': [] if message['method']=='workspace/configuration' else None})
|
||||
else: messages.put(message)
|
||||
threading.Thread(target=read, daemon=True).start()
|
||||
seq = 0
|
||||
transcript = []
|
||||
def request(method, params):
|
||||
global seq
|
||||
seq += 1
|
||||
send({'jsonrpc':'2.0', 'id':seq, 'method':method, 'params':params})
|
||||
deadline = time.monotonic() + 180
|
||||
while time.monotonic() < deadline:
|
||||
msg = messages.get(timeout=max(1, deadline-time.monotonic()))
|
||||
transcript.append(msg)
|
||||
if msg.get('id') == seq:
|
||||
if 'error' in msg: raise RuntimeError(msg['error'])
|
||||
return msg.get('result')
|
||||
raise TimeoutError(method)
|
||||
try:
|
||||
init = request('initialize', {'processId':None, 'rootUri':project.as_uri(), 'workspaceFolders':[{'uri':project.as_uri(), 'name':'accessors'}], 'capabilities':{}, 'initializationOptions':{'bundles':[str(bundle)], 'settings':{'java':{'references':{'includeAccessors':True}, 'import':{'gradle':{'enabled':False}, 'maven':{'enabled':False}}}}}})
|
||||
send({'jsonrpc':'2.0','method':'initialized','params':{}})
|
||||
send({'jsonrpc':'2.0','method':'textDocument/didOpen','params':{'textDocument':{'uri':file.as_uri(), 'languageId':'java','version':1,'text':source}}})
|
||||
request('java/buildWorkspace', True)
|
||||
evidence = {'workspace':str(work), 'source':source, 'lombokSha256':hashlib.sha256(lombok.read_bytes()).hexdigest(), 'lombokManifest':zipfile.ZipFile(lombok).read('META-INF/MANIFEST.MF').decode(), 'jdtls':next((home/'plugins').glob('org.eclipse.jdt.ls.core_*.jar')).name, 'commands':init.get('capabilities', {}).get('executeCommandProvider'), 'cases':{}}
|
||||
evidence['cases']={}
|
||||
for field in ['count','score','items','next']:
|
||||
line,text=next((i,t) for i,t in enumerate(source.splitlines()) if f'public int {field};' in t or f'public int[] {field};' in t or f'public Bean {field};' in t)
|
||||
col=text.index(field)
|
||||
evidence['cases'][field]=request('workspace/executeCommand',{'command':'openidea.java.usages','arguments':[file.as_uri(),line,col,False]})
|
||||
errors=[d for m in transcript if m.get('method')=='textDocument/publishDiagnostics' for d in m['params']['diagnostics'] if d.get('severity')==1]
|
||||
assert not errors, errors
|
||||
expected={8:['read'],9:['write'],10:['readWrite'],11:['readWrite'],12:['readWrite'],13:['read','write'],14:['read','write'],15:['read','write'],16:['unknown'],17:['unknown'],21:['write']}
|
||||
if index_stress:
|
||||
expected[22]=['read','write']*12
|
||||
expected[len(source.splitlines())-1]=['read','write']
|
||||
actual={}
|
||||
for row in evidence['cases']['count']:
|
||||
actual.setdefault(row['location']['range']['start']['line'],[]).append(row['access'])
|
||||
for line,accesses in expected.items(): assert sorted(actual.get(line,[]))==sorted(accesses),(line,actual)
|
||||
assert [r['access'] for r in evidence['cases']['items']]==['read'],evidence['cases']['items']
|
||||
assert [r['access'] for r in evidence['cases']['next']]==['read'],evidence['cases']['next']
|
||||
scores={}
|
||||
for row in evidence['cases']['score']: scores.setdefault(row['location']['range']['start']['line'],[]).append(row['access'])
|
||||
expected_scores={18:['read','write'],19:['read','write']}
|
||||
if index_stress: expected_scores[22]=sorted(['read','write']*12)
|
||||
assert {l:sorted(a) for l,a in scores.items()}==expected_scores,scores
|
||||
# Exercise the real JSON-RPC cancellation path separately from assertions
|
||||
# about successful responses. Send cancellation immediately after dispatch.
|
||||
line,text=next((i,t) for i,t in enumerate(source.splitlines()) if 'public int count;' in t)
|
||||
seq += 1
|
||||
send({'jsonrpc':'2.0','id':seq,'method':'workspace/executeCommand','params':{'command':'openidea.java.usages','arguments':[file.as_uri(),line,text.index('count'),False]}})
|
||||
send({'jsonrpc':'2.0','method':'$/cancelRequest','params':{'id':seq}})
|
||||
deadline=time.monotonic()+30
|
||||
while True:
|
||||
message=messages.get(timeout=max(.1,deadline-time.monotonic()))
|
||||
transcript.append(message)
|
||||
if message.get('id')==seq:
|
||||
evidence['cancellation']=message
|
||||
assert message.get('error',{}).get('code') == -32800, message
|
||||
break
|
||||
assert time.monotonic()<deadline, 'Cancellation response timed out'
|
||||
evidence['assertions']='direct field read/write/readWrite, nested calls, inherited/interface, method references unknown, fluent, array/receiver reads passed'
|
||||
(work/'evidence.json').write_text(json.dumps(evidence, indent=2))
|
||||
print(json.dumps(evidence, indent=2))
|
||||
finally:
|
||||
(work/'transcript.json').write_text(json.dumps(transcript, indent=2))
|
||||
proc.terminate()
|
||||
proc.wait(timeout=20)
|
||||
print('Evidence:', work, file=sys.stderr)
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Run actual JDT LS + Lombok integration test. Arguments: jdtls home, lombok jar."""
|
||||
import hashlib
|
||||
import zipfile
|
||||
import json
|
||||
import pathlib
|
||||
import platform
|
||||
import queue
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
home, lombok = map(lambda p: pathlib.Path(p).resolve(), sys.argv[1:3])
|
||||
bundle = pathlib.Path(__file__).resolve().parents[1] / 'openidea-java-usages.jar'
|
||||
work = pathlib.Path(tempfile.mkdtemp(prefix='openidea-usages-'))
|
||||
config = work / 'config'
|
||||
config.mkdir()
|
||||
system, machine = platform.system(), platform.machine().lower()
|
||||
config_name = {'Windows': 'config_win', 'Darwin': 'config_mac'}.get(system, 'config_linux')
|
||||
config_names = ([config_name + '_arm'] if machine in ('arm64', 'aarch64') else []) + [config_name]
|
||||
config_source = next(home / name / 'config.ini' for name in config_names
|
||||
if (home / name / 'config.ini').is_file())
|
||||
(config / 'config.ini').write_bytes(config_source.read_bytes())
|
||||
project = work / 'project'
|
||||
project.mkdir()
|
||||
(project / 'src').mkdir()
|
||||
(project / '.project').write_text('<projectDescription><name>accessors</name><buildSpec><buildCommand><name>org.eclipse.jdt.core.javabuilder</name></buildCommand></buildSpec><natures><nature>org.eclipse.jdt.core.javanature</nature></natures></projectDescription>')
|
||||
(project / '.classpath').write_text(f'<classpath><classpathentry kind="src" path="src"/><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="lib" path="{lombok}"/><classpathentry kind="output" path="bin"/></classpath>')
|
||||
source = '''import lombok.Data;
|
||||
@Data
|
||||
class Bean {
|
||||
private String name;
|
||||
private boolean active;
|
||||
void direct() { name = "direct"; System.out.println(name); }
|
||||
}
|
||||
@Data
|
||||
@lombok.experimental.Accessors(fluent=true, chain=true, prefix="m")
|
||||
class Fluent {
|
||||
private String mTitle;
|
||||
}
|
||||
@Data
|
||||
@lombok.experimental.Accessors(chain=true, prefix="m")
|
||||
class Prefixed {
|
||||
private String mLabel;
|
||||
}
|
||||
class Manual {
|
||||
private int size;
|
||||
public int getSize() { return size; }
|
||||
public void setSize(int value) { size = value; }
|
||||
public void setSize(String unrelated) {}
|
||||
}
|
||||
class Child extends Manual {}
|
||||
@Data
|
||||
@lombok.experimental.Accessors(fluent=true)
|
||||
class NotSetter {
|
||||
private String value;
|
||||
public int value(String x) { return 1; }
|
||||
}
|
||||
class Use {
|
||||
void unrelated(NotSetter n) { n.value("not a setter"); }
|
||||
void manual(Manual m, Child c) { m.setSize(m.getSize()); System.out.println(c.getSize()); m.setSize("unrelated"); }
|
||||
void prefixed(Prefixed p) { p.setLabel(p.getLabel()); }
|
||||
void fluent(Fluent f) { f.title(f.title()); }
|
||||
void calls(Bean b) { b.setName(b.getName()); b.setActive(b.isActive()); }
|
||||
java.util.function.Supplier<String> getter(Bean b) { return b::getName; }
|
||||
java.util.function.Consumer<String> setter(Bean b) { return b::setName; }
|
||||
}
|
||||
'''
|
||||
file = project / 'src/Bean.java'
|
||||
file.write_text(source)
|
||||
log = (work / 'stderr.log').open('w')
|
||||
proc = subprocess.Popen(['java', f'-javaagent:{lombok}', '-Declipse.application=org.eclipse.jdt.ls.core.id1', '-Dosgi.bundles.defaultStartLevel=4', '-Declipse.product=org.eclipse.jdt.ls.core.product', '-Xmx1G', '--add-modules=ALL-SYSTEM', '--add-opens', 'java.base/java.util=ALL-UNNAMED', '--add-opens', 'java.base/java.lang=ALL-UNNAMED', '-jar', str(next((home/'plugins').glob('org.eclipse.equinox.launcher_*.jar'))), '-configuration', str(config), '-data', str(work/'metadata')], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log)
|
||||
messages = queue.Queue()
|
||||
lock = threading.Lock()
|
||||
def send(message):
|
||||
data = json.dumps(message).encode()
|
||||
with lock:
|
||||
proc.stdin.write(f'Content-Length: {len(data)}\r\n\r\n'.encode() + data)
|
||||
proc.stdin.flush()
|
||||
def read():
|
||||
while True:
|
||||
headers = {}
|
||||
while True:
|
||||
line = proc.stdout.readline()
|
||||
if not line: return
|
||||
if line == b'\r\n': break
|
||||
k,v = line.decode().split(':', 1)
|
||||
headers[k.lower()] = v.strip()
|
||||
message = json.loads(proc.stdout.read(int(headers['content-length'])))
|
||||
if 'method' in message and 'id' in message:
|
||||
send({'jsonrpc':'2.0', 'id':message['id'], 'result': [] if message['method']=='workspace/configuration' else None})
|
||||
else: messages.put(message)
|
||||
threading.Thread(target=read, daemon=True).start()
|
||||
seq = 0
|
||||
transcript = []
|
||||
def request(method, params):
|
||||
global seq
|
||||
seq += 1
|
||||
send({'jsonrpc':'2.0', 'id':seq, 'method':method, 'params':params})
|
||||
deadline = time.monotonic() + 180
|
||||
while time.monotonic() < deadline:
|
||||
msg = messages.get(timeout=max(1, deadline-time.monotonic()))
|
||||
transcript.append(msg)
|
||||
if msg.get('id') == seq:
|
||||
if 'error' in msg: raise RuntimeError(msg['error'])
|
||||
return msg.get('result')
|
||||
raise TimeoutError(method)
|
||||
try:
|
||||
init = request('initialize', {'processId':None, 'rootUri':project.as_uri(), 'workspaceFolders':[{'uri':project.as_uri(), 'name':'accessors'}], 'capabilities':{}, 'initializationOptions':{'bundles':[str(bundle)], 'settings':{'java':{'references':{'includeAccessors':True}, 'import':{'gradle':{'enabled':False}, 'maven':{'enabled':False}}}}}})
|
||||
send({'jsonrpc':'2.0','method':'initialized','params':{}})
|
||||
send({'jsonrpc':'2.0','method':'textDocument/didOpen','params':{'textDocument':{'uri':file.as_uri(), 'languageId':'java','version':1,'text':source}}})
|
||||
request('java/buildWorkspace', True)
|
||||
evidence = {'workspace':str(work), 'source':source, 'lombokSha256':hashlib.sha256(lombok.read_bytes()).hexdigest(), 'lombokManifest':zipfile.ZipFile(lombok).read('META-INF/MANIFEST.MF').decode(), 'jdtls':next((home/'plugins').glob('org.eclipse.jdt.ls.core_*.jar')).name, 'commands':init.get('capabilities', {}).get('executeCommandProvider'), 'cases':{}}
|
||||
for field, expected in [('name',(2,2,2)), ('active',(1,1,0)), ('mTitle',(1,1,0)), ('mLabel',(1,1,0)), ('size',(2,1,2)), ('value',(0,0,0))]:
|
||||
line, text = next((i, t) for i,t in enumerate(source.splitlines()) if 'private ' in t and f' {field};' in t)
|
||||
col = text.index(field)
|
||||
before = request('textDocument/references', {'textDocument':{'uri':file.as_uri()},'position':{'line':line,'character':col},'context':{'includeDeclaration':False}})
|
||||
after = request('workspace/executeCommand', {'command':'openidea.java.usages','arguments':[file.as_uri(),line,col,False]})
|
||||
evidence['cases'][field] = {'before':before,'after':after}
|
||||
assert all(any(row['location'] == loc for row in after) for loc in before), 'lost standard references'
|
||||
kinds = [r['kind'] for r in after]
|
||||
assert kinds.count('getter') == expected[0], (field, kinds)
|
||||
assert kinds.count('setter') == expected[1], (field, kinds)
|
||||
assert kinds.count('field') == expected[2], (field, kinds)
|
||||
# Respect the existing global preference: the command must not switch it on.
|
||||
send({'jsonrpc':'2.0','method':'workspace/didChangeConfiguration','params':{'settings':{'java':{'references':{'includeAccessors':False}}}}})
|
||||
disabled = request('workspace/executeCommand', {'command':'openidea.java.usages','arguments':[file.as_uri(),3,19,False]})
|
||||
assert len(disabled) == 2 and all(r['kind'] == 'field' for r in disabled), disabled
|
||||
evidence['accessorsDisabled'] = disabled
|
||||
(work/'evidence.json').write_text(json.dumps(evidence, indent=2))
|
||||
print(json.dumps(evidence, indent=2))
|
||||
finally:
|
||||
(work/'transcript.json').write_text(json.dumps(transcript, indent=2))
|
||||
proc.terminate()
|
||||
proc.wait(timeout=20)
|
||||
print('Evidence:', work, file=sys.stderr)
|
||||
@@ -0,0 +1,104 @@
|
||||
Copyright (C) 2009-2021 The Project Lombok Authors.
|
||||
|
||||
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.
|
||||
|
||||
==============================================================================
|
||||
Licenses for included components:
|
||||
|
||||
org.ow2.asm:asm
|
||||
org.ow2.asm:asm-analysis
|
||||
org.ow2.asm:asm-commons
|
||||
org.ow2.asm:asm-tree
|
||||
org.ow2.asm:asm-util
|
||||
ASM: a very small and fast Java bytecode manipulation framework
|
||||
Copyright (c) 2000-2011 INRIA, France Telecom
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
3. Neither the name of the copyright holders nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
|
||||
THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
rzwitserloot/com.zwitserloot.cmdreader
|
||||
|
||||
Copyright © 2010 Reinier Zwitserloot.
|
||||
|
||||
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.
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
|
||||
projectlombok/lombok.patcher
|
||||
|
||||
Copyright (C) 2009-2021 The Project Lombok Authors.
|
||||
|
||||
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,71 @@
|
||||
# Lombok agent for JDT LS
|
||||
|
||||
`lombok-1.18.48-openidea.1.jar` is the app-provided Java agent for JDT LS. It includes
|
||||
[projectlombok/lombok#4059](https://github.com/projectlombok/lombok/pull/4059), which restores
|
||||
`lombok.config` lookup after Equinox removed `getModuleClassLoader(boolean)`.
|
||||
|
||||
The jar is embedded by `ide-tools`, so every platform receives the same bytes without a download.
|
||||
Both Java server startup and launch diagnostics obtain it through `managed_bundle`. Tool detection
|
||||
reports the same version and path, replacing older IDE-installed official agents automatically.
|
||||
An explicit user `-javaagent` still takes precedence. Project Maven/Gradle dependencies are unchanged.
|
||||
The filename includes the patch version because JDT LS workspace keys include the agent path;
|
||||
changing agents must rebuild classes produced by the old agent. Old jars remain for running windows.
|
||||
|
||||
Replace this temporary bundle with an official Maven Central release once that release includes
|
||||
#4059. Restore the registry's Maven Central install method and remove the embedded jar. Keep the
|
||||
workspace migration test when changing its path.
|
||||
|
||||
## Provenance and build
|
||||
|
||||
- Repository: https://github.com/projectlombok/lombok
|
||||
- Base tag: `v1.18.48` (`b48657c83ce44d027984f539bd36048293ce5e8e`).
|
||||
- Cherry-picked commits from PR #4059, in order:
|
||||
- `2d535482a913de46c27d06c5b0b294918ede3f9c`
|
||||
- `3098f4dd78b5349c2f382e7310e64db810dd380b`
|
||||
- Upstream version: `1.18.48`; `openidea.1` identifies this distribution of the patched agent.
|
||||
Upstream's own `java -jar ... --version` still reports `1.18.48`.
|
||||
- SHA-256: `10f5cd1a32b946d3ff1c075735b94f35fffdbac11dea2be29d24dbf591dd51a4`
|
||||
- License: [MIT, including bundled component notices](LICENSE), also retained inside the jar.
|
||||
- Build environment: macOS arm64, OpenJDK 23.0.1, Apache Ant 1.10.15, upstream Ivy setup.
|
||||
|
||||
Build using the upstream Ant entry point described in its contributing guide:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/projectlombok/lombok.git
|
||||
cd lombok
|
||||
git checkout -b openidea-1.18.48 v1.18.48
|
||||
git fetch https://github.com/chagong/lombok.git fix-equinox-bundle-wiring
|
||||
git cherry-pick 2d535482a913de46c27d06c5b0b294918ede3f9c 3098f4dd78b5349c2f382e7310e64db810dd380b
|
||||
ant dist
|
||||
cp dist/lombok.jar /path/to/openidea/plugins/lombok/lombok-1.18.48-openidea.1.jar
|
||||
```
|
||||
|
||||
The changelog context conflicts because the first commit adds a release-note line under the
|
||||
older development heading and the second removes it. Resolve mechanically by adding then removing
|
||||
only that line, retaining the complete v1.18.48 changelog. The final source diff from v1.18.48 changes
|
||||
only `src/eclipseAgent/lombok/launch/PatchFixesHider.java`, `test/core/src/lombok/TestEclipse.java`,
|
||||
and `test/core/src/lombok/launch/PatchFixesHiderTest.java`; no other Java source changes were made.
|
||||
In the build checkout, the two remote resolvers in
|
||||
`buildScripts/ivysettings.xml` were reordered to try Maven Central before Eclipse staging; the
|
||||
local resolver and all dependency coordinates were retained. The JVM was configured to use the
|
||||
local HTTP/HTTPS proxy for downloads. Ant's timestamps mean a rebuild need not be byte-identical;
|
||||
`SHA256SUMS` records the checked-in artifact and is verified by the Rust regression tests.
|
||||
|
||||
## Validation
|
||||
|
||||
A parent POM with DTO and application modules uses Lombok 1.18.46. Root `lombok.config` enables
|
||||
`config.stopBubbling = true` and `lombok.accessors.chain = true`.
|
||||
|
||||
On macOS arm64 with JDT LS 1.63.0 / Equinox 3.25.0, server OpenJDK 25 and project JDK 21:
|
||||
|
||||
- Official 1.18.46 and 1.18.48 agents generated `void` setters; the following Maven incremental
|
||||
build reused the DTO classes and failed with `void cannot be dereferenced`.
|
||||
- This agent passed five fresh project/workspace builds. `javap` confirmed setters returning
|
||||
the DTO class; the following Maven incremental install passed.
|
||||
- Without `lombok.config`, both official 1.18.48 and patched agents built successfully and produced
|
||||
identical `javap` output, including default `void` setters.
|
||||
- Upstream `PatchFixesHiderTest` passed both the standard OSGi and legacy Equinox lookup tests.
|
||||
|
||||
Windows and Linux runtime validation has not been performed. Rust tests cover source selection
|
||||
for both supported architectures on all three OS variants, offline provisioning, corruption
|
||||
repair, concurrent windows, explicit user overrides, and JDT LS workspace migration.
|
||||
@@ -0,0 +1 @@
|
||||
10f5cd1a32b946d3ff1c075735b94f35fffdbac11dea2be29d24dbf591dd51a4 lombok-1.18.48-openidea.1.jar
|
||||
Бінарний файл не відображається.
@@ -69,3 +69,11 @@ ide-tools = { path = "../crates/ide-tools" }
|
||||
ide-plugin = { path = "../crates/ide-plugin" }
|
||||
ide-docker = { path = "../crates/ide-docker" }
|
||||
ide-github = { path = "../crates/ide-github" }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block2 = "0.6"
|
||||
objc2 = "0.6"
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSButton", "NSResponder", "NSView", "NSWindow"] }
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] }
|
||||
# Used only by the debug font-restriction override; Cargo dependency cfg cannot test debug_assertions.
|
||||
objc2-web-kit = { version = "0.3", default-features = false, features = ["std", "WKWebViewConfiguration", "WKPreferences"] }
|
||||
@@ -0,0 +1,120 @@
|
||||
//! Debounced application activation, shared by every project window.
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use tauri::{Emitter, Manager};
|
||||
|
||||
pub const DEACTIVATED: &str = "ide://application-deactivated";
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ApplicationFocus {
|
||||
generation: AtomicU64,
|
||||
active: AtomicBool,
|
||||
}
|
||||
|
||||
impl ApplicationFocus {
|
||||
fn changed(&self, focused: bool) -> u64 {
|
||||
if focused {
|
||||
self.active.store(true, Ordering::Relaxed);
|
||||
}
|
||||
self.generation.fetch_add(1, Ordering::Relaxed) + 1
|
||||
}
|
||||
|
||||
fn deactivate(&self, generation: u64, active: bool) -> bool {
|
||||
self.generation.load(Ordering::Relaxed) == generation && !active && self.active.swap(false, Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn changed(app: &tauri::AppHandle, focused: bool) {
|
||||
let generation = app.state::<ApplicationFocus>().changed(focused);
|
||||
if focused {
|
||||
return;
|
||||
}
|
||||
let app = app.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
|
||||
let handle = app.clone();
|
||||
let _ = app.run_on_main_thread(move || {
|
||||
if handle.state::<ApplicationFocus>().deactivate(generation, application_active(&handle)) {
|
||||
let _ = handle.emit(DEACTIVATED, ());
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn observe(app: &tauri::AppHandle) {
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2_app_kit::{NSApplicationDidBecomeActiveNotification, NSApplicationDidResignActiveNotification};
|
||||
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol};
|
||||
thread_local! {
|
||||
static OBSERVERS: std::cell::RefCell<Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
for (name, focused) in
|
||||
unsafe { [(NSApplicationDidBecomeActiveNotification, true), (NSApplicationDidResignActiveNotification, false)] }
|
||||
{
|
||||
let handle = app.clone();
|
||||
let block = block2::RcBlock::new(move |_| changed(&handle, focused));
|
||||
let observer = unsafe {
|
||||
NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(
|
||||
Some(name),
|
||||
None,
|
||||
None,
|
||||
&block,
|
||||
)
|
||||
};
|
||||
OBSERVERS.with_borrow_mut(|observers| observers.push(observer));
|
||||
}
|
||||
}
|
||||
|
||||
fn application_active(app: &tauri::AppHandle) -> bool {
|
||||
// A settings window, utility window or native dialog is still this application.
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let _ = app;
|
||||
let main = objc2::MainThreadMarker::new().expect("activation is checked on the main thread");
|
||||
objc2_app_kit::NSApplication::sharedApplication(main).isActive()
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let _ = app;
|
||||
#[link(name = "user32")]
|
||||
unsafe extern "system" {
|
||||
fn GetForegroundWindow() -> *mut std::ffi::c_void;
|
||||
fn GetWindowThreadProcessId(window: *mut std::ffi::c_void, process: *mut u32) -> u32;
|
||||
}
|
||||
let mut process = 0;
|
||||
unsafe { GetWindowThreadProcessId(GetForegroundWindow(), &mut process) };
|
||||
process == std::process::id()
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
app.webview_windows().values().any(|w| w.is_focused().unwrap_or(true))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn window_and_dialog_focus_transfers_do_not_deactivate_the_application() {
|
||||
let state = ApplicationFocus::default();
|
||||
state.changed(true);
|
||||
let blur = state.changed(false);
|
||||
assert!(!state.deactivate(blur, true));
|
||||
state.changed(true);
|
||||
assert!(!state.deactivate(blur, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debounce_emits_once_for_an_external_application_and_skips_stale_checks() {
|
||||
let state = ApplicationFocus::default();
|
||||
state.changed(true);
|
||||
let stale = state.changed(false);
|
||||
let latest = state.changed(false);
|
||||
assert!(!state.deactivate(stale, false));
|
||||
assert!(state.deactivate(latest, false));
|
||||
assert!(!state.deactivate(latest, false));
|
||||
state.changed(true);
|
||||
let latest = state.changed(false);
|
||||
assert!(state.deactivate(latest, false));
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,25 @@
|
||||
//! The OS clipboard's file list, so the project view and Explorer exchange files.
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use crate::commands::doc::blocking;
|
||||
#[cfg(target_os = "macos")]
|
||||
use ide_core::IdeError;
|
||||
use ide_core::IdeResult;
|
||||
use std::path::{Path, PathBuf};
|
||||
use tauri::AppHandle;
|
||||
|
||||
/// Absolute paths on the clipboard, empty when it holds no file list.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn clipboard_file_list() -> IdeResult<Vec<String>> {
|
||||
blocking(|| Ok(ide_clipboard::files().iter().map(|p| slash(p)).collect())).await
|
||||
pub async fn clipboard_file_list(app: AppHandle) -> IdeResult<Vec<String>> {
|
||||
with_clipboard(app, || Ok(ide_clipboard::files()?.iter().map(|p| slash(p)).collect())).await
|
||||
}
|
||||
|
||||
/// Whether the clipboard holds files: cheap, for the Paste item's enabled state.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn clipboard_has_files() -> bool {
|
||||
// Synchronous Tauri commands run on the main thread, as macOS requires.
|
||||
ide_clipboard::has_files()
|
||||
}
|
||||
|
||||
@@ -22,8 +27,30 @@ pub fn clipboard_has_files() -> bool {
|
||||
/// false when the clipboard stayed busy; the caller keeps working either way.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn clipboard_set_file_list(paths: Vec<PathBuf>) -> IdeResult<bool> {
|
||||
blocking(move || Ok(ide_clipboard::set_files(&paths))).await
|
||||
pub async fn clipboard_set_file_list(app: AppHandle, paths: Vec<PathBuf>) -> IdeResult<bool> {
|
||||
with_clipboard(app, move || Ok(ide_clipboard::set_files(&paths))).await
|
||||
}
|
||||
|
||||
/// AppKit and WebKit share the general pasteboard, so a worker-side mutex cannot
|
||||
/// protect its type cache. Await the main thread without blocking a command thread.
|
||||
async fn with_clipboard<T: Send + 'static>(
|
||||
app: AppHandle,
|
||||
f: impl FnOnce() -> IdeResult<T> + Send + 'static,
|
||||
) -> IdeResult<T> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
app.run_on_main_thread(move || {
|
||||
let _ = tx.send(f());
|
||||
})
|
||||
.map_err(|error| IdeError::internal(format!("Cannot dispatch clipboard access to the main thread: {error}")))?;
|
||||
rx.await.map_err(|error| IdeError::internal(format!("Clipboard main-thread task was dropped: {error}")))?
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
let _ = app;
|
||||
blocking(f).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Paths cross the IPC boundary `/`-separated, as every other backend path does.
|
||||
|
||||
@@ -13,3 +13,13 @@ pub async fn system_font_families(refresh: bool) -> IdeResult<Vec<FontFamily>> {
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
}
|
||||
|
||||
/// Raw font bundle, selected by family, never by a frontend-supplied path.
|
||||
#[tauri::command]
|
||||
pub async fn user_font_data(family: String) -> IdeResult<tauri::ipc::Response> {
|
||||
tauri::async_runtime::spawn_blocking(move || ide_fonts::user_font_data(&family))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
.map(tauri::ipc::Response::new)
|
||||
.map_err(|e| IdeError::invalid(e.to_string()))
|
||||
}
|
||||
@@ -5,6 +5,38 @@ use ide_vfs::FileEntry;
|
||||
use std::path::PathBuf;
|
||||
use tauri::{State, Window};
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn fs_entry_kind(state: State<'_, AppState>, path: PathBuf) -> IdeResult<ide_vfs::EntryKind> {
|
||||
fs::entry_kind(&state.host, path).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn fs_compare_directories(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
left: PathBuf,
|
||||
right: PathBuf,
|
||||
request: ide_core::RequestId,
|
||||
on_progress: tauri::ipc::Channel<ide_vfs::DirectoryCompareProgress>,
|
||||
) -> IdeResult<Vec<ide_vfs::DirectoryCompareEntry>> {
|
||||
fs::compare_directories(&state.host, window.label(), left, right, request, super::sender(on_progress)).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn fs_copy_merge(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
source_root: PathBuf,
|
||||
destination_root: PathBuf,
|
||||
path: PathBuf,
|
||||
overwrite: bool,
|
||||
) -> IdeResult<()> {
|
||||
fs::copy_merge(&state.host, window.label(), source_root, destination_root, path, overwrite).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn fs_read_dir(window: Window, state: State<'_, AppState>, path: PathBuf) -> IdeResult<Vec<FileEntry>> {
|
||||
|
||||
@@ -95,8 +95,8 @@ pub async fn lsp_implementations(
|
||||
ide_host::ops::lsp::lsp_implementations(&state.host, window.label(), request, doc, positions).await
|
||||
}
|
||||
|
||||
/// Contents of a virtual document (library class, decompiled code) that a
|
||||
/// language server returned a non-`file:` URI for. Cached per project.
|
||||
/// Contents of a read-only language-server document, including JDT library
|
||||
/// classes and disk class files. Cached per project.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn lsp_virtual_document(
|
||||
@@ -107,6 +107,16 @@ pub async fn lsp_virtual_document(
|
||||
ide_host::ops::lsp::lsp_virtual_document(&state.host, window.label(), uri).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn lsp_resolve_class_file(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
path: std::path::PathBuf,
|
||||
) -> IdeResult<String> {
|
||||
ide_host::ops::lsp::lsp_resolve_class_file(&state.host, window.label(), path).await
|
||||
}
|
||||
|
||||
/// References of the symbol at `pos`. `project_wide` also searches project files
|
||||
/// outside the language server's analysis scope; bulk scans over many symbols
|
||||
/// leave it off. Cancel with `cancel_request(request)`.
|
||||
@@ -343,3 +353,30 @@ pub async fn lsp_execute_command(
|
||||
) -> IdeResult<()> {
|
||||
ide_host::ops::lsp::lsp_execute_command(&state.host, window.label(), doc, command).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn lsp_resolve_command(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
server: ServerId,
|
||||
command: Command,
|
||||
answers: Vec<FormAnswer>,
|
||||
) -> IdeResult<Option<CommandForm>> {
|
||||
ide_host::ops::lsp::lsp_resolve_command(&state.host, window.label(), request, doc, server, command, answers).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn lsp_execute_code_action(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
action: CodeAction,
|
||||
answers: Vec<FormAnswer>,
|
||||
) -> IdeResult<Vec<ide_core::IpcPath>> {
|
||||
ide_host::ops::lsp::lsp_execute_code_action(&state.host, window.label(), request, doc, action, answers).await
|
||||
}
|
||||
@@ -126,6 +126,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
notebook::notebook_interrupt,
|
||||
notebook::notebook_restart,
|
||||
fs::fs_read_dir,
|
||||
fs::fs_entry_kind,
|
||||
bytes::fs_probe,
|
||||
bytes::fs_read_range,
|
||||
bytes::fs_read_image,
|
||||
@@ -136,6 +137,8 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
fs::fs_set_writable,
|
||||
fs::fs_delete,
|
||||
fs::fs_copy,
|
||||
fs::fs_copy_merge,
|
||||
fs::fs_compare_directories,
|
||||
fs::fs_read_text,
|
||||
clipboard::clipboard_file_list,
|
||||
clipboard::clipboard_has_files,
|
||||
@@ -201,6 +204,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
lsp::lsp_goto,
|
||||
lsp::lsp_implementations,
|
||||
lsp::lsp_virtual_document,
|
||||
lsp::lsp_resolve_class_file,
|
||||
lsp::lsp_references,
|
||||
lsp::lsp_document_highlights,
|
||||
lsp::lsp_workspace_symbols,
|
||||
@@ -222,6 +226,8 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
lsp::lsp_restart,
|
||||
lsp::apply_workspace_edit,
|
||||
lsp::lsp_execute_command,
|
||||
lsp::lsp_resolve_command,
|
||||
lsp::lsp_execute_code_action,
|
||||
vcs::vcs_status,
|
||||
vcs::vcs_roots,
|
||||
vcs::vcs_branch_info,
|
||||
@@ -271,6 +277,8 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
vcs::vcs_add_worktree,
|
||||
vcs::vcs_remove_worktree,
|
||||
vcs::vcs_diff_with_worktree,
|
||||
vcs::vcs_compare_scope,
|
||||
vcs::vcs_compare_paths,
|
||||
vcs::vcs_diff_revisions,
|
||||
vcs::vcs_merge_base,
|
||||
vcs::vcs_create_patch,
|
||||
@@ -309,6 +317,8 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
run::run_tomcat_home,
|
||||
run::run_tomcat_artifacts,
|
||||
run::run_tomcat_build,
|
||||
run::run_application_build,
|
||||
run::run_application_publish,
|
||||
run::run_tomcat_update,
|
||||
run::run_test_reports,
|
||||
build::build_model,
|
||||
@@ -356,6 +366,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
window::window_open_settings,
|
||||
window::window_cycle,
|
||||
window::window_toggle_fullscreen,
|
||||
window::window_set_titlebar_height,
|
||||
window::window_take_launch,
|
||||
window::window_close_context,
|
||||
window::window_open_projects,
|
||||
@@ -476,6 +487,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
crate::remote_dev::remote_current,
|
||||
crate::remote_dev::remote_disconnect,
|
||||
crate::remote_dev::remote_invoke,
|
||||
crate::remote_dev::remote_import_local,
|
||||
env::env_reload,
|
||||
db::db_test,
|
||||
db::db_connected,
|
||||
|
||||
@@ -8,6 +8,29 @@ use ide_run::{OutputChunk, RunConfig, RunInfo};
|
||||
use tauri::ipc::Channel;
|
||||
use tauri::{State, Window};
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn run_application_build(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
config: RunConfig,
|
||||
module: std::path::PathBuf,
|
||||
) -> IdeResult<RunConfig> {
|
||||
ide_host::ops::run::run_application_build(&state.host, window.label(), config, module).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn run_application_publish(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
config: RunConfig,
|
||||
class_paths: Vec<String>,
|
||||
main_class: String,
|
||||
) -> IdeResult<()> {
|
||||
ide_host::ops::run::run_application_publish(&state.host, window.label(), config, class_paths, main_class).await
|
||||
}
|
||||
|
||||
/// Detected configs followed by user-defined ones (user ids win on conflict).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
|
||||
Loaded 100 of 305 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача