Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 66 additions & 5 deletions backend/src/jdtls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ pub fn manifest_java_version(manifest: &str) -> Option<u64> {

/// The one Equinox launcher JAR in `directory`. None or several mean the
/// folder is no usable installation.
fn launcher_in(directory: &Path) -> Option<PathBuf> {
pub(crate) fn launcher_in(directory: &Path) -> Option<PathBuf> {
let mut launchers: Vec<PathBuf> = fs::read_dir(directory)
.ok()?
.filter_map(Result::ok)
Expand Down Expand Up @@ -312,12 +312,58 @@ pub fn locate_for_runtime(
/// The folders [`locate`] tries without a configured one, in order. A folder
/// may hold no installation; [`inspect`] decides.
pub fn candidates(environment: &SearchEnvironment, os: &str) -> Vec<PathBuf> {
candidate_sources(environment, os)
.into_iter()
.map(|(_, path)| path)
.collect()
}

/// Identifies where each candidate came from, in the same order used to launch.
pub(crate) fn candidate_sources(
environment: &SearchEnvironment,
os: &str,
) -> Vec<(&'static str, PathBuf)> {
let mut folders = Vec::new();
folders.extend(environment.server_home.clone());
folders.extend(launcher_installations(environment.path.as_ref(), os));
folders.extend(package_manager_folders(environment, os));
folders.extend(
environment
.server_home
.clone()
.map(|path| ("JDTLS_HOME", path)),
);
folders.extend(
launcher_installations(environment.path.as_ref(), os)
.into_iter()
.map(|path| ("PATH", path)),
);
folders.extend(
package_manager_folders(environment, os)
.into_iter()
.map(|path| ("package", path)),
);
if let Some(home) = &environment.home {
folders.extend(editor_extension_servers(home));
folders.extend(
editor_extension_servers(home)
.into_iter()
.map(|path| ("extension", path)),
);
if os == "macos" {
// Other editors can install the server at this fixed depth. Probe only this
// suffix, never descend through an application's other data.
if let Ok(entries) = fs::read_dir(home.join("Library/Application Support")) {
let mut servers: Vec<_> = entries
.take(256)
.filter_map(Result::ok)
.map(|entry| entry.path().join("tools/jdtls"))
.filter(|server| server.is_dir())
.collect();
servers.sort();
folders.extend(
servers
.into_iter()
.map(|path| ("Application Support", path)),
);
}
}
}
folders
}
Expand Down Expand Up @@ -596,6 +642,21 @@ mod tests {
);
}

#[test]
fn macos_application_tools_are_discovered_only_at_the_reported_depth() {
let temp = TempDir::new();
let support = temp.0.join("Library/Application Support");
let home = support.join("An Editor/tools/jdtls");
install(&home, &["config_mac_arm"]);
let nested = support.join("Another/nested/tools/jdtls");
install(&nested, &["config_mac_arm"]);
let environment = environment(&temp.0);
let found = candidates(&environment, "macos");
assert!(found.contains(&home));
assert!(!found.contains(&nested));
assert!(!candidates(&environment, "windows").contains(&home));
}

#[test]
fn jdtls_home_comes_before_the_other_folders() {
let temp = TempDir::new();
Expand Down
19 changes: 19 additions & 0 deletions backend/src/launch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -894,6 +894,25 @@ pub fn resolve_launch_function(
answer["initializationOptions"]["settings"] = configuration;
}
context.check_cancelled()?;
if let Some(workspace) = context.workspace_context() {
let jdk = &params["runtimes"]["jdk"];
if let (Some(version), Some(home), Some(server_version)) = (
jdk["version"].as_str(),
jdk["home"].as_str(),
params["runtimes"]["jdtls"]["version"].as_str(),
) {
session.record_service_environment(
workspace,
params["settings"][SERVER_HOME_SETTING]
.as_str()
.unwrap_or(""),
[
format!("JDT LS {server_version} · {}", server.home.display()),
format!("JDK {version} · {home}"),
],
);
}
}
Ok(answer)
}

Expand Down
3 changes: 2 additions & 1 deletion backend/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,12 +289,13 @@ pub fn backend() -> Result<Backend, SdkError> {
})?;
backend.suppress_success_diagnostics(function)?;
}
let view_session = Arc::clone(&session);
backend.function("compiler.prepareSettings", move |params, context| {
projects.edit(params, context, &session)
})?;
backend.function(
settings_view::SETTINGS_VIEW_FUNCTION_ID,
settings_view::view_function,
move |params, context| settings_view::view_function(&view_session, params, context),
)?;
backend.suppress_success_diagnostics(settings_view::SETTINGS_VIEW_FUNCTION_ID)?;
Ok(backend)
Expand Down
183 changes: 175 additions & 8 deletions backend/src/managed_runtimes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,9 +286,13 @@ pub fn inspect_jdk(home: &Path, os: &str, arch: &str) -> Option<(PathBuf, String
Some((home, version.to_owned()))
}

fn matches_size(home: &Path, pin: &PinnedFile) -> bool {
fs::metadata(home.join(&pin.path)).is_ok_and(|m| m.is_file() && m.len() == pin.size)
}

fn matches_file(home: &Path, pin: &PinnedFile) -> bool {
let path = home.join(&pin.path);
if !fs::metadata(&path).is_ok_and(|metadata| metadata.is_file() && metadata.len() == pin.size) {
if !matches_size(home, pin) {
return false;
}
let Ok(file) = File::open(path) else {
Expand All @@ -313,6 +317,17 @@ fn inspect_server_with(
arch: &str,
profile: &ServerProfile,
check_cancelled: &dyn Fn() -> Result<(), FunctionError>,
) -> Result<Option<ServerInstallation>, FunctionError> {
inspect_layout(home, os, arch, profile, check_cancelled, matches_file)
}

fn inspect_layout(
home: &Path,
os: &str,
arch: &str,
profile: &ServerProfile,
check_cancelled: &dyn Fn() -> Result<(), FunctionError>,
matches: fn(&Path, &PinnedFile) -> bool,
) -> Result<Option<ServerInstallation>, FunctionError> {
let Some(configuration) = jdtls::configuration_name(os, arch) else {
return Ok(None);
Expand Down Expand Up @@ -348,7 +363,7 @@ fn inspect_server_with(
};
for pin in std::iter::once(config).chain(&profile.files) {
check_cancelled()?;
if !matches_file(&server.home, pin) {
if !matches(&server.home, pin) {
return Ok(None);
}
}
Expand All @@ -365,6 +380,111 @@ pub fn inspect_server(
inspect_server_with(home, os, arch, &ServerProfile::pinned()?, check_cancelled)
}

/// Checks local server candidates only when requested from settings. A successful
/// local probe is not a claim that the host chose it over a managed installation.
pub fn check_local_servers(
configured: &str,
zh: bool,
check_cancelled: &dyn Fn() -> Result<(), FunctionError>,
) -> Result<Vec<String>, FunctionError> {
let os = std::env::consts::OS;
let arch = match std::env::consts::ARCH {
"aarch64" => "arm64",
arch => arch,
};
let profile = ServerProfile::pinned()?;
let explicit = !configured.is_empty();
let homes = if explicit {
vec![("setting", PathBuf::from(configured))]
} else {
jdtls::candidate_sources(&SearchEnvironment::current(), os)
};
let mut lines = Vec::new();
let mut seen = BTreeSet::new();
let limited = homes.len() > MAX_DISCOVERED_SERVERS;
for (source, home) in homes.into_iter().take(MAX_DISCOVERED_SERVERS) {
check_cancelled()?;
if !seen.insert(home.clone()) {
continue;
}
let (en, cn) = if !explicit && !home.is_dir() {
("Folder not found", "未找到目录")
} else if home.is_absolute()
&& inspect_layout(&home, os, arch, &profile, check_cancelled, matches_size)?.is_some()
{
(
"Layout matches 1.61.0; Toolchains verifies file contents",
"目录结构符合 1.61.0,可在工具链页校验文件内容",
)
} else {
server_rejection(&home, os, arch)
};
let origin = match (source, zh) {
("setting", true) => "手动选择",
("setting", false) => "Selected folder",
("package", true) => "包管理器",
("package", false) => "Package manager",
("extension", true) => "编辑器扩展",
("extension", false) => "Editor extension",
_ => source,
};
lines.push(format!(
"{origin} · {} · {}",
home.display(),
if zh { cn } else { en }
));
}
if lines.is_empty() {
lines.push(if zh {
"在已检查的位置未找到本机 JDT LS。可选择语言服务器目录,或使用工具链页准备托管环境。"
} else {
"No local JDT LS found in the checked locations. Choose a server folder or prepare the managed environment in Toolchains."
}.into());
}
if limited {
lines.push(
if zh {
"已达到 32 个候选目录的检查上限。"
} else {
"Checked the first 32 candidate folders."
}
.into(),
);
}
Ok(lines)
}

fn server_rejection(home: &Path, os: &str, arch: &str) -> (&'static str, &'static str) {
if !home.is_absolute() || !home.is_dir() {
return (
"Choose an existing absolute server folder",
"请选择存在的语言服务器绝对路径",
);
}
let roots = [home.to_path_buf(), home.join("libexec")];
if let Some(config) = jdtls::configuration_name(os, arch) {
if !roots
.iter()
.any(|root| root.join(config).join("config.ini").is_file())
{
return ("Missing platform config.ini", "缺少当前平台的 config.ini");
}
}
if !roots
.iter()
.any(|root| jdtls::launcher_in(&root.join("plugins")).is_some())
{
return (
"Expected one Equinox launcher JAR",
"需要一个 Equinox 启动 JAR",
);
}
(
"Files differ from verified JDT LS 1.61.0",
"文件与已验证的 JDT LS 1.61.0 不一致",
)
}

fn resolve_with(
params: &Value,
environment: &SearchEnvironment,
Expand Down Expand Up @@ -442,9 +562,12 @@ Choose a valid JDK or clear its toolchain override to use the managed runtime.",
let candidates = absolute(params["candidates"].get(JDTLS_ID))
.into_iter()
.chain(
jdtls::candidates(environment, os)
.into_iter()
.take(MAX_DISCOVERED_SERVERS),
std::iter::once_with(|| {
jdtls::candidates(environment, os)
.into_iter()
.take(MAX_DISCOVERED_SERVERS)
})
.flatten(),
);
let mut found = None;
let mut seen = BTreeSet::new();
Expand Down Expand Up @@ -474,7 +597,8 @@ Choose a valid JDK or clear its toolchain override to use the managed runtime.",
/// invalid explicit configuration is an SDK-reported error. Cancellation is
/// checked between each bounded file read and never becomes a failure log.
pub fn resolve_runtimes_function(params: Value, context: &Context) -> Result<Value, FunctionError> {
localize_result(
let language = params["language"].as_str().unwrap_or_default();
let result = localize_result(
(|| {
resolve_with(
&params,
Expand All @@ -483,8 +607,26 @@ pub fn resolve_runtimes_function(params: Value, context: &Context) -> Result<Val
&|| context.check_cancelled().map_err(Into::into),
)
})(),
params["language"].as_str().unwrap_or_default(),
)
language,
);
if let Err(FunctionError::Plugin(error)) = &result {
if error.code() == SERVER_INCOMPATIBLE {
if let Some(home) = absolute(params["settings"].get(SERVER_HOME_SETTING)) {
let (en, zh) = server_rejection(
&home,
params["platform"]["os"].as_str().unwrap_or_default(),
params["platform"]["arch"].as_str().unwrap_or_default(),
);
let message = if language.to_ascii_lowercase().starts_with("zh") {
format!("{zh}。请重新选择语言服务器目录,或清除选择以使用托管环境。")
} else {
format!("{en}. Choose another server folder or clear it to use the managed environment.")
};
return Err(PluginError::new(SERVER_INCOMPATIBLE, message).into());
}
}
}
result
}

fn localize_result(
Expand Down Expand Up @@ -741,6 +883,31 @@ mod tests {
);
}

#[test]
fn local_probe_distinguishes_missing_configuration_and_other_distributions() {
let fixture = Fixture::new();
let (home, profile) = fixture.server("server");
let checked = || Ok(());
assert!(
inspect_layout(&home, "linux", "x86_64", &profile, &checked, matches_size)
.unwrap()
.is_some()
);
fs::write(home.join("plugins/extra.jar"), b"other distribution").unwrap();
assert!(
inspect_layout(&home, "linux", "x86_64", &profile, &checked, matches_size)
.unwrap()
.is_none()
);
assert!(server_rejection(&home, "linux", "x86_64")
.0
.contains("differ"));
fs::remove_file(home.join("config_linux/config.ini")).unwrap();
assert!(server_rejection(&home, "linux", "x86_64")
.0
.contains("config.ini"));
}

#[test]
fn full_jdk_checks_are_platform_specific_and_reject_jre_wrong_arch_and_partial_files() {
let fixture = Fixture::new();
Expand Down
Loading