From 999d84b18960c6efea53537743cb3f04bf5dd08e Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 23 Nov 2026 22:01:15 +0800 Subject: [PATCH] fix(run): resolve Java launches in attached projects (#5471) Running or debugging a Java main class of a project attached to the window failed to compile (its Maven dependencies were missing): launch preparation used the primary project's root, build model, settings and cache. Run/Debug/test launches now resolve the owning attached project (innermost root containing the module) and use its build model, Maven reactor, settings, classpath and launch-snapshot cache; older saved configurations resolve the same way. --- crates/ide-host/src/mcp/run/configs.rs | 3 +- crates/ide-host/src/ops/build.rs | 15 ++- crates/ide-host/src/ops/build/workspace.rs | 29 +++-- crates/ide-host/src/ops/java.rs | 119 ++++++++++----------- crates/ide-host/src/ops/java/cache.rs | 24 +++++ crates/ide-host/src/ops/run.rs | 5 +- crates/ide-host/src/project.rs | 16 +-- crates/ide-host/tests/workspaces.rs | 101 +++++++++++++++++ src/features/debugger/java.ts | 2 +- src/features/run/contextRun.test.ts | 51 ++++++++- src/features/run/contextRun.ts | 7 +- src/features/run/javaModule.test.ts | 22 ++++ src/platform/javaLaunch.ts | 13 ++- 13 files changed, 312 insertions(+), 95 deletions(-) diff --git a/crates/ide-host/src/mcp/run/configs.rs b/crates/ide-host/src/mcp/run/configs.rs index a50ea9d28..ce3a510a6 100644 --- a/crates/ide-host/src/mcp/run/configs.rs +++ b/crates/ide-host/src/mcp/run/configs.rs @@ -488,7 +488,7 @@ async fn find_java_module(call: &Call, main: &str) -> IdeResult> /// (compile errors are added to `errors`). Other configurations are returned as they are. async fn resolve_jvm_application( call: &Call, - config: RunConfig, + mut config: RunConfig, errors: &mut BuildErrors, ) -> IdeResult> { if !JVM_APPLICATION_KINDS.contains(&config.kind.as_str()) { @@ -544,6 +544,7 @@ async fn resolve_jvm_application( (Some(exec), "java") => exec.clone(), _ => config.command.clone(), }; + config.extras.module = Some(module); Ok(Ok(RunConfig { command, args, ..config })) } diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index 36f6f17c6..8894d4ba1 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -1,6 +1,6 @@ //! Maven / Gradle tool windows (the build model and its background sync) and //! Build › Build Project (compiling with the project's build system). -mod workspace; +pub(super) mod workspace; use super::dependencies::{MavenCentralArtifacts, MavenCentralGroups, MavenCentralVersions}; use crate::ops::Channel; @@ -181,7 +181,7 @@ fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings) /// `model` building with the Maven profiles of the last sync (`-P`), as Maven runs from /// the tool window do. -fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel { +pub(super) fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel { let profiles = ide_build::maven_profiles(cache); if let (Some(m), false) = (&mut model.maven, profiles.is_empty()) { for p in &mut m.projects { @@ -952,16 +952,18 @@ pub async fn build_run( items: Vec::new(), }); } + let mut launch_caches = Vec::new(); let plan = if let Some(id) = cmake { + launch_caches.push(cache.clone()); let configs = super::run::project_configs(&root, &settings, &config_dir)?; cmake_plan(&root, kind, &configs, &id)? } else if let Some(workspace) = ide_workspace::workspace::Workspace::load(&root)? { let mut combined: Option = None; for member in workspace.projects.iter().filter(|p| file.as_ref().is_none_or(|f| f.starts_with(p))) { let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective(); - let member_cache = - if member == &root { cache.clone() } else { cache.join(crate::project::project_key(member)) }; + let member_cache = workspace::cache_at(&root, &cache, member); let model = with_profiles(load(member, &member_cache, &settings), &member_cache); + launch_caches.push(member_cache); let plan = prepare_plan( compile::plan( member, @@ -985,6 +987,7 @@ pub async fn build_run( plan } else { let model = with_profiles(load(&root, &cache, &settings), &cache); + launch_caches.push(cache.clone()); match compile::plan( &root, &model, @@ -1007,7 +1010,9 @@ pub async fn build_run( }); if kind == BuildKind::Rebuild { // The clean removed outputs that earlier launch snapshots still hold. - launch_project.java_launch_snapshots.lock().forget_reusable_snapshots(); + for cache in launch_caches { + launch_project.java_launches.for_cache(&cache).snapshots.lock().forget_reusable_snapshots(); + } } let result = result?; if result.success && single && kind == BuildKind::Build { diff --git a/crates/ide-host/src/ops/build/workspace.rs b/crates/ide-host/src/ops/build/workspace.rs index 27da5d0cb..afc422e40 100644 --- a/crates/ide-host/src/ops/build/workspace.rs +++ b/crates/ide-host/src/ops/build/workspace.rs @@ -1,12 +1,33 @@ use super::*; use std::path::PathBuf; -pub(super) struct Scope { +pub(in crate::ops) struct Scope { pub root: PathBuf, pub cache: PathBuf, pub settings: Settings, } +pub(in crate::ops) fn scope_for(project: &Project, path: &Path) -> IdeResult { + let workspace = ide_workspace::workspace::Workspace::load(&project.root)?; + let root = workspace + .as_ref() + .and_then(|w| w.projects.iter().filter(|p| path.starts_with(p)).max_by_key(|p| p.components().count())) + .unwrap_or(&project.root); + Ok(Scope { + cache: cache_at(&project.root, &project.build_cache_dir(), root), + settings: if root == &project.root { + project.settings.effective() + } else { + project.settings.for_project(root).effective() + }, + root: root.clone(), + }) +} + +pub(super) fn cache_at(window_root: &Path, cache: &Path, root: &Path) -> PathBuf { + if root == window_root { cache.to_owned() } else { cache.join(crate::project::project_key(root)) } +} + pub(super) fn scopes(project: &Project, config: &Path) -> IdeResult> { scopes_at(&project.root, &project.build_cache_dir(), config, project.settings.effective()) } @@ -19,11 +40,7 @@ fn scopes_at(root: &Path, cache: &Path, config: &Path, settings: Settings) -> Id .into_iter() .filter(|p| p.is_dir()) .map(|root| Scope { - cache: if root == window_root { - cache.to_owned() - } else { - cache.join(crate::project::project_key(&root)) - }, + cache: cache_at(window_root, cache, &root), settings: ide_workspace::SettingsStore::load(config, Some(&root)).effective(), root, }) diff --git a/crates/ide-host/src/ops/java.rs b/crates/ide-host/src/ops/java.rs index d5301341e..f18000ad9 100644 --- a/crates/ide-host/src/ops/java.rs +++ b/crates/ide-host/src/ops/java.rs @@ -4,7 +4,7 @@ pub(crate) mod cache; use crate::Host; use ide_command::command; -use super::build::load; +use super::build::{load, with_profiles, workspace}; use ide_build::BuildModel; use ide_build::compile; use ide_core::error::ErrorKind; @@ -46,37 +46,44 @@ pub(crate) async fn resolve_launch( ) -> IdeResult { let started = std::time::Instant::now(); let project = host.project(window)?; - let module = project.root.join(module); + let module = ide_core::project_roots::resolve(&project.root, &module); + let scope = { + 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, test, policy, cancel).await; + return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel).await; } - let waiting = project.java_launches_waiting.add(module.clone(), test, policy); - let settings = project.settings.effective(); + let scope = std::sync::Arc::new(scope); + let launches = project.java_launches.for_cache(&scope.cache); + let waiting = launches.waiting.add(module.clone(), test, policy); + let prefer_maven = scope.settings.languages.java.maven.delegate_build; // A launch builds incrementally unless the configuration asks for Rebuild or NoBuild. let build = policy != BuildPolicy::NoBuild; let full = policy == BuildPolicy::Rebuild; let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build }; - let (model, external, mut delegated, prefer_maven, is_maven) = { - let project = project.clone(); - let settings = settings.clone(); + let (model, external, mut delegated, is_maven) = { + let scope = scope.clone(); + let launches = launches.clone(); let module = module.clone(); tokio::task::spawn_blocking(move || { - project.java_launch_snapshots.lock().initialize(); - let model = load(&project.root, &project.build_cache_dir(), &settings); - let non_java = build && compile::launch_has_non_java_sources(&project.root, &model, &module, test); - let is_maven = - model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module)); - let prefer_maven = settings.languages.java.maven.delegate_build; + launches.snapshots.lock().initialize(); + let root = &scope.root; + let model = load_launch_model(&scope); + let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test); + let is_maven = is_maven_module(root, &model, &module); let delegated = build && delegates_to_external_build( is_maven, policy, non_java, - cache::has_record(&project.root, &project.build_cache_dir(), &module), + cache::has_record(root, &scope.cache, &module), prefer_maven, ); let external = non_java || delegated; - (model, external, delegated, prefer_maven, is_maven) + (model, external, delegated, is_maven) }) .await .map_err(|e| IdeError::internal(e.to_string()))? @@ -101,7 +108,7 @@ pub(crate) async fn resolve_launch( } let model = std::sync::Arc::new(model); let members = if delegated { - build_members(&project, &model, &module, test, prefer_maven, &waiting, cancel).await? + build_members(&project, &scope, &model, &module, test, &waiting, cancel).await? } else { Vec::new() }; @@ -110,7 +117,8 @@ pub(crate) async fn resolve_launch( let cancel = cancel.clone(); tokio::task::spawn_blocking(move || { let _external_build = external_build; - let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings); + let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings); + let local_repo = ide_sdk::apply::maven_local_repository(root, settings); // Module outputs the launch runs from a snapshot of: the originals must not come back. let mut snapshotted = Vec::new(); // The modules of the launches sharing this build also share its classpath probe. @@ -118,8 +126,8 @@ pub(crate) async fn resolve_launch( std::iter::once(module.clone()).chain(members.iter().map(|m| m.module.clone())).collect(); let built = if delegated { let rebuild_on_jdt_errors = rebuild_on_jdt_errors(policy, prefer_maven, info.error_count); - let outputs = project.java_launch_snapshots.lock().build( - &project.root, + let outputs = launches.snapshots.lock().build( + root, &model, &module, cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members }, @@ -132,7 +140,7 @@ pub(crate) async fn resolve_launch( snapshotted = outputs.originals; copies } else if external { - let built = compile::build_for_launch(&project.root, &model, &module, test, build_kind, &cancel)?; + let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel)?; if let Some(failure) = built.failure { if policy != BuildPolicy::MakeAndContinueOnErrors { return Err(IdeError::internal(failure)); @@ -149,24 +157,15 @@ pub(crate) async fn resolve_launch( // m2e runs inside jdtls on the server JDK and can resolve a different // Maven profile/classifier than the module build. Ask the same Maven // process that built the module for its runtime/test dependencies. - let maven_cp = compile::module_classpaths( - &project.root, - &model, - &probed, - test, - local_repo, - &project.build_cache_dir(), - &cancel, - ); + let maven_cp = compile::module_classpaths(root, &model, &probed, test, local_repo, cache, &cancel); merge_maven_launch_classpath(&mut class_paths, &mut info, maven_cp, &snapshotted)?; } else { append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths)); } info.class_paths = class_paths; - apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test); + apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test); if build && !delegated { - let cache_dir = project.build_cache_dir(); - match compile::process_launch_resources(&project.root, &model, &cache_dir, &info.class_paths, &cancel) { + match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) { Ok(tasks) if !tasks.is_empty() => tracing::info!(?tasks, "Processed launch resources with Gradle"), Ok(_) => {} Err(e) if e.kind == ErrorKind::Cancelled => return Err(e), @@ -177,7 +176,7 @@ pub(crate) async fn resolve_launch( } } let compile_ms = started.elapsed().as_millis() - lsp_ms; - finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir); + finish_launch(&mut info, root, &module, settings, &model, &data_dir); if cancel.is_cancelled() { return Err(IdeError::cancelled()); } @@ -194,28 +193,36 @@ pub(crate) async fn resolve_launch( .map_err(|e| IdeError::internal(e.to_string()))? } +fn load_launch_model(scope: &workspace::Scope) -> BuildModel { + with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache) +} + +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)) +} + /// 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. async fn resolve_launch_without_jdtls( host: &Host, project: &std::sync::Arc, module: PathBuf, + scope: workspace::Scope, test: bool, policy: BuildPolicy, cancel: &CancellationToken, ) -> IdeResult { let started = std::time::Instant::now(); - let settings = project.settings.effective(); + let scope = std::sync::Arc::new(scope); let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build }; let (model, built) = { - let (root, cache, settings, module, cancel) = - (project.root.clone(), project.build_cache_dir(), settings.clone(), module.clone(), cancel.clone()); + let (scope, module, cancel) = (scope.clone(), module.clone(), cancel.clone()); tokio::task::spawn_blocking(move || { - let model = load(&root, &cache, &settings); + let model = load_launch_model(&scope); let built = if policy == BuildPolicy::NoBuild { None } else { - Some(compile::build_for_launch(&root, &model, &module, test, kind, &cancel)) + Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel)) }; (model, built) }) @@ -249,9 +256,9 @@ async fn resolve_launch_without_jdtls( let build_ms = started.elapsed().as_millis(); let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?; let data_dir = host.local_data_dir.clone(); - let project = project.clone(); let cancel = cancel.clone(); tokio::task::spawn_blocking(move || { + let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings); match from_server { Some(server) => { info.project_root = server.classpath.project_root; @@ -260,26 +267,14 @@ async fn resolve_launch_without_jdtls( append_unique_class_paths(&mut class_paths, server.classpath.class_paths); } None => { - let is_maven = model - .maven - .as_ref() - .is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module)); - if !is_maven { + if !is_maven_module(root, &model, &module) { return Err(IdeError::unavailable( "Cannot resolve the classpath: the Java language server does not report it \ (java-analyzer/projectClasspath), and the module is not a Maven project", )); } - let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings); - let classpath = compile::module_classpath( - &project.root, - &model, - &module, - test, - local_repo, - &project.build_cache_dir(), - &cancel, - )?; + let local_repo = ide_sdk::apply::maven_local_repository(root, settings); + let classpath = 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()), @@ -287,8 +282,8 @@ async fn resolve_launch_without_jdtls( } } info.class_paths = class_paths; - apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test); - finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir); + apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test); + finish_launch(&mut info, root, &module, settings, &model, &data_dir); if cancel.is_cancelled() { return Err(IdeError::cancelled()); } @@ -445,10 +440,10 @@ fn apply_library_classpath( /// whether its JDT errors call for a clean rebuild (as its own launch would decide). async fn build_members( project: &std::sync::Arc, + scope: &std::sync::Arc, model: &std::sync::Arc, module: &Path, test: bool, - prefer_maven: bool, waiting: &cache::WaitingGuard, cancel: &CancellationToken, ) -> IdeResult> { @@ -456,10 +451,11 @@ async fn build_members( if others.is_empty() { return Ok(Vec::new()); } + let prefer_maven = scope.settings.languages.java.maven.delegate_build; let joining = { - let (project, model, module) = (project.clone(), model.clone(), module.to_path_buf()); + let (scope, model, module) = (scope.clone(), model.clone(), module.to_path_buf()); tokio::task::spawn_blocking(move || { - joining_launches(&project.root, &project.build_cache_dir(), &model, &module, test, others, prefer_maven) + joining_launches(&scope.root, &scope.cache, &model, &module, test, others, prefer_maven) }) .await .map_err(|e| IdeError::internal(e.to_string()))? @@ -500,8 +496,7 @@ fn joining_launches( others .into_iter() .filter(|o| { - let is_maven = - model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == o.module)); + let is_maven = is_maven_module(root, model, &o.module); o.test == test && matches!(o.policy, BuildPolicy::Automatic | BuildPolicy::Make) && compile::launch_reactor(root, model, &o.module).as_ref() == Some(&reactor) diff --git a/crates/ide-host/src/ops/java/cache.rs b/crates/ide-host/src/ops/java/cache.rs index a07e34b7d..56bab0bb5 100644 --- a/crates/ide-host/src/ops/java/cache.rs +++ b/crates/ide-host/src/ops/java/cache.rs @@ -64,6 +64,30 @@ pub(super) struct Member { pub rebuild_on_jdt_errors: bool, } +/// Launches share a build only within the same workspace project's cache. +#[derive(Default)] +pub(crate) struct Sessions(Mutex>>); + +pub(in crate::ops) struct Launches { + pub waiting: Waiting, + pub snapshots: Mutex, +} + +impl Sessions { + pub(in crate::ops) fn for_cache(&self, cache: &Path) -> Arc { + self.0 + .lock() + .entry(cache.to_owned()) + .or_insert_with(|| { + Arc::new(Launches { + waiting: Waiting::default(), + snapshots: Mutex::new(Session::new(cache.to_owned())), + }) + }) + .clone() + } +} + /// Java launches from their start until their build: one launch's Maven run also builds /// the modules of launches still waiting (configurations started together, #3971). #[derive(Default)] diff --git a/crates/ide-host/src/ops/run.rs b/crates/ide-host/src/ops/run.rs index 8eb5b7643..33a755aee 100644 --- a/crates/ide-host/src/ops/run.rs +++ b/crates/ide-host/src/ops/run.rs @@ -242,7 +242,10 @@ fn settings_only( .cloned() }); if workspace.as_ref().is_some_and(|w| w.is_container(&project.root)) || member.is_some() { - if config.extras.module.is_none() && !matches!(config.kind.as_str(), "application" | "spring-boot") { + let jvm = matches!(config.kind.as_str(), "application" | "spring-boot"); + if jvm && member.is_some() && config.cwd.is_none() { + config.cwd = Some(owner.into()); + } else if config.extras.module.is_none() && !jvm { config.extras.module = config.cwd.as_deref().map(ide_core::ipc_path::to_ipc); } ide_run::scope::rebase(config, &project.root, None); diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index 944d09832..c736aefbb 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -51,10 +51,8 @@ pub struct Project { pub(crate) member_excludes: MemberExcludes, /// Per-project cache directory (build tool sync results…). pub cache_dir: PathBuf, - /// Superseded launch snapshots retained until this project session ends. - pub(crate) java_launch_snapshots: Mutex, - /// Java launches waiting for their build, which can share one Maven run. - pub(crate) java_launches_waiting: crate::ops::java::cache::Waiting, + /// Pending launches and retained snapshots, scoped to each workspace project. + pub(crate) java_launches: crate::ops::java::cache::Sessions, /// Reasons this window was already told why Kotlin is debugged with kotlin-debug-adapter. pub(crate) kotlin_debug_notices: Mutex>, /// Database tool window: data sources and their connections. @@ -641,10 +639,7 @@ impl Host { detected_roots, member_excludes, cache_dir: self.local_data_dir.join("cache").join(&project_key), - java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new( - self.local_data_dir.join("cache").join(&project_key).join("build"), - )), - java_launches_waiting: Default::default(), + java_launches: Default::default(), kotlin_debug_notices: Mutex::default(), db, http_history, @@ -891,10 +886,7 @@ impl Host { detected_roots: Arc::default(), member_excludes: Arc::default(), cache_dir: self.local_data_dir.join("cache").join(&project_key), - java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new( - self.local_data_dir.join("cache").join(&project_key).join("build"), - )), - java_launches_waiting: Default::default(), + java_launches: Default::default(), kotlin_debug_notices: Mutex::default(), db, http_history, diff --git a/crates/ide-host/tests/workspaces.rs b/crates/ide-host/tests/workspaces.rs index 15c2904dc..b0fb69a49 100644 --- a/crates/ide-host/tests/workspaces.rs +++ b/crates/ide-host/tests/workspaces.rs @@ -6,6 +6,107 @@ use std::{ time::Duration, }; +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn java_launch_builds_the_owning_workspace_reactor() { + use ide_run::BuildPolicy; + use ide_workspace::{SettingsStore, settings::SettingsScope}; + use std::{fs, os::unix::fs::PermissionsExt}; + + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let config_dir = base.join("config"); + let primary = base.join("primary"); + let sibling = base.join("spring"); + let nested = primary.join("nested"); + let roots = [&primary, &sibling, &nested]; + for (i, root) in roots.into_iter().enumerate() { + fs::create_dir_all(root.join("app")).unwrap(); + fs::write( + root.join("pom.xml"), + format!("demoreactor-{i}1pomapp"), + ) + .unwrap(); + fs::write( + root.join("app/pom.xml"), + format!("demoreactor-{i}1app"), + ) + .unwrap(); + let wrapper = root.join("mvnw"); + fs::write( + &wrapper, + r#"#!/bin/sh +set -eu +printf '%s\n' "$*" >> calls +mkdir -p app/target/classes +case " $* " in *" test-compile "*) mkdir -p app/target/test-classes;; esac +scope=runtime +for arg in "$@"; do + case "$arg" in + -Dmdep.includeScope=*) scope="${arg#*=}";; + esac +done +for arg in "$@"; do + case "$arg" in + -Dmdep.outputFile=*) + touch "app/$scope.jar" + printf '%s\n' "$PWD/app/$scope.jar" > "app/${arg#*=}";; + esac +done +"#, + ) + .unwrap(); + fs::set_permissions(wrapper, fs::Permissions::from_mode(0o755)).unwrap(); + SettingsStore::load(&config_dir, Some(root)) + .set( + SettingsScope::Project, + "languages.java.maven.activeProfiles", + serde_json::json!(format!("member-{i}")), + ) + .unwrap(); + } + // Exercise the build-tool classpath fallback without starting an installed server. + let global = SettingsStore::load(&config_dir, None); + for server in ["jdtls", "java-analyzer", "kmp-lsp"] { + global + .set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false)) + .unwrap(); + } + let host = Host::new(HostConfig { + config_dir, + data_dir: base.join("data"), + local_data_dir: base.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, + }); + for root in roots { + host.trust.decide(root, true, false).unwrap(); + } + host.open_project("main", &primary).unwrap(); + for root in [&sibling, &nested] { + ops::project::attach_workspace(&host, "main", root).unwrap(); + } + for (index, root) in roots.into_iter().enumerate() { + let module = if root == &sibling { root.join("app") } else { root.strip_prefix(&primary).unwrap().join("app") }; + let test = index != 0; + let info = ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next()) + .await + .unwrap(); + let out = root.join("app/target").join(if test { "test-classes" } else { "classes" }); + let jar = root.join("app").join(if test { "test.jar" } else { "runtime.jar" }); + assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out)); + assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == jar)); + let calls = fs::read_to_string(root.join("calls")).unwrap(); + assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}"); + assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}"); + assert!(calls.contains("dependency:build-classpath"), "{calls}"); + } +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn linked_projects_share_navigation_but_keep_files_repositories_and_run_directories() { let temp = tempfile::tempdir().unwrap(); diff --git a/src/features/debugger/java.ts b/src/features/debugger/java.ts index ee984006a..c7bbdfe2b 100644 --- a/src/features/debugger/java.ts +++ b/src/features/debugger/java.ts @@ -140,7 +140,6 @@ export async function javaLaunchConfig( root: string, preparation?: JavaPreparation, ): Promise { - const cwd = rc.cwd ? join(root, rc.cwd) : root; rc = await withEnvFiles(rc, root); const parsed = parseJavaArgs(rc.args); if (!parsed.mainClass) throw new Error(`No main class in '${rc.name}'`); @@ -155,6 +154,7 @@ export async function javaLaunchConfig( }, }, ); + const cwd = resolved.cwd ? join(root, resolved.cwd) : root; if (info.errorCount > 0 && !preparation?.report) notifications().notify({ group: "run", diff --git a/src/features/run/contextRun.test.ts b/src/features/run/contextRun.test.ts index 6f4466ea7..c5082d7a9 100644 --- a/src/features/run/contextRun.test.ts +++ b/src/features/run/contextRun.test.ts @@ -3,8 +3,8 @@ import type { RunConfig } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { menuGroupItems, registerMenuGroup } from "@/workbench/contributions"; import type { MenuItem } from "@/ui"; -import { canDebugProduced, choiceItems, compiledDebugPlan, contextMenuItems } from "./contextRun"; -import { OPTIMISTIC, produceContextChoices, type ToolEnv } from "./producers"; +import { canDebugProduced, choiceItems, compiledDebugPlan, contextMenuItems, projectContext } from "./contextRun"; +import { OPTIMISTIC, produceContext, produceContextChoices, type ToolEnv } from "./producers"; import { gutterTestState, markerIcon, targetMenuItems } from "./runGutter"; import { useRun } from "./store"; import type { RunTarget } from "./targets"; @@ -115,6 +115,53 @@ describe("run context menu group", () => { expect(contextMenuItems("projectView", { paths: [`${ROOT}/src/components`], dirs: [true] })).toEqual([]); }); + it("routes an attached Spring Boot main and its tests through the member's Maven build", () => { + const member = "/work/spring"; + const project = useProject.getState().project!; + useProject.setState({ project: { ...project, workspace: { version: 1, name: "app", projects: [ROOT, member] } } }); + const maven: RunConfig = { ...npmTest, kind: "maven", command: "mvn", args: ["test"], debugAdapter: null }; + useRun.setState({ + configs: [ + { ...maven, id: "maven:test" }, + { ...maven, id: "member:test", cwd: member }, + ], + }); + const content = [ + "package demo;", + "import org.springframework.boot.SpringApplication;", + "import org.springframework.boot.autoconfigure.SpringBootApplication;", + "@SpringBootApplication", + "public class App {", + " public static void main(String[] args) { SpringApplication.run(App.class, args); }", + "}", + ].join("\n"); + const main = { ...projectContext(), path: `${member}/src/main/java/demo/App.java`, content, line: 5 }; + expect(produceContext(main, OPTIMISTIC)?.config).toMatchObject({ + kind: "spring-boot", + module: member, + args: ["-cp", "${classpath}", "demo.App"], + }); + expect( + produceContext( + { + ...main, + path: `${member}/src/test/java/demo/AppTest.java`, + content: "package demo;\nclass AppTest {\n @Test\n void starts() {}\n}", + line: 3, + }, + OPTIMISTIC, + )?.config, + ).toMatchObject({ + kind: "maven", + cwd: member, + args: ["test", "-Dtest=demo.AppTest#starts", "-Dsurefire.failIfNoSpecifiedTests=false"], + }); + expect(produceContext({ ...main, path: `${ROOT}/src/main/java/demo/App.java` }, OPTIMISTIC)?.config).toMatchObject({ + kind: "spring-boot", + module: "", + }); + }); + it("shows nothing when no producer matches or for several paths", () => { expect(contextMenuItems("editor", { paths: [`${ROOT}/README.md`], text: "# hi", line: 0 })).toEqual([]); expect(contextMenuItems("projectView", { paths: [`${ROOT}/a.js`, `${ROOT}/b.js`], dirs: [false, false] })).toEqual( diff --git a/src/features/run/contextRun.ts b/src/features/run/contextRun.ts index 879b0ee29..553460309 100644 --- a/src/features/run/contextRun.ts +++ b/src/features/run/contextRun.ts @@ -50,15 +50,16 @@ async function ensureConfigs() { } /** The focused editor's file, text and caret line. */ -/** Project folders outside its root: Project Structure content roots and Gradle modules (as of the last sync). */ +/** Attached projects, Project Structure content roots and external Gradle modules. */ export function projectContentRoots(): string[] { - const own = effectiveContentRoots(validateProjectStructure(useProject.getState().settings?.projectStructure)); + const { project, settings } = useProject.getState(); + const own = effectiveContentRoots(validateProjectStructure(settings?.projectStructure)); // The build model keeps the folders of modules outside the project absolute. const gradle = (useBuildModel.getState().model?.gradle ?? []) .flatMap((g) => g.projects) .map((p) => p.dir) .filter((d) => isAbsolute(d)); - return [...new Set([...own, ...gradle])]; + return [...new Set([...(project?.workspace?.projects ?? []), ...own, ...gradle])]; } const isAbsolute = (p: string) => p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p); diff --git a/src/features/run/javaModule.test.ts b/src/features/run/javaModule.test.ts index f448232f7..5d39c46f3 100644 --- a/src/features/run/javaModule.test.ts +++ b/src/features/run/javaModule.test.ts @@ -68,6 +68,7 @@ beforeEach(() => { afterEach(() => { resetRuns(); _resetI18nForTests(); + useProject.setState({ project: null }); }); it.each(["sibling", "/outside/modules"])("runs from %s using the stored module's classpath", async (cwd) => { @@ -142,6 +143,27 @@ it("finds the source module for an old saved configuration without a module", as ); }); +it.each([null, "/elsewhere"])("recovers an attached module from its indexed path with cwd %s", async (cwd) => { + const root = "/p"; + const member = "/other/spring"; + const module = `${member}/web`; + useProject.setState({ + project: { root, workspace: { version: 1, name: "demo", projects: [root, member] } } as never, + }); + ipc.findFiles.mockResolvedValueOnce({ + status: "ok", + data: [{ path: `${module}/src/main/java/a/Main.java`, relPath: "spring/web/src/main/java/a/Main.java" }], + }); + const session = await startRun({ ...config, cwd }); + expect(session?.status).toBe("running"); + expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(module, false, "automatic", expect.any(Number)); + expect(ipc.runStart).toHaveBeenCalledWith( + expect.objectContaining({ cwd: cwd ?? module, module }), + expect.anything(), + expect.any(Number), + ); +}); + it.each([["-cp", "lib/*"], []])("colours Spring Boot runs without classpath resolution (%j)", async (...classpath) => { const args = ["-Xmx256m", ...classpath, "a.Main", "--spring.profiles.active=dev"]; const boot = { ...config, kind: "spring-boot", args }; diff --git a/src/platform/javaLaunch.ts b/src/platform/javaLaunch.ts index a00a3ee65..a1a31660f 100644 --- a/src/platform/javaLaunch.ts +++ b/src/platform/javaLaunch.ts @@ -14,6 +14,7 @@ import { type RequestId, } from "@/platform/ipc"; import { tx } from "@/platform/i18n"; +import { projectFolder, relativePath, useProject } from "@/platform/project"; import { useBuildPresentation } from "@/platform/projectPresentation"; import { isRemoteWindow } from "@/platform/remote"; @@ -198,6 +199,7 @@ export async function findJavaModule(config: RunConfig): Promise /** Module directories (as {@link jvmModuleDir}) of the project's sources declaring the class `binaryName`. */ export async function classModules(binaryName: string): Promise { + const root = useProject.getState().project?.root; const outer = binaryName.split("$")[0]!; const simple = outer.slice(outer.lastIndexOf(".") + 1); const pkg = outer.slice(0, Math.max(0, outer.lastIndexOf("."))); @@ -210,7 +212,7 @@ export async function classModules(binaryName: string): Promise { for (const file of matches) { const text = await call(commands.fsReadText(file.path)); const sourcePackage = /^\s*package\s+([\w.]+)\s*[;\r\n]/m.exec(text)?.[1] ?? ""; - if (sourcePackage === pkg) modules.add(jvmModuleDir(file.relPath, configs)); + if (sourcePackage === pkg) modules.add(jvmModuleDir(root ? relativePath(root, file.path) : file.relPath, configs)); } return [...modules]; } @@ -291,5 +293,12 @@ export async function prepareJavaLaunch(config: RunConfig, preparation: JavaPrep } if (parsed.classpath && !info.classPaths.length) throw new Error(tx("The classpath is empty: is the module imported by the Java language server?")); - return { module, info, resolved: resolveJavaCommand(config, info) }; + const resolved = resolveJavaCommand({ ...config, module }, info); + const project = useProject.getState().project; + if (resolved.cwd == null && project?.workspace) { + const path = /^(?:[A-Za-z]:)?\//.test(module) ? module : `${project.root}/${module}`; + const owner = projectFolder(project, path); + if (owner && owner.root !== project.root) resolved.cwd = path; + } + return { module, info, resolved }; }