diff --git a/crates/ide-core/src/error.rs b/crates/ide-core/src/error.rs index b3c044e677..2d40a50954 100644 --- a/crates/ide-core/src/error.rs +++ b/crates/ide-core/src/error.rs @@ -41,6 +41,11 @@ pub enum ErrorData { AmendConflict { commit: String, }, + /// jdtls could not set a module up as a Java project: the errors on its build files and + /// the builds enclosing it (`path: message`, the path relative to the project), nearest first. + JavaBuildProblems { + problems: Vec, + }, } /// Git's reported result for each destination ref. A remote with several push URLs can diff --git a/crates/ide-lsp/src/jdtls.rs b/crates/ide-lsp/src/jdtls.rs index b79966604a..f36d42df63 100644 --- a/crates/ide-lsp/src/jdtls.rs +++ b/crates/ide-lsp/src/jdtls.rs @@ -7,7 +7,7 @@ use crate::LspManager; use crate::server::{Running, Server}; -use ide_core::error::ErrorKind; +use ide_core::error::{ErrorData, ErrorKind}; use ide_core::event::LspRefreshKind; use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId}; use serde::{Deserialize, Serialize}; @@ -520,6 +520,30 @@ fn not_imported(e: &IdeError) -> bool { || m.contains("cannot find") } +const BUILD_FILES: [&str; 5] = + ["pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts"]; + +/// Errors on the build files of `module` and the builds enclosing it, nearest first, as +/// `path: message` (relative to `root`). When m2e or Buildship can't configure a module (a build +/// plugin or parent that doesn't resolve), it stays out of the Java model and these say why. +fn build_file_errors(diagnostics: &[(PathBuf, lsp_types::Diagnostic)], root: &Path, module: &Path) -> Vec { + let mut errors: Vec<_> = diagnostics + .iter() + .filter(|(path, d)| { + d.severity == Some(lsp_types::DiagnosticSeverity::ERROR) + && path.file_name().and_then(|n| n.to_str()).is_some_and(|n| BUILD_FILES.contains(&n)) + && path.parent().is_some_and(|dir| module.starts_with(dir)) + }) + .map(|(path, d)| { + let message = d.message.lines().next().unwrap_or_default().trim().trim_end_matches(':'); + (path.components().count(), format!("{}: {message}", path.strip_prefix(root).unwrap_or(path).display())) + }) + .collect(); + errors.sort_by_key(|(depth, _)| std::cmp::Reverse(*depth)); + let mut seen = HashSet::new(); + errors.into_iter().map(|(_, e)| e).filter(|e| seen.insert(e.clone())).collect() +} + /// The java-debug bundle is not loaded into jdtls. fn missing_bundle(e: &IdeError) -> bool { let m = e.message.to_ascii_lowercase(); @@ -844,6 +868,10 @@ impl LspManager { loop { match self.jdtls_command_cancellable(path, command, arguments.clone(), cancel).await { Err(e) if not_imported(&e) && Instant::now() < deadline => { + // An import that failed on the build file won't finish by waiting. + if let Some(unconfigured) = self.unconfigured_module(path, cancel).await? { + return Err(unconfigured); + } tracing::debug!("{command}: {e}; waiting for the project import"); cancellable_wait(cancel, tokio::time::sleep(Duration::from_millis(1500))).await?; } @@ -852,6 +880,17 @@ impl LspManager { } } + /// Why jdtls has no Java project for the module at `path`, when its build files say so. + async fn unconfigured_module(&self, path: &Path, cancel: &CancellationToken) -> IdeResult> { + let (server, _) = self.jdtls(path, cancel).await?; + let problems = build_file_errors(&server.diagnostics_snapshot(), &self.project_root, path); + Ok((!problems.is_empty()).then(|| IdeError { + kind: ErrorKind::InvalidInput, + message: format!("{SERVER}: {} is not a Java project: {}", path.display(), problems.join("; ")), + data: Some(ErrorData::JavaBuildProblems { problems }), + })) + } + fn running_java_projects<'a>(&self, files: &'a [PathBuf]) -> Vec<(Running, Vec<&'a Path>)> { let java = LanguageId::new("java"); let mut targets = HashMap::new(); @@ -1004,12 +1043,21 @@ impl LspManager { }; let cp = match self.java_classpath(module, test, cancel).await { Ok(cp) => Some(cp), - Err(e) if e.kind == ErrorKind::Cancelled => return Err(e), - Err(e) if matches!(build, Some(JavaBuildStatus::WithErrors | JavaBuildStatus::Failed)) => { - tracing::debug!("java.project.getClasspaths: {e}; retaining all compile errors"); - None + Err(e) + if e.kind == ErrorKind::Cancelled + || matches!(e.data, Some(ErrorData::JavaBuildProblems { .. })) => + { + return Err(e); } - Err(e) => return Err(e), + Err(e) => match self.unconfigured_module(module, cancel).await? { + // The build "fails" on the build file's errors alone, with no compile errors to show. + Some(unconfigured) => return Err(unconfigured), + None if matches!(build, Some(JavaBuildStatus::WithErrors | JavaBuildStatus::Failed)) => { + tracing::debug!("java.project.getClasspaths: {e}; retaining all compile errors"); + None + } + None => return Err(e), + }, }; let java_home = match self.java_vm_location(module, cancel).await { Ok(home) => home, @@ -1273,6 +1321,36 @@ mod tests { language.language_servers.into_iter().next().unwrap() } + #[test] + fn a_module_without_java_configuration_reports_its_build_file_errors() { + let at = |path: &str, severity, message: &str| { + let d = lsp_types::Diagnostic { severity: Some(severity), message: message.into(), ..Default::default() }; + (PathBuf::from(path), d) + }; + use lsp_types::DiagnosticSeverity as S; + let diagnostics = [ + at("/w/pom.xml", S::ERROR, "Non-resolvable import POM"), + at( + "/w/app-server/pom.xml", + S::ERROR, + "Could not calculate build plan: Plugin x:y:9.9.9 could not be resolved:\nFailure to find…", + ), + at("/w/app-server/pom.xml", S::WARNING, "Overriding managed version"), + at("/w/app-server/src/main/java/Main.java", S::ERROR, "Main cannot be resolved"), + at("/w/app-system/pom.xml", S::ERROR, "Another module's error"), + at("/w/app-server/build.gradle", S::ERROR, "Could not run phased build action"), + ]; + assert_eq!( + build_file_errors(&diagnostics, Path::new("/w"), Path::new("/w/app-server")), + [ + "app-server/pom.xml: Could not calculate build plan: Plugin x:y:9.9.9 could not be resolved", + "app-server/build.gradle: Could not run phased build action", + "pom.xml: Non-resolvable import POM", + ] + ); + assert!(build_file_errors(&diagnostics, Path::new("/w"), Path::new("/w/app-module")).len() == 1); + } + #[test] fn an_unresolvable_build_plugin_is_explained() { let diagnostic = |severity, message: &str| lsp_types::Diagnostic { diff --git a/src/bindings.ts b/src/bindings.ts index 8d6c56f73d..73c7259400 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -6650,7 +6650,12 @@ report?: PushReport | null } | /** Git updated some refs before a later ref or push URL failed. */ { type: "pushPartiallyApplied"; report: PushReport } | /** A conflicted history replay left an amend commit ready to keep separately. */ -{ type: "amendConflict"; commit: string }; +{ type: "amendConflict"; commit: string } | +/** + * jdtls could not set a module up as a Java project: the errors on its build files and + * the builds enclosing it (`path: message`, the path relative to the project), nearest first. + */ +{ type: "javaBuildProblems"; problems: string[] }; export type ErrorKind = "notFound" | "alreadyExists" | "permissionDenied" | "invalidInput" | /** The requested state is stale; the UI must use the current snapshot. */ diff --git a/src/features/run/javaModule.test.ts b/src/features/run/javaModule.test.ts index 5d39c46f3f..90acadff48 100644 --- a/src/features/run/javaModule.test.ts +++ b/src/features/run/javaModule.test.ts @@ -250,6 +250,26 @@ it.each([ expect(ipc.runStart).not.toHaveBeenCalled(); }); +it("says which build errors kept a module from being imported", async () => { + const problems = ["web/pom.xml: Plugin org.apache.maven.plugins:maven-compiler-plugin:9.9.9 could not be resolved"]; + ipc.javaResolveLaunch.mockResolvedValueOnce({ + status: "error", + error: { + kind: "invalidInput", + message: "jdtls: /p/web is not a Java project", + data: { type: "javaBuildProblems", problems }, + }, + } as never); + const session = await startRun({ ...config, module: "web" }); + expect(session?.status).toBe("failed"); + const output = runtime(session!.id)! + .console.lines.map((line) => line.text) + .join("\n"); + expect(output).toContain(`Java module 'web' could not be imported because its build has errors: ${problems[0]}.`); + expect(output).not.toContain("Wait for Java project import"); + expect(ipc.runStart).not.toHaveBeenCalled(); +}); + it.each([ ["unavailable", "jdtls is not installed (Settings › Languages & Frameworks › Language Servers)"], ["unavailable", "jdtls exited with code 1: wrong Java version"], diff --git a/src/platform/javaLaunch.ts b/src/platform/javaLaunch.ts index a1a31660f6..6ee7bf41c5 100644 --- a/src/platform/javaLaunch.ts +++ b/src/platform/javaLaunch.ts @@ -266,6 +266,12 @@ export async function prepareJavaLaunch(config: RunConfig, preparation: JavaPrep const info = await call( commands.javaResolveLaunch(module, parsed.classpath === "test", policy, preparation.request), ).catch((error: unknown) => { + if (error instanceof IpcError && error.data?.type === "javaBuildProblems") { + const problems = error.data.problems.join("; "); + throw new Error( + tx`Java module '${module || "."}' could not be imported because its build has errors: ${problems}. Fix them, then reload the Maven or Gradle project.`, + ); + } if ( error instanceof IpcError && error.kind !== "cancelled" && diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index de4e81795f..fcecd8f4c2 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -3865,5 +3865,6 @@ "Archive All Below": "Archive All Below", "Mark Agent Tasks as Unread": "Mark Agent Tasks as Unread", "Mark Agent Tasks as Read": "Mark Agent Tasks as Read", + "Java module '{value}' could not be imported because its build has errors: {problems}. Fix them, then reload the Maven or Gradle project.": "Java module '{value}' could not be imported because its build has errors: {problems}. Fix them, then reload the Maven or Gradle project.", "No tests ran. The build may skip them (skipTests, maven.test.skip, a disabled test task) or lack their engine: JUnit 4 tests on the JUnit Platform need junit-vintage-engine.": "No tests ran. The build may skip them (skipTests, maven.test.skip, a disabled test task) or lack their engine: JUnit 4 tests on the JUnit Platform need junit-vintage-engine." } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index bd04f036db..6445b42054 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10095,5 +10095,6 @@ "Archive All Below": "归档下方全部", "Mark Agent Tasks as Unread": "将 Agent 任务标记为未读", "Mark Agent Tasks as Read": "将 Agent 任务标记为已读", + "Java module '{value}' could not be imported because its build has errors: {problems}. Fix them, then reload the Maven or Gradle project.": "Java 模块 '{value}' 的构建存在错误,无法导入:{problems}。请修复后重新加载 Maven 或 Gradle 项目。", "No tests ran. The build may skip them (skipTests, maven.test.skip, a disabled test task) or lack their engine: JUnit 4 tests on the JUnit Platform need junit-vintage-engine.": "没有运行任何测试。构建可能跳过了测试(skipTests、maven.test.skip、被禁用的测试任务),或缺少对应的测试引擎:在 JUnit Platform 上运行 JUnit 4 测试需要 junit-vintage-engine。" }