From e44d7fd396eb967331d266176f1ad198ce2ad888 Mon Sep 17 00:00:00 2001 From: solhovoy <50910307+solhovoy@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:39:53 +0200 Subject: [PATCH] fix(java): support launch classpaths from Maven POM modules (#6184) An Application configuration whose classpath module is a dependency-only Maven module (packaging=pom, such as a distribution or assembly module) could not launch: launch preparation required the POM to be a Java project in jdtls, and the Maven fallback rejected aggregators outright. Such a module now resolves its launch classpath from its dependencies: reactor modules (including runtime-scoped ones, which are now built as upstream projects for every launch) and external libraries, without a Java language server and without its own output directory. NoBuild reuses the last resolved classpath instead of running the compile lifecycle, and a launch from such a POM leaves the Java project to java-debug instead of naming a non-Java project; a JDWP attach at an aggregator root still names the root project. Co-authored-by: solhovoy <50910307+solhovoy@users.noreply.github.com> --- crates/ide-build/src/compile/mod.rs | 3 +- crates/ide-build/src/compile/single.rs | 112 +++++++++++++++++-- crates/ide-build/src/jbuild/mod.rs | 12 +- crates/ide-host/src/ops/java.rs | 41 +++++-- crates/ide-host/tests/java_build.rs | 103 +++++++++++++++++ docs/en/languages/java.mdx | 2 + src/features/debugger/__tests__/java.test.ts | 29 ++++- src/features/debugger/java.ts | 17 ++- 8 files changed, 288 insertions(+), 31 deletions(-) diff --git a/crates/ide-build/src/compile/mod.rs b/crates/ide-build/src/compile/mod.rs index b084163687..80a1121258 100644 --- a/crates/ide-build/src/compile/mod.rs +++ b/crates/ide-build/src/compile/mod.rs @@ -16,7 +16,8 @@ pub use launch_resources::process_launch_resources; pub use modules::record_module_build; pub use single::{ SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan, - has_gradle_file_target, javac_step, module_classpath, module_classpaths, single_file_classpath, single_file_target, + has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths, + single_file_classpath, single_file_target, }; pub use structure::{ StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan, diff --git a/crates/ide-build/src/compile/single.rs b/crates/ide-build/src/compile/single.rs index 454df082da..ff493c2f45 100644 --- a/crates/ide-build/src/compile/single.rs +++ b/crates/ide-build/src/compile/single.rs @@ -94,12 +94,12 @@ pub(super) fn build_javac_step( Ok(step) } -/// The resolved dependency classpath for one module and scope, tied to the same -/// inputs as its launch build so POM, JDK, settings and profile changes invalidate it. +/// The last resolved dependency classpath for one module and scope. A fingerprint +/// permits reuse during a build; NoBuild also uses records without one. #[derive(Debug, Deserialize, Serialize)] struct CachedClasspath { version: u32, - fingerprint: LaunchFingerprint, + fingerprint: Option, classpath: String, } @@ -162,9 +162,6 @@ fn module_target(root: &Path, model: &BuildModel, module: &Path, test: bool) -> .iter() .find(|p| root.join(&p.dir) == module) .ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?; - if project.packaging == "pom" { - return Err(IdeError::not_found("the launch module is a Maven aggregator without sources")); - } let top = maven_reactor(m, &project.dir) .ok_or_else(|| IdeError::not_found("no linked Maven reactor found for module"))?; let top_dir = subdir(root, &top.dir); @@ -217,6 +214,30 @@ pub fn module_classpath( module_classpaths(root, model, &[module.to_path_buf()], test, local_repo, cache, cancel) } +/// Uses the last launch classpath, or probes dependencies without invoking the compile lifecycle. +pub fn module_classpath_without_build( + root: &Path, + model: &BuildModel, + module: &Path, + test: bool, + cache: &Path, + cancel: &CancellationToken, +) -> IdeResult { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let target = module_target(root, model, module, test)?; + if let Some(path) = classpath_cache_path(root, cache, module, test) + && let Ok(bytes) = fs::read(path) + && let Ok(cached) = serde_json::from_slice::(&bytes) + && cached.version == CLASSPATH_CACHE_VERSION + && classpath_entries_exist(root, &cached.classpath) + { + return Ok(cached.classpath); + } + classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel) +} + /// [`module_classpath`] of `modules[0]`. The other modules, launched together with it /// (#3971), share its Maven probe when they have no cached classpath, which leaves /// theirs cached for their own launches. @@ -245,7 +266,7 @@ pub fn module_classpaths( && let Ok(bytes) = fs::read(path) && let Ok(cached) = serde_json::from_slice::(&bytes) && cached.version == CLASSPATH_CACHE_VERSION - && cached.fingerprint == *fingerprint + && cached.fingerprint.as_ref() == Some(fingerprint) && classpath_entries_exist(root, &cached.classpath) { if i == 0 { @@ -269,7 +290,7 @@ pub fn module_classpaths( return Err(IdeError::cancelled()); } for (Probe(_, fingerprint, cache_path), classpath) in probes.into_iter().zip(&classpaths) { - if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) { + if let Some(path) = cache_path { let cached = CachedClasspath { version: CLASSPATH_CACHE_VERSION, fingerprint, classpath: classpath.clone() }; if let Err(error) = cache_classpath(&path, &cached) { @@ -675,6 +696,81 @@ mod tests { assert!(single_file_target(root, &model, &root.join("other/Main.java")).is_err()); } + #[cfg(unix)] + #[test] + fn pom_launch_resolves_dependencies_without_compiling_for_no_build() { + use std::os::unix::fs::PermissionsExt; + + let dir = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(dir.path()).unwrap(); + fixture(&root); + let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap(); + write( + &root, + "app/pom.xml", + &pom.replace("app", "apppom"), + ); + let script = root.join("mvnw"); + write( + &root, + "mvnw", + "#!/bin/sh\nprintf '%s\\n' \"$@\" > args.txt\nmkdir -p app/target\nprintf '/repo/runtime.jar' > app/target/ide-compile-cp.txt\n", + ); + fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap(); + let model = crate::load(&root, &root.join("cache"), None); + let cancel = CancellationToken::new(); + let cp = module_classpath_without_build(&root, &model, &root.join("app"), false, &root.join("cache"), &cancel) + .unwrap(); + let paths: Vec<_> = std::env::split_paths(&cp).collect(); + assert!(paths.contains(&root.join("lib/target/classes")), "{cp}"); + assert!(paths.contains(&root.join("shared/target/classes")), "{cp}"); + assert!(paths.contains(&PathBuf::from("/repo/runtime.jar")), "{cp}"); + assert!(!paths.contains(&root.join("app/target/classes")), "{cp}"); + let args = fs::read_to_string(root.join("args.txt")).unwrap(); + assert!(!args.lines().any(|a| matches!(a, "compile" | "package" | "test-compile")), "{args}"); + assert!(args.lines().any(|a| a == "-Dmdep.includeScope=runtime"), "{args}"); + + module_classpath(&root, &model, &root.join("app"), false, None, &root.join("cache"), &cancel).unwrap(); + let args = fs::read_to_string(root.join("args.txt")).unwrap(); + assert!(args.lines().any(|a| a == "compile"), "{args}"); + } + + #[cfg(unix)] + #[test] + fn no_build_keeps_the_last_launch_classpath_after_a_pom_change() { + use std::os::unix::fs::PermissionsExt; + + let dir = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(dir.path()).unwrap(); + fixture(&root); + let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap(); + write( + &root, + "app/pom.xml", + &pom.replace("app", "apppom"), + ); + write( + &root, + "mvnw", + "#!/bin/sh\necho called >> calls.txt\nprintf '%s\\n' \"$@\" > args.txt\nmkdir -p app/target repo\ntouch repo/runtime.jar repo/runtime-v2.jar\nif grep -q changed app/pom.xml; then printf \"$PWD/repo/runtime-v2.jar\" > app/target/ide-compile-cp.txt; else printf \"$PWD/repo/runtime.jar\" > app/target/ide-compile-cp.txt; fi\n", + ); + fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap(); + let model = crate::load(&root, &root.join("cache"), None); + let cancel = CancellationToken::new(); + let previous = + module_classpath(&root, &model, &root.join("app"), false, None, &root.join("cache"), &cancel).unwrap(); + assert!(previous.contains("repo/runtime.jar"), "{previous}"); + + let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap(); + write(&root, "app/pom.xml", &pom.replace("", "changed")); + let launch = + module_classpath_without_build(&root, &model, &root.join("app"), false, &root.join("cache"), &cancel) + .unwrap(); + assert!(launch.contains("repo/runtime.jar"), "{launch}"); + assert!(!launch.contains("runtime-v2.jar"), "{launch}"); + assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap().lines().count(), 1); + } + #[test] fn javac_prefers_the_module_jdk_and_scopes_test_sources() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ide-build/src/jbuild/mod.rs b/crates/ide-build/src/jbuild/mod.rs index 55a9f5b6f5..1f5bd71044 100644 --- a/crates/ide-build/src/jbuild/mod.rs +++ b/crates/ide-build/src/jbuild/mod.rs @@ -441,7 +441,7 @@ impl JavaBuild<'_> { let record = model::load_record(&model::reactor_dir(self.cache, &top.key()))?; let project = record.model.projects.iter().find(|p| p.dir == module)?; let paths = class_paths(project, test); - paths.first().is_some_and(|p| p.is_dir()).then_some(paths) + paths.first().is_some_and(|p| p.exists()).then_some(paths) } /// Builds `target`. A launch gets the classpath to run with; the others an empty one. @@ -1039,7 +1039,7 @@ fn launch_projects<'a>(model: &'a ReactorModel, target: &'a ProjectModel, test: if test { visit(project, false, by_output, by_test_output, seen, out); } - for entry in &project.set(test).classpath { + for entry in project.set(test).classpath.iter().chain(&project.set(test).runtime_classpath) { if let Some(upstream) = by_output.get(entry.as_path()).filter(|p| p.dir != project.dir) { visit(upstream, false, by_output, by_test_output, seen, out); } else if let Some(upstream) = by_test_output.get(entry.as_path()).filter(|p| p.dir != project.dir) { @@ -1061,10 +1061,12 @@ fn class_paths(target: &ProjectModel, test: bool) -> Vec { out.push(p.clone()); } }; - if test { - push(&target.test.output); + if target.packaging != "pom" { + if test { + push(&target.test.output); + } + push(&target.main.output); } - push(&target.main.output); for entry in &target.set(test).runtime_classpath { push(entry); } diff --git a/crates/ide-host/src/ops/java.rs b/crates/ide-host/src/ops/java.rs index 34a8a49f24..9aef49c5ab 100644 --- a/crates/ide-host/src/ops/java.rs +++ b/crates/ide-host/src/ops/java.rs @@ -69,16 +69,15 @@ pub(crate) async fn resolve_launch( progress("Resolving the module"); let project = host.project(window)?; let module = ide_core::project_roots::resolve(&project.root, &module); - let scope = { + let scope = std::sync::Arc::new({ let (project, module) = (project.clone(), module.clone()); tokio::task::spawn_blocking(move || workspace::scope_for(&project, &module)) .await .map_err(|e| IdeError::internal(e.to_string()))?? - }; + }); if !project.lsp.java_served_by_jdtls(&module) { return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel, events).await; } - let scope = std::sync::Arc::new(scope); let launches = project.java_launches.for_cache(&scope.cache); let prefer_maven = scope.settings.languages.java.maven.delegate_build; // A launch builds incrementally unless the configuration asks for Rebuild or NoBuild. @@ -110,6 +109,10 @@ pub(crate) async fn resolve_launch( .await .map_err(|e| IdeError::internal(e.to_string()))? }; + // A dependency-only POM has no Java project in jdtls, but is a valid launch classpath. + if is_maven_aggregator(&scope.root, &model, &module) { + return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel, events).await; + } // A Maven or Gradle module is built by the IDE's Java build ([`served_by_service`]), unless // the launch debugs with java-debug, whose HotSwap reloads what jdtls compiles (ecj's // classes differ from javac's: lambda names). jdtls keeps building for its diagnostics @@ -383,6 +386,10 @@ fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool { model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module)) } +fn is_maven_aggregator(root: &Path, model: &BuildModel, module: &Path) -> bool { + model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module && p.packaging == "pom")) +} + /// Whether the IDE's Java build builds the module holding `path` (#4078): a Maven module unless /// Settings › Maven › Delegate IDE build/run actions to Maven asks for Maven; a Gradle module /// when Settings › Gradle › Build and run using asks for the IDE. @@ -418,31 +425,32 @@ fn gradle_served(settings: &Settings) -> bool { /// A launch of a module jdtls doesn't serve (another Java language server, or none): the /// build tool compiles it, and the classpath comes from that server, else from Maven. +/// Dependency-only Maven POMs also use this path, without querying a Java language server. #[allow(clippy::too_many_arguments)] async fn resolve_launch_without_jdtls( host: &Host, project: &std::sync::Arc, module: PathBuf, - scope: workspace::Scope, + scope: std::sync::Arc, test: bool, policy: BuildPolicy, cancel: &CancellationToken, events: Option, ) -> IdeResult { let started = std::time::Instant::now(); - let scope = std::sync::Arc::new(scope); let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build }; let (model, built, by_service) = { let (scope, module, cancel, events) = (scope.clone(), module.clone(), cancel.clone(), events.clone()); let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone()); tokio::task::spawn_blocking(move || { let model = load_launch_model(&scope); + let aggregator = is_maven_aggregator(&scope.root, &model, &module); let on_event = |event: BuildEvent| { if let Some(events) = &events { events(event); } }; - if policy == BuildPolicy::NoBuild { + if policy == BuildPolicy::NoBuild && !aggregator { return (model, None, false); } if served_by_service(&scope.root, &model, &scope.settings, &module) @@ -455,7 +463,7 @@ async fn resolve_launch_without_jdtls( &model, &module, test, - Some(kind), + (policy != BuildPolicy::NoBuild).then_some(kind), &cancel, &on_event, ) { @@ -467,6 +475,9 @@ async fn resolve_launch_without_jdtls( Err(e) => return (model, Some(Err(e)), false), } } + if policy == BuildPolicy::NoBuild { + return (model, None, false); + } let built = compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event); (model, Some(built), false) }) @@ -486,14 +497,17 @@ async fn resolve_launch_without_jdtls( ))); } Some(Ok(built)) => { - info.build = Some(match built.failure { + let status = match built.failure { None => JavaBuildStatus::Succeeded, Some(failure) if policy == BuildPolicy::MakeAndContinueOnErrors => { info.hints.push(failure); JavaBuildStatus::Failed } Some(failure) => return Err(IdeError::internal(failure)), - }); + }; + if policy != BuildPolicy::NoBuild { + info.build = Some(status); + } class_paths.extend(built.class_dirs.iter().map(|p| p.to_string_lossy().into_owned())); } } @@ -501,7 +515,8 @@ async fn resolve_launch_without_jdtls( if let Some(events) = &events { events(BuildEvent::Progress { message: "Resolving the classpath".into(), fraction: None }); } - let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?; + let aggregator = is_maven_aggregator(&scope.root, &model, &module); + let from_server = if aggregator { None } else { project.lsp.java_server_classpath(&module, test, cancel).await? }; let data_dir = host.local_data_dir.clone(); let cancel = cancel.clone(); tokio::task::spawn_blocking(move || { @@ -527,7 +542,11 @@ async fn resolve_launch_without_jdtls( )); } let local_repo = ide_sdk::apply::maven_local_repository(root, settings); - let classpath = compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?; + let classpath = if aggregator && policy == BuildPolicy::NoBuild { + compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel)? + } else { + compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)? + }; append_unique_class_paths( &mut class_paths, std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()), diff --git a/crates/ide-host/tests/java_build.rs b/crates/ide-host/tests/java_build.rs index 8bc99c0eb1..4145088d2a 100644 --- a/crates/ide-host/tests/java_build.rs +++ b/crates/ide-host/tests/java_build.rs @@ -15,6 +15,109 @@ fn write(root: &Path, rel: &str, text: &str) { fs::write(path, text).unwrap(); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn pom_launch_uses_dependency_classpath_without_a_java_project() { + let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir()); + if !has_jdk || ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path()).is_none() { + eprintln!("skipped: needs JAVA_HOME and mvn"); + return; + } + for (jdtls, delegate) in [(false, false), (true, false), (true, true)] { + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let root = base.join("project"); + let pom = include_str!("../../ide-build/tests/fixtures/jbuild-maven/pom.xml") + .replace("", "assembly"); + write(&root, "pom.xml", &pom); + write(&root, "lib/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/lib/pom.xml")); + write(&root, "app/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/app/pom.xml")); + write( + &root, + "assembly/pom.xml", + r#"4.0.0 + troot1 + assemblypom + + tapp1runtime + org.slf4jslf4j-api1.7.36 + "#, + ); + write( + &root, + "lib/src/main/java/l/L.java", + "package l;\npublic class L { public static String name() { return \"lib\"; } }\n", + ); + let main = "package a;\npublic class A { public static void main(String[] args) throws Exception { Class.forName(\"org.slf4j.Logger\"); System.out.println(l.L.name()); } }\n"; + write(&root, "app/src/main/java/a/A.java", main); + let global = SettingsStore::load(&base.join("config"), None); + for server in ["jdtls", "java-analyzer", "kmp-lsp"] { + global + .set( + SettingsScope::Global, + &format!("languageServers.{server}.enabled"), + serde_json::json!(server == "jdtls" && jdtls), + ) + .unwrap(); + } + global.set(SettingsScope::Global, "languages.java.maven.delegateBuild", serde_json::json!(delegate)).unwrap(); + global + .set( + SettingsScope::Global, + "languageServers.jdtls.command", + serde_json::json!(root.join("must-not-start-jdtls")), + ) + .unwrap(); + let host = Host::new(common::host_config(&base)); + host.trust.decide(&root, true, false).unwrap(); + host.open_project("main", &root).unwrap(); + let module = root.join("assembly"); + assert_eq!(host.project("main").unwrap().lsp.java_served_by_jdtls(&module), jdtls); + + for (policy, debug) in [ + (BuildPolicy::Make, false), + (BuildPolicy::NoBuild, false), + (BuildPolicy::NoBuild, true), + (BuildPolicy::Rebuild, true), + ] { + if policy == BuildPolicy::NoBuild { + write(&root, "app/src/main/java/a/A.java", "this must not be compiled"); + } else { + write(&root, "app/src/main/java/a/A.java", main); + } + let events = Arc::new(Mutex::new(Vec::new())); + let sink = events.clone(); + let info = ops::java::java_resolve_launch( + &host, + "main", + module.clone(), + false, + debug, + policy, + RequestId::next(), + ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event)), + ) + .await + .unwrap_or_else(|e| panic!("jdtls={jdtls}, delegate={delegate}, policy={policy:?}: {e:?}")); + assert_eq!(info.build.is_some(), policy != BuildPolicy::NoBuild); + assert!(info.class_paths.iter().any(|p| p.ends_with("slf4j-api-1.7.36.jar")), "{:?}", info.class_paths); + assert!(!info.class_paths.iter().any(|p| p.contains("t.assembly/classes")), "{:?}", info.class_paths); + let cp = std::env::join_paths(&info.class_paths).unwrap(); + let out = std::process::Command::new(info.java_exec.as_ref().expect("resolved Java executable")) + .arg("-cp") + .arg(cp) + .arg("a.A") + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "lib"); + if policy == BuildPolicy::NoBuild { + assert!(!events.lock().unwrap().iter().any(|e| matches!(e, BuildEvent::Step { .. }))); + } + } + host.shutdown().await; + } +} + /// A Maven launch compiles with the IDE's Java build (javac, outputs in the project cache) /// and runs from its outputs. Needs `mvn` and a JDK (`JAVA_HOME`), else it is skipped. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/docs/en/languages/java.mdx b/docs/en/languages/java.mdx index 9c804c8633..cd421dd7bd 100644 --- a/docs/en/languages/java.mdx +++ b/docs/en/languages/java.mdx @@ -110,6 +110,8 @@ In a Maven project with Kotlin sources, OpenIDEA builds the Kotlin code in the b Gutter icons on main methods, test classes and test methods create these configurations, and Maven and Gradle run configurations are detected from the build files. For Gradle, **Build and run using** decides whether an Application runs as a Gradle `JavaExec` task (the default) or is launched by OpenIDEA on the classpath reported by jdtls. +An Application configuration can also use a Maven module with `packaging=pom`, such as a distribution or assembly module without sources. Its dependencies supply the launch classpath, including reactor modules and external libraries; the POM does not need to be imported as a Java project by jdtls. + A JUnit 5 test class or method run from the gutter of a Maven module starts on jdtls' test classpath with OpenIDEA's JUnit Platform runner, without Maven, like IDEA (**Settings › Build, Execution, Deployment › Maven › Run tests using**). The runner adds `junit-platform-launcher` of the engine's version when the project has none (from the local repository, else downloaded once from Maven Central). As in IDEA, the test JVM gets the module's Surefire configuration: `argLine` (with `@{…}` late replacement), `systemPropertyVariables`, `environmentVariables`, `workingDirectory`, `additionalClasspathElements` and `classpathDependencyExcludes`, read from the effective POM of the last Maven sync (before a sync, from the module's own `pom.xml`). Resource filtering and Surefire's other settings (forking, includes, groups) don't apply; choose **Maven** to run through Surefire. Test results are read from the JUnit XML reports Maven and Gradle write, so passed tests are listed as well. The test tree supports rerunning failed tests. VM options of a Gradle run configuration are applied to the JVMs Gradle forks (`run`, `bootRun`, `test`). When a classpath is too long for the command line (common on Windows), it is moved into an argument file or a manifest-only jar. diff --git a/src/features/debugger/__tests__/java.test.ts b/src/features/debugger/__tests__/java.test.ts index 22eda42bbb..52e691cd7d 100644 --- a/src/features/debugger/__tests__/java.test.ts +++ b/src/features/debugger/__tests__/java.test.ts @@ -3,6 +3,7 @@ import type { RunConfig } from "@/platform/ipc"; const invoked: Array<[string, unknown[]]> = []; let shortenCommandLine: string | null = null; +let launchProjectRoot: string | undefined = "/p"; let kotlinFiles = false; let debugAdapter = "java-debug"; const files: Record = {}; @@ -45,7 +46,7 @@ vi.mock("@/platform/ipc", async (orig) => { invoked.push(["javaResolveLaunch", a]); return ok({ build: "succeeded", - projectRoot: "/p", + projectRoot: launchProjectRoot, classPaths: ["/p/target/classes", "/m2/a.jar"], modulePaths: [], pathListSeparator: ":", @@ -90,6 +91,7 @@ describe("Java debugging (java-debug through jdtls)", () => { beforeEach(() => { invoked.length = 0; shortenCommandLine = null; + launchProjectRoot = "/p"; kotlinFiles = false; debugAdapter = "java-debug"; }); @@ -273,6 +275,31 @@ describe("naming the Java project jdtls imported", () => { expect(await javaProjectName("/p")).toBe("taihe"); }); + it("lets java-debug resolve the main class instead of naming a POM-only project", async () => { + launchProjectRoot = undefined; + files["/p/assembly/pom.xml"] = "assemblypom"; + files["/p/assembly/.project"] = "assembly"; + kotlinFiles = false; + debugAdapter = "java-debug"; + const launch = await javaLaunchConfig({ ...app, module: "assembly" }, "/p"); + expect(JSON.parse(launch.extraJson!)).not.toHaveProperty("projectName"); + expect(JSON.parse(launch.extraJson!).classPaths).toEqual(["/p/target/classes", "/m2/a.jar"]); + }); + + it("still names the project of an aggregator root for a JDWP attach", async () => { + files["/p/pom.xml"] = "rootpom"; + const attach = await javaAttachConfig({ name: "remote", module: "", hostName: "remote", port: 5005 }, "/p"); + expect(JSON.parse(attach.extraJson!).projectName).toBe("root"); + }); + + it("uses the configured Java module when the resolver does not report a project root", async () => { + launchProjectRoot = undefined; + files["/p/pom.xml"] = "rootpom"; + files["/p/api/pom.xml"] = "api-module"; + const launch = await javaLaunchConfig({ ...app, module: "api" }, "/p"); + expect(JSON.parse(launch.extraJson!).projectName).toBe("api-module"); + }); + it("falls back to the folder name when the project says nothing, including unresolved properties", async () => { expect(await javaProjectName("/p/api")).toBe("api"); files["/p/pom.xml"] = "${revision}"; diff --git a/src/features/debugger/java.ts b/src/features/debugger/java.ts index bb97f8e353..a7127f5b6d 100644 --- a/src/features/debugger/java.ts +++ b/src/features/debugger/java.ts @@ -49,14 +49,19 @@ export async function javaProjectName(root: string): Promise { const descriptor = await readText(join(root, ".project")); const eclipse = /([^<]+)<\/name>/.exec(descriptor)?.[1]?.trim(); if (eclipse) return eclipse; - const pom = await readText(join(root, "pom.xml")); - // A child module's own follows the block, which names the parent. - const own = pom.replace(/[\s\S]*?<\/parent>/, ""); - const artifact = /\s*([^<\s]+)\s*<\/artifactId>/.exec(own)?.[1]; + const artifact = /\s*([^<\s]+)\s*<\/artifactId>/.exec(ownPom(await readText(join(root, "pom.xml"))))?.[1]; if (artifact && !artifact.includes("${")) return artifact; return baseName(root); } +/** A child module's own part of its POM: its follows the block, which names the parent. */ +const ownPom = (pom: string) => pom.replace(/[\s\S]*?<\/parent>/, ""); + +/** A dependency-only Maven module (`packaging=pom`): jdtls has no Java project for it. */ +async function isPomOnlyModule(root: string): Promise { + return /\s*pom\s*<\/packaging>/.test(ownPom(await readText(join(root, "pom.xml")))); +} + /** A file of the project, or "" when it is missing (or when there is no filesystem bridge). */ async function readText(path: string): Promise { try { @@ -224,7 +229,9 @@ export async function javaLaunchConfig( // java-debug resolves the Java project for Evaluate on its own from `mainClass` only when // the class belongs to a project it knows; name the project it imported so that works for // classes compiled outside the language server's build (plain folders, custom outputs). - const project = await javaProjectName(info.projectRoot ?? root); + const projectRoot = info.projectRoot ?? join(root, module); + // A launch from a dependency-only POM names no project: java-debug finds the main class's own. + const project = (await isPomOnlyModule(projectRoot)) ? undefined : await javaProjectName(projectRoot); return { name: rc.name, adapter: JAVA_ADAPTER,