From 55a4ab55d6af2390492b53a7cec4a399eaaf516e Mon Sep 17 00:00:00 2001 From: Li <2188718831@qq.com> Date: Tue, 1 Dec 2026 04:27:57 +0000 Subject: [PATCH 1/2] feat(toolchains): discover JDKs on fixed Windows drives Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- Cargo.lock | 4 +- backend/Cargo.toml | 6 +- backend/src/lib.rs | 5 + backend/src/toolchain_provider.rs | 395 ++++++++++++++++++ backend/tests/repository_pins.rs | 25 ++ backend/tests/session.rs | 37 +- compiler-host.json | 4 +- contract.lock.json | 8 +- docs/feature-matrix.md | 6 + io.github.lithe-idea.java-support/plugin.json | 11 +- sdk.lock.json | 2 +- 11 files changed, 491 insertions(+), 12 deletions(-) create mode 100644 backend/src/toolchain_provider.rs diff --git a/Cargo.lock b/Cargo.lock index 474e357..a5e44ee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -401,6 +401,7 @@ dependencies = [ "serde_json", "sha2", "url", + "windows-sys", "xmltree", "zip", ] @@ -424,9 +425,10 @@ dependencies = [ [[package]] name = "lithe-plugin-sdk" version = "0.4.0" -source = "git+https://github.com/Lithe-IDEA/Lithe-core-rust?rev=65cf82343c5e315aae2e335b2e8f0217b703e89a#65cf82343c5e315aae2e335b2e8f0217b703e89a" +source = "git+https://github.com/Lithe-IDEA/Lithe-core-rust?rev=a1a792a5a3b2284720d3209b7a9c93394c365c18#a1a792a5a3b2284720d3209b7a9c93394c365c18" dependencies = [ "base64", + "serde", "serde_json", ] diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 4e77f0b..0458ec1 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -15,7 +15,7 @@ path = "src/main.rs" lithe-java-domain = { path = "../crates/java-domain" } # SDK source is pinned to the Viva baseline's exact Core commit. SDK 0.4.0 # has no release tag yet; sdk.lock.json and Cargo.lock must name the same commit. -lithe-plugin-sdk = { git = "https://github.com/Lithe-IDEA/Lithe-core-rust", rev = "65cf82343c5e315aae2e335b2e8f0217b703e89a" } +lithe-plugin-sdk = { git = "https://github.com/Lithe-IDEA/Lithe-core-rust", rev = "a1a792a5a3b2284720d3209b7a9c93394c365c18" } serde_json.workspace = true base64 = "0.22.1" zip.workspace = true @@ -26,6 +26,10 @@ sha2.workspace = true java-properties = "2.0.0" xmltree = { version = "0.12.0", features = ["attribute-order"] } jsonc-parser = { version = "0.34.0", features = ["cst", "serde"] } + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem", "Win32_System_WindowsProgramming"] } + [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/backend/src/lib.rs b/backend/src/lib.rs index 606084b..ccae90a 100644 --- a/backend/src/lib.rs +++ b/backend/src/lib.rs @@ -62,6 +62,7 @@ pub mod project_settings; pub mod run; pub mod settings_session; pub mod settings_view; +pub mod toolchain_provider; pub mod web_facet; use crate::launch::LAUNCH_FUNCTION_ID; @@ -298,6 +299,10 @@ pub fn backend() -> Result { move |params, context| settings_view::view_function(&view_session, params, context), )?; backend.suppress_success_diagnostics(settings_view::SETTINGS_VIEW_FUNCTION_ID)?; + backend.toolchain_provider( + toolchain_provider::PROVIDER_ID, + toolchain_provider::query_installations, + )?; Ok(backend) } diff --git a/backend/src/toolchain_provider.rs b/backend/src/toolchain_provider.rs new file mode 100644 index 0000000..3045ad8 --- /dev/null +++ b/backend/src/toolchain_provider.rs @@ -0,0 +1,395 @@ +//! Installation facts the Java tool cannot declare as fixed discovery roots. +//! +//! Windows users can install a JDK on another fixed drive. The declarative +//! scans name only the system drive, so this provider enumerates fixed drive +//! roots itself and applies the same vendor-directory rules to each one. + +use lithe_plugin_sdk::toolchains::{ + ToolchainInstallation, ToolchainQuery, ToolchainQueryError, ToolchainQueryResult, + ToolchainWorkspace, +}; +use lithe_plugin_sdk::Cancellation; +use std::fs; +use std::io::Read; +use std::path::{Path, PathBuf}; + +pub const PROVIDER_ID: &str = "installs"; +const JAVA_TOOL: &str = "java"; +const MAX_INSTALLATIONS: usize = 64; +const MAX_ROOT_ENTRIES: usize = 4096; + +struct VendorScan { + directory: &'static str, + jdk_prefix_only: bool, +} + +const VENDOR_SCANS: &[VendorScan] = &[ + VendorScan { + directory: "Java", + jdk_prefix_only: false, + }, + VendorScan { + directory: "Eclipse Adoptium", + jdk_prefix_only: false, + }, + VendorScan { + directory: "Microsoft", + jdk_prefix_only: true, + }, + VendorScan { + directory: "Zulu", + jdk_prefix_only: false, + }, + VendorScan { + directory: "Amazon Corretto", + jdk_prefix_only: false, + }, + VendorScan { + directory: "BellSoft", + jdk_prefix_only: false, + }, +]; + +/// Answers one host query. The provider currently has facts only for Windows; +/// on other platforms the declarative discovery rules already cover their +/// standard installation locations. +pub fn query_installations( + query: &ToolchainQuery, + cancellation: &Cancellation, +) -> Result { + cancellation.check()?; + let mut result = ToolchainQueryResult::default(); + if !query.tools.iter().any(|tool| tool == JAVA_TOOL) { + return Ok(result); + } + #[cfg(windows)] + let drives = fixed_drive_roots(); + #[cfg(not(windows))] + let drives = Vec::new(); + let (installations, watch) = scan_drives(&drives, query.workspace.as_ref(), cancellation)?; + result.installations = installations; + result.watch = watch; + Ok(result) +} + +fn scan_drives( + drives: &[PathBuf], + workspace: Option<&ToolchainWorkspace>, + cancellation: &Cancellation, +) -> Result<(Vec, Vec), ToolchainQueryError> { + let mut installations = Vec::new(); + let mut watch = Vec::new(); + let workspace_root = workspace.map(|workspace| { + let root = PathBuf::from(&workspace.root); + dunce::canonicalize(&root).unwrap_or(root) + }); + for drive in drives { + cancellation.check()?; + for scan in VENDOR_SCANS { + cancellation.check()?; + let root = drive.join("Program Files").join(scan.directory); + watch.push(root.to_string_lossy().into_owned()); + scan_vendor_root( + &root, + scan.jdk_prefix_only, + cancellation, + &mut installations, + workspace_root.as_deref(), + )?; + } + } + installations.sort_by(|left, right| left.home.cmp(&right.home)); + installations.dedup_by(|right, left| { + installation_key(Path::new(&left.home)) == installation_key(Path::new(&right.home)) + }); + Ok((installations, watch)) +} + +fn scan_vendor_root( + root: &Path, + jdk_prefix_only: bool, + cancellation: &Cancellation, + installations: &mut Vec, + workspace_root: Option<&Path>, +) -> Result<(), ToolchainQueryError> { + if installations.len() >= MAX_INSTALLATIONS { + return Ok(()); + } + let entries = match fs::read_dir(root) { + Ok(entries) => entries, + Err(_) => return Ok(()), + }; + for (index, entry) in entries.flatten().enumerate() { + cancellation.check()?; + if index >= MAX_ROOT_ENTRIES { + break; + } + if installations.len() >= MAX_INSTALLATIONS { + break; + } + let name = entry.file_name(); + let Some(name) = name.to_str() else { + continue; + }; + if name.starts_with('.') || (jdk_prefix_only && !name.starts_with("jdk-")) { + continue; + } + let home = entry.path(); + if !home.is_dir() || !java_executable(&home).is_file() { + continue; + } + let Some(version) = release_version(&home) else { + continue; + }; + let home = dunce::canonicalize(&home).unwrap_or(home); + if workspace_root.is_some_and(|root| home.starts_with(root)) { + continue; + } + if installations.iter().any(|installation| { + installation_key(Path::new(&installation.home)) == installation_key(&home) + }) { + continue; + } + installations.push(ToolchainInstallation { + tool: JAVA_TOOL.to_string(), + version, + home: home.to_string_lossy().into_owned(), + }); + } + Ok(()) +} + +fn java_executable(home: &Path) -> PathBuf { + #[cfg(windows)] + return home.join("bin").join("java.exe"); + #[cfg(not(windows))] + home.join("bin").join("java") +} + +fn release_version(home: &Path) -> Option { + const RELEASE_BYTES: u64 = 4096; + + let mut bytes = Vec::new(); + fs::File::open(home.join("release")) + .ok()? + .take(RELEASE_BYTES) + .read_to_end(&mut bytes) + .ok()?; + let release = String::from_utf8_lossy(&bytes); + for line in release.lines() { + if let Some(value) = line.strip_prefix("JAVA_VERSION=") { + return normalize_java_version(value.trim().trim_matches('"')); + } + } + None +} + +/// Matches the tool definition's probe capture: a leading `1.` is not part of +/// the major version, and suffixes such as `_151` or `+8` are not either. +fn normalize_java_version(raw: &str) -> Option { + let raw = raw.strip_prefix("1.").unwrap_or(raw); + let bytes = raw.as_bytes(); + let mut end = 0; + while end < bytes.len() && bytes[end].is_ascii_digit() { + end += 1; + } + if end == 0 { + return None; + } + loop { + if end >= bytes.len() + || bytes[end] != b'.' + || end + 1 >= bytes.len() + || !bytes[end + 1].is_ascii_digit() + { + break; + } + end += 1; + while end < bytes.len() && bytes[end].is_ascii_digit() { + end += 1; + } + } + Some(raw[..end].to_string()) +} + +fn installation_key(path: &Path) -> String { + let path = path.to_string_lossy(); + #[cfg(windows)] + return path.to_lowercase(); + #[cfg(not(windows))] + path.into_owned() +} + +#[cfg(windows)] +fn fixed_drive_roots() -> Vec { + use windows_sys::Win32::Storage::FileSystem::GetDriveTypeW; + use windows_sys::Win32::System::WindowsProgramming::DRIVE_FIXED; + + let mut drives = Vec::new(); + for letter in b'A'..=b'Z' { + let root: Vec = format!("{}:\\\0", letter as char).encode_utf16().collect(); + if unsafe { GetDriveTypeW(root.as_ptr()) } == DRIVE_FIXED { + drives.push(PathBuf::from(format!("{}:\\", letter as char))); + } + } + drives +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct TempDir(PathBuf); + + impl TempDir { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let path = std::env::temp_dir().join(format!( + "lithe-java-toolchain-test-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&path).unwrap(); + Self(dunce::canonicalize(path).unwrap()) + } + + fn path(&self) -> &Path { + &self.0 + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn installation(root: &Path, parent: &str, name: &str, version: &str) -> PathBuf { + let home = root.join("Program Files").join(parent).join(name); + fs::create_dir_all(home.join("bin")).unwrap(); + let executable = java_executable(&home); + fs::write(executable, "").unwrap(); + fs::write( + home.join("release"), + format!("JAVA_VERSION=\"{version}\"\n"), + ) + .unwrap(); + home + } + + #[test] + fn scans_the_same_vendor_directories_on_every_fixed_drive() { + let temp = TempDir::new(); + let c = temp.path().join("c"); + let d = temp.path().join("d"); + let system = installation(&c, "Java", "jdk-21", "21.0.5"); + let wanted = installation(&d, "Java", "jdk1.8.0_151", "1.8.0_151"); + installation(&d, "Eclipse Adoptium", "jdk-17.0.10", "17.0.10+7"); + installation(&d, "Microsoft", "jdk-11.0.22", "11.0.22"); + installation(&d, "Microsoft", "not-a-jdk", "21"); + installation(&d, "Zulu", "zulu8", "1.8.0_402"); + installation(&d, "Amazon Corretto", "corretto-17", "17.0.9"); + installation(&d, "BellSoft", "liberica-21", "21.0.3"); + + let (found, watch) = scan_drives(&[c, d], None, &Cancellation::new()).unwrap(); + let homes: Vec = found + .iter() + .map(|installation| PathBuf::from(&installation.home)) + .collect(); + assert!(homes.contains(&system), "{found:?}"); + assert!(homes.contains(&wanted), "{found:?}"); + assert_eq!(found.len(), 7, "{found:?}"); + let eight = found + .iter() + .find(|installation| installation.home == wanted.to_string_lossy()) + .unwrap(); + assert_eq!(eight.version, "8.0"); + let seventeen = found + .iter() + .find(|installation| installation.version == "17.0.10") + .unwrap(); + assert_eq!(seventeen.tool, "java"); + assert_eq!(watch.len(), VENDOR_SCANS.len() * 2, "{watch:?}"); + let java_root = Path::new("d").join("Program Files").join("Java"); + assert!( + watch + .iter() + .any(|path| Path::new(path).ends_with(&java_root)), + "{watch:?}" + ); + } + + #[test] + fn a_workspace_can_never_supply_a_system_installation() { + let temp = TempDir::new(); + let c = temp.path().join("c"); + let d = temp.path().join("d"); + installation(&c, "Java", "jdk-21", "21.0.5"); + let wanted = installation(&d, "Java", "jdk1.8.0_151", "1.8.0_151"); + let workspace = ToolchainWorkspace { + root_id: "root".into(), + root: c.to_string_lossy().into_owned(), + directory: ".".into(), + }; + + let (found, _) = scan_drives(&[c, d], Some(&workspace), &Cancellation::new()).unwrap(); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(found[0].home, wanted.to_string_lossy()); + } + + #[test] + fn skips_directories_without_a_java_program_or_release_version() { + let temp = TempDir::new(); + let drive = temp.path().join("d"); + let no_program = drive + .join("Program Files") + .join("Java") + .join("jdk-no-program"); + fs::create_dir_all(&no_program).unwrap(); + fs::write(no_program.join("release"), "JAVA_VERSION=\"21\"\n").unwrap(); + let no_release = drive + .join("Program Files") + .join("Java") + .join("jdk-no-release"); + fs::create_dir_all(no_release.join("bin")).unwrap(); + fs::write(java_executable(&no_release), "").unwrap(); + + let (found, watch) = scan_drives(&[drive], None, &Cancellation::new()).unwrap(); + assert!(found.is_empty(), "{found:?}"); + assert_eq!(watch.len(), VENDOR_SCANS.len(), "{watch:?}"); + } + + #[test] + fn the_scan_is_bounded() { + let temp = TempDir::new(); + let drive = temp.path().join("d"); + for index in 0..(MAX_INSTALLATIONS + 1) { + installation( + &drive, + "Java", + &format!("jdk-{index}"), + &format!("21.0.{index}"), + ); + } + + let (found, _) = scan_drives(&[drive], None, &Cancellation::new()).unwrap(); + assert_eq!(found.len(), MAX_INSTALLATIONS); + } + + #[test] + fn cancellation_stops_the_scan() { + let cancellation = Cancellation::new(); + cancellation.cancel(); + let result = scan_drives(&[PathBuf::from("d")], None, &cancellation); + assert!(matches!(result, Err(ToolchainQueryError::Cancelled))); + } + + #[test] + fn normalizes_versions_like_the_probe_pattern() { + for (raw, want) in [("1.8.0_151", "8.0"), ("17.0.10+7", "17.0.10"), ("21", "21")] { + assert_eq!(normalize_java_version(raw).as_deref(), Some(want)); + } + assert_eq!(normalize_java_version("x"), None); + } +} diff --git a/backend/tests/repository_pins.rs b/backend/tests/repository_pins.rs index a807f01..a2a7401 100644 --- a/backend/tests/repository_pins.rs +++ b/backend/tests/repository_pins.rs @@ -193,6 +193,31 @@ fn package_scripts_name_every_path_the_backend_resolves() { } } +#[test] +fn the_java_installation_provider_matches_the_backend_registration() { + let manifest = read_json(&format!("{PLUGIN_ID}/plugin.json")); + assert_eq!(manifest["requires"]["toolchainProviders"], 0); + assert!( + manifest["permissions"] + .as_array() + .unwrap() + .iter() + .any(|permission| permission == "toolchains.provide"), + "the provider permission is missing" + ); + let providers = manifest["toolchainProviders"].as_array().unwrap(); + assert_eq!(providers.len(), 1); + assert_eq!( + providers[0]["id"], + lithe_java_backend::toolchain_provider::PROVIDER_ID + ); + assert_eq!(providers[0]["tools"], serde_json::json!(["java"])); + assert!( + providers[0].get("watchFiles").is_none(), + "installation-only providers omit watchFiles" + ); +} + #[test] fn the_language_service_jdk_is_separate_from_the_project_jdk() { let manifest = read_json(&format!("{PLUGIN_ID}/plugin.json")); diff --git a/backend/tests/session.rs b/backend/tests/session.rs index 23d9412..98335db 100644 --- a/backend/tests/session.rs +++ b/backend/tests/session.rs @@ -150,7 +150,8 @@ impl Host { json!({"rootUri": "file:///tmp/state/", "capabilities": { "experimental": { "litheFunctions": {"versions": [0]}, - "litheLogging": {"versions": [0]} + "litheLogging": {"versions": [0]}, + "litheToolchains": {"versions": [0], "providers": ["installs"]} } }}), ); @@ -183,6 +184,40 @@ fn read_frame(reader: &mut impl BufRead) -> Option { serde_json::from_slice(&body).ok() } +#[test] +fn the_backend_negotiates_the_java_installation_provider() { + let mut host = Host::start(); + let initialized = host.initialize(); + assert_eq!( + initialized["result"]["capabilities"]["experimental"]["litheToolchains"], + json!({"version": 0, "providers": ["installs"]}), + "{initialized}" + ); + + host.request( + 1, + "toolchains/query", + json!({ + "operationID": "query-1", "generation": 1, "providerID": "installs", + "authority": {"kind": "local"}, "context": null, "workspace": null, + "tools": ["other"] + }), + ); + let reply = host.answer(1); + assert_eq!( + reply["result"], + json!({ + "operationID": "query-1", "generation": 1, "providerID": "installs", + "installations": [], "statements": [], "watch": [] + }), + "{reply}" + ); + host.request(2, "shutdown", Value::Null); + assert_eq!(host.answer(2)["result"], Value::Null); + host.notify("exit", Value::Null); + assert_eq!(host.close(), 0); +} + #[test] fn the_backend_offers_the_java_commands_as_plugin_functions() { let mut host = Host::start(); diff --git a/compiler-host.json b/compiler-host.json index 7b00f83..0449204 100644 --- a/compiler-host.json +++ b/compiler-host.json @@ -1,6 +1,6 @@ { "repository": "https://github.com/1lck/Lithe-IDEA", - "revision": "76f8a663f18cafa3405da47ceede1ebd450d858f", - "coreRevision": "0b6da2725ded74de7c3b62b49d12c1947dc0a38a", + "revision": "b62a0817d321fe4a76dfabd3d54990a65324d3c5", + "coreRevision": "a1a792a5a3b2284720d3209b7a9c93394c365c18", "package": "io.github.lithe-idea.java-support" } diff --git a/contract.lock.json b/contract.lock.json index 34eeed8..4959bb3 100644 --- a/contract.lock.json +++ b/contract.lock.json @@ -1,18 +1,18 @@ { "repository": "https://github.com/Lithe-IDEA/Lithe-core-rust", - "commit": "0b6da2725ded74de7c3b62b49d12c1947dc0a38a", + "commit": "a1a792a5a3b2284720d3209b7a9c93394c365c18", "schemas": [ { "path": "plugin-manifest.schema.json", - "sha256": "ab756a2dfa023bd2301f7e52cf5d0a9a5341d60ec3df9a106715ad604119415c" + "sha256": "977000c699a1e363994e247ff0169460c9e4ea2d2287102f0009c52beadf8836" }, { "path": "plugin-ui.schema.json", - "sha256": "7e2155edacb2818145f300e3191e4ec041d0f3cb82b6fdfa22e68c5b552824a8" + "sha256": "0efd13690991337ada5c158ade268b5b18f7ca963cbcc767aaa66389ad1d5615" }, { "path": "plugin-l10n.schema.json", - "sha256": "a6d07bfe0fae0760640cffe9f1ed76f6f42b2851f6c5e7c4ff6a4407af30e38e" + "sha256": "0bf0518f624f4860a74ff30dbd7fd2efcac86c0c82954a39c4e6a46ce2b742f7" } ] } diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 5f983b1..b2831bd 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -16,6 +16,12 @@ | 声明 `settingRegions`(`language` 与 `compiler`)中英文设置搜索关键词,支持在设置侧栏检索 `jdtls`、`javac`、`字节码`、`类路径`、`Java 编译器` 等直达 Java 语言与编译器设置页 | implemented / verified | implemented / pending | implemented / pending | `io.github.lithe-idea.java-support/plugin.json`、`io.github.lithe-idea.java-support/l10n/zh-Hans.json`、`backend/tests/repository_pins.rs`(`manifest_and_zh_hans_declare_setting_regions`)、`scripts/verify-contract.py`(针对 Core `0b6da2725ded74de7c3b62b49d12c1947dc0a38a`)及宿主 Viva 无头搜索定位验证(2026-11-18 macOS arm64) | | 声明 `requires.ui: 0` 与 `ui.contribute` 权限,为 `language` 与 `compiler` 两个 `settingRegions` 提供 `settings.view` 实时画布预览(Java 语言页 4 张配置随草稿与界面语言联动卡片;Java 编译器页 3 层配置覆盖顺序图,响应窗口宽度 `width` 与 `resize`) | implemented / verified | implemented / pending | implemented / pending | `io.github.lithe-idea.java-support/plugin.json`、`backend/src/settings_view.rs`、`backend/tests/repository_pins.rs`、`scripts/verify-contract.py`(Core `0b6da2725ded74de7c3b62b49d12c1947dc0a38a`)、`e2e/host/desktop/internal/settingswindow/plugin_native_source_test.go` 与 `scripts/compiler/visual.mjs` 经 Core `ApplyPluginViewResult` 与 Viva 无头深浅色中英文截图验证(2026-11-19 macOS arm64) | +## Windows 固定盘符 JDK 发现(本次改动) + +| 能力 | macOS | Windows | Linux | 证据 | +| --- | --- | --- | --- | --- | +| 后端注册 `toolchainProviders` 版本 `0` 的 `installs` 提供方,在 Windows 枚举固定盘符并扫描各盘 `Program Files` 下的 Java、Eclipse Adoptium、Microsoft、Zulu、Amazon Corretto、BellSoft 安装根;只读取 `release` 元数据,按工具定义探针规则规范化 `1.8.x` 等版本,返回有界安装清单与扫描根 watch 路径,且不执行被发现的 Java 程序 | — | implemented / pending | — | `backend/src/toolchain_provider.rs`、`backend/tests/session.rs`、`backend/tests/repository_pins.rs`、`scripts/verify-contract.py`(Core `a1a792a5a3b2284720d3209b7a9c93394c365c18`);Windows 单元测试由 CI 覆盖,真实桌面端发现流程待 Windows 验收 | + ## 自动准备语言服务环境 | 能力 | macOS | Windows | Linux | 证据 | diff --git a/io.github.lithe-idea.java-support/plugin.json b/io.github.lithe-idea.java-support/plugin.json index e5b0453..157776e 100644 --- a/io.github.lithe-idea.java-support/plugin.json +++ b/io.github.lithe-idea.java-support/plugin.json @@ -4,7 +4,7 @@ "displayName": "Java Support", "version": "4.3.1", "pluginAPIVersion": 0, - "requires": {"backend": 0, "debugAdapters": 0, "languages": 0, "languageServers": 0, "pluginFunctions": 0, "settings": 0, "projectGenerators": 0, "toolDefinitions": 1, "sourceSettings": 1, "managedRuntimes": 1, "ui": 0}, + "requires": {"backend": 0, "debugAdapters": 0, "languages": 0, "languageServers": 0, "pluginFunctions": 0, "settings": 0, "projectGenerators": 0, "toolDefinitions": 1, "toolchainProviders": 0, "sourceSettings": 1, "managedRuntimes": 1, "ui": 0}, "managedRuntimes": { "resolve": { "function": "java.resolveRuntimes", @@ -160,7 +160,7 @@ "displayName": "Lithe Community", "signatureRequirement": "none" }, - "permissions": ["backend.launch", "runtimes.install", "ui.contribute", "documents.contentProvider", "documents.read", "documents.save", "editor.actions", "languageServer.launch", "languageServer.request", "project.generate", "debug.launch", "debug.attach", "debug.start", "run.start", "window.messages", "workspace.metadata"], + "permissions": ["backend.launch", "toolchains.provide", "runtimes.install", "ui.contribute", "documents.contentProvider", "documents.read", "documents.save", "editor.actions", "languageServer.launch", "languageServer.request", "project.generate", "debug.launch", "debug.attach", "debug.start", "run.start", "window.messages", "workspace.metadata"], "activationEvents": ["onLanguage:java", "onDebug:java"], "toolDefinitions": [ { @@ -644,6 +644,13 @@ ] } ], + "toolchainProviders": [ + { + "id": "installs", + "displayName": "JDK", + "tools": ["java"] + } + ], "languages": [ { "id": "java", diff --git a/sdk.lock.json b/sdk.lock.json index 79b905a..4153c41 100644 --- a/sdk.lock.json +++ b/sdk.lock.json @@ -2,5 +2,5 @@ "comment": "SDK 0.4.0 from the exact Core revision used by the Viva integration baseline. No SDK release tag exists yet; Cargo.lock pins the git source.", "version": "0.4.0", "repository": "https://github.com/Lithe-IDEA/Lithe-core-rust", - "commit": "65cf82343c5e315aae2e335b2e8f0217b703e89a" + "commit": "a1a792a5a3b2284720d3209b7a9c93394c365c18" } From 449c64fbb6ad9848a7694a660f973b1f2a2197f9 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Mon, 30 Nov 2026 23:43:52 -0800 Subject: [PATCH 2/2] fix(toolchains): tighten Windows drive watch slots, workspace boundary checks, and release parsing --- backend/src/toolchain_provider.rs | 127 ++++++++++++++++++++++++++---- 1 file changed, 112 insertions(+), 15 deletions(-) diff --git a/backend/src/toolchain_provider.rs b/backend/src/toolchain_provider.rs index 3045ad8..bf4247a 100644 --- a/backend/src/toolchain_provider.rs +++ b/backend/src/toolchain_provider.rs @@ -85,20 +85,39 @@ fn scan_drives( }); for drive in drives { cancellation.check()?; - for scan in VENDOR_SCANS { - cancellation.check()?; - let root = drive.join("Program Files").join(scan.directory); - watch.push(root.to_string_lossy().into_owned()); - scan_vendor_root( - &root, - scan.jdk_prefix_only, - cancellation, - &mut installations, - workspace_root.as_deref(), - )?; + let program_files = drive.join("Program Files"); + match fs::metadata(&program_files) { + Ok(metadata) if metadata.is_dir() => { + for scan in VENDOR_SCANS { + cancellation.check()?; + let root = program_files.join(scan.directory); + watch.push(root.to_string_lossy().into_owned()); + scan_vendor_root( + &root, + scan.jdk_prefix_only, + cancellation, + &mut installations, + workspace_root.as_deref(), + )?; + } + } + Ok(_) => { + watch.push(program_files.to_string_lossy().into_owned()); + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + // Only watch `Program Files` itself when absent so drives without + // one do not consume six watch slots each against host limits. + watch.push(program_files.to_string_lossy().into_owned()); + } + Err(_) => { + // Locked or unready fixed volumes (e.g. BitLocker) must not fail + // host directory observation for accessible drives. + } } } - installations.sort_by(|left, right| left.home.cmp(&right.home)); + installations.sort_by(|left, right| { + installation_key(Path::new(&left.home)).cmp(&installation_key(Path::new(&right.home))) + }); installations.dedup_by(|right, left| { installation_key(Path::new(&left.home)) == installation_key(Path::new(&right.home)) }); @@ -142,7 +161,7 @@ fn scan_vendor_root( continue; }; let home = dunce::canonicalize(&home).unwrap_or(home); - if workspace_root.is_some_and(|root| home.starts_with(root)) { + if workspace_root.is_some_and(|root| is_within_workspace(&home, root)) { continue; } if installations.iter().any(|installation| { @@ -167,7 +186,7 @@ fn java_executable(home: &Path) -> PathBuf { } fn release_version(home: &Path) -> Option { - const RELEASE_BYTES: u64 = 4096; + const RELEASE_BYTES: u64 = 64 * 1024; let mut bytes = Vec::new(); fs::File::open(home.join("release")) @@ -178,7 +197,7 @@ fn release_version(home: &Path) -> Option { let release = String::from_utf8_lossy(&bytes); for line in release.lines() { if let Some(value) = line.strip_prefix("JAVA_VERSION=") { - return normalize_java_version(value.trim().trim_matches('"')); + return normalize_java_version(value.trim().trim_matches(&['"', '\''][..])); } } None @@ -212,6 +231,36 @@ fn normalize_java_version(raw: &str) -> Option { Some(raw[..end].to_string()) } +fn is_within_workspace(home: &Path, workspace_root: &Path) -> bool { + #[cfg(windows)] + { + let mut home_components = home.components(); + for root_component in workspace_root.components() { + let Some(home_component) = home_components.next() else { + return false; + }; + let same = match (home_component, root_component) { + (std::path::Component::Prefix(a), std::path::Component::Prefix(b)) => { + a.as_os_str().to_string_lossy().to_lowercase() + == b.as_os_str().to_string_lossy().to_lowercase() + } + (std::path::Component::Normal(a), std::path::Component::Normal(b)) => { + a.to_string_lossy().to_lowercase() == b.to_string_lossy().to_lowercase() + } + (a, b) => a == b, + }; + if !same { + return false; + } + } + true + } + #[cfg(not(windows))] + { + home.starts_with(workspace_root) + } +} + fn installation_key(path: &Path) -> String { let path = path.to_string_lossy(); #[cfg(windows)] @@ -392,4 +441,52 @@ mod tests { } assert_eq!(normalize_java_version("x"), None); } + + #[test] + fn drive_without_program_files_uses_a_single_watch_path() { + let temp = TempDir::new(); + let c = temp.path().join("c"); + let e = temp.path().join("e"); + installation(&c, "Java", "jdk-21", "21.0.5"); + fs::create_dir_all(&e).unwrap(); + + let (found, watch) = scan_drives(&[c, e.clone()], None, &Cancellation::new()).unwrap(); + assert_eq!(found.len(), 1); + assert_eq!(watch.len(), VENDOR_SCANS.len() + 1, "{watch:?}"); + let expected = e.join("Program Files").to_string_lossy().into_owned(); + assert!(watch.contains(&expected), "{watch:?}"); + } + + #[test] + fn reads_java_version_past_large_release_fields() { + let temp = TempDir::new(); + let drive = temp.path().join("d"); + let home = installation(&drive, "Java", "jdk-21", "21.0.5"); + let modules = "java.base ".repeat(600); + fs::write( + home.join("release"), + format!("MODULES=\"{modules}\"\nJAVA_VERSION=\"21.0.5+11\"\n"), + ) + .unwrap(); + + let (found, _) = scan_drives(&[drive], None, &Cancellation::new()).unwrap(); + assert_eq!(found.len(), 1); + assert_eq!(found[0].version, "21.0.5"); + } + + #[test] + fn workspace_boundary_respects_component_boundaries() { + let temp = TempDir::new(); + let sibling = temp.path().join("work2"); + let home = installation(&sibling, "Java", "jdk-21", "21.0.5"); + let workspace = ToolchainWorkspace { + root_id: "root".into(), + root: temp.path().join("work").to_string_lossy().into_owned(), + directory: ".".into(), + }; + + let (found, _) = scan_drives(&[sibling], Some(&workspace), &Cancellation::new()).unwrap(); + assert_eq!(found.len(), 1); + assert_eq!(found[0].home, home.to_string_lossy()); + } }