diff --git a/crates/ide-build/src/compile/mod.rs b/crates/ide-build/src/compile/mod.rs index 6e5735639..3d359bb17 100644 --- a/crates/ide-build/src/compile/mod.rs +++ b/crates/ide-build/src/compile/mod.rs @@ -17,8 +17,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_classpath_without_build, module_classpaths, - single_file_classpath, single_file_target, + has_gradle_file_target, javac_step, maven_system_classpath, 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, @@ -986,7 +986,7 @@ fn maven_launch_projects<'a>( } projects.push(p); for dep in &p.dependencies { - if !dep.resolved() || (dep.scope == "test" && (!test || p.pom != start.pom)) { + if !dep.resolved() || dep.scope == "system" || (dep.scope == "test" && (!test || p.pom != start.pom)) { continue; } if let Some(upstream) = reactor.iter().find(|u| { diff --git a/crates/ide-build/src/compile/single.rs b/crates/ide-build/src/compile/single.rs index ff493c2f4..1420328c2 100644 --- a/crates/ide-build/src/compile/single.rs +++ b/crates/ide-build/src/compile/single.rs @@ -180,6 +180,30 @@ pub fn find_javac(env: &BTreeMap) -> String { exe.to_owned() } +/// Existing system-scope dependencies of this module. Maven resolves these from +/// their local files and does not pass them transitively to reactor dependents. +pub fn maven_system_classpath(root: &Path, model: &BuildModel, module: &Path) -> Vec { + let Some(maven) = &model.maven else { return Vec::new() }; + let module = root.join(module); + maven + .projects + .iter() + .find(|p| root.join(&p.dir) == module) + .into_iter() + .flat_map(|p| &p.system_paths) + .filter(|p| p.is_file()) + .cloned() + .collect() +} + +fn with_system_classpath(root: &Path, model: &BuildModel, module: &Path, classpath: String) -> String { + let system = maven_system_classpath(root, model, module); + if system.is_empty() { + return classpath; + } + join_classpath(std::env::split_paths(&classpath).chain(system).map(|p| p.to_string_lossy().into_owned())) +} + /// Dependency classpath of the module: existing reactor class directories plus /// `mvn dependency:build-classpath` (which resolves without compiling anything, /// so `-am` stays cheap). Entries are platform-separated (`;` on Windows). @@ -233,7 +257,7 @@ pub fn module_classpath_without_build( && cached.version == CLASSPATH_CACHE_VERSION && classpath_entries_exist(root, &cached.classpath) { - return Ok(cached.classpath); + return Ok(with_system_classpath(root, model, &target.module, cached.classpath)); } classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel) } @@ -270,7 +294,7 @@ pub fn module_classpaths( && classpath_entries_exist(root, &cached.classpath) { if i == 0 { - return Ok(cached.classpath); + return Ok(with_system_classpath(root, model, &target.module, cached.classpath)); } continue; } @@ -298,7 +322,7 @@ pub fn module_classpaths( } } } - Ok(classpaths.into_iter().next().unwrap()) + Ok(with_system_classpath(root, model, &modules[0], classpaths.into_iter().next().unwrap())) } /// A module whose classpath the Maven probe resolves, with its cache key and file. @@ -346,7 +370,8 @@ fn classpath( compile_first: bool, cancel: &CancellationToken, ) -> IdeResult { - Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap()) + let classpath = classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap(); + Ok(with_system_classpath(root, model, &target.module, classpath)) } /// The classpath of each of `targets` (modules of one reactor) from one Maven probe. @@ -912,6 +937,64 @@ mod tests { assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}"); } + #[cfg(unix)] + #[test] + fn system_jars_augment_maven_javac_and_launch_classpaths() { + use std::os::unix::fs::PermissionsExt; + + let dir = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(dir.path()).unwrap(); + write( + &root, + "pom.xml", + r#"demoparent1 + pomapp + src/main/resources/lib"#, + ); + write( + &root, + "app/pom.xml", + r#"demoparent1 + app + ${lib.dir}/offline.jar + + localoffline1 + system${pom.basedir}/${lib.file} + locallate1 + system${project.basedir}/${lib.dir}/late.jar + localdirectory1 + system${project.basedir}/${lib.dir} + "#, + ); + let jars = "app/src/main/resources/lib"; + write(&root, &format!("{jars}/offline.jar"), ""); + write(&root, "app/src/main/java/demo/Main.java", "class Main {}"); + // The scope-filtered Maven classpath can contain no dependencies. + write(&root, "mvnw", "#!/bin/sh\nmkdir -p app/target\n: > app/target/ide-compile-cp.txt\n"); + fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap(); + + let cache = root.join("cache"); + let model = crate::load(&root, &cache, None); + let module = root.join("app"); + let file = module.join("src/main/java/demo/Main.java"); + let jar = root.join(jars).join("offline.jar"); + let plan = compile_file_plan(&root, &model, &file).unwrap(); + assert!(plan.steps[0].args.windows(2).any(|arg| arg[0] == "-cp" && Path::new(&arg[1]) == jar)); + let cancel = CancellationToken::new(); + let cp = module_classpath(&root, &model, &module, false, None, &cache, &cancel).unwrap(); + let paths: Vec<_> = std::env::split_paths(&cp).collect(); + assert_eq!(paths, [module.join("target/classes"), jar.clone()]); + assert!(maven_system_classpath(&root, &model, &root).is_empty()); + + // Adding a previously absent jar or deleting an old one updates a no-build launch. + fs::remove_file(jar).unwrap(); + write(&root, &format!("{jars}/late.jar"), ""); + fs::remove_file(root.join("mvnw")).unwrap(); + let cp = module_classpath_without_build(&root, &model, &module, false, &cache, &cancel).unwrap(); + let paths: Vec<_> = std::env::split_paths(&cp).collect(); + assert_eq!(paths, [module.join("target/classes"), root.join(jars).join("late.jar")]); + } + /// Modules launched together resolve their classpaths in one Maven probe and leave /// the others' cached; a probe another module breaks still resolves the first one. #[cfg(unix)] diff --git a/crates/ide-build/src/maven.rs b/crates/ide-build/src/maven.rs index 336f8c3a7..5336a7f90 100644 --- a/crates/ide-build/src/maven.rs +++ b/crates/ide-build/src/maven.rs @@ -69,6 +69,9 @@ pub struct MavenProject { pub aggregated: bool, pub plugins: Vec, pub dependencies: Vec, + /// Local classpath entries from the POM. The synced dependency tree has coordinates only. + #[serde(skip)] + pub system_paths: Vec, /// Profile ids declared in this POM. pub profiles: Vec, /// Java feature version the project compiles for (`maven.compiler.release`, `java.version`…). @@ -176,6 +179,7 @@ struct RawDep { kind: Option, classifier: Option, scope: Option, + system_path: Option, optional: bool, } @@ -248,6 +252,7 @@ fn read_dep(e: &Element) -> Option { kind: e.text_of("type"), classifier: e.text_of("classifier"), scope: e.text_of("scope"), + system_path: e.text_of("systemPath"), optional: e.text_of("optional").is_some_and(|o| o == "true"), }) } @@ -1519,7 +1524,13 @@ pub fn load_with_linked_jdk( let packaging = i(pom.packaging.as_deref().unwrap_or("jar")); let managed: HashMap = ctx.managed.iter().map(|m| (m.key(), m)).collect(); let managed_version = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.version.clone()); - let managed_scope = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.scope.clone()); + let scope = |d: &RawDep| { + d.scope + .as_deref() + .or_else(|| managed.get(&d.key()).and_then(|m| m.scope.as_deref())) + .map(i) + .unwrap_or_else(|| "compile".into()) + }; let dependencies = ctx .deps .iter() @@ -1529,11 +1540,24 @@ pub fn load_with_linked_jdk( version: d.version.clone().or_else(|| managed_version(d)).map(|v| i(&v)), kind: d.kind.clone().unwrap_or_else(|| "jar".into()), classifier: d.classifier.clone(), - scope: d.scope.clone().or_else(|| managed_scope(d)).unwrap_or_else(|| "compile".into()), + scope: scope(d), optional: d.optional, ..MavenDependency::default() }) .collect(); + let system_paths = ctx + .deps + .iter() + .filter(|d| scope(d) == "system") + .filter_map(|d| { + let path = d + .system_path + .as_deref() + .or_else(|| managed.get(&d.key()).and_then(|m| m.system_path.as_deref()))?; + let path = i(path); + (!path.contains("${") && Path::new(&path).is_absolute()).then(|| PathBuf::from(path)) + }) + .collect(); let mut plugins: Vec = ctx.plugins.clone(); for a in lifecycle_plugins(&packaging) { @@ -1592,6 +1616,7 @@ pub fn load_with_linked_jdk( aggregated, plugins, dependencies, + system_paths, profiles: ctx.profiles.iter().map(|(id, _)| id.clone()).collect(), java_version: jv, command: wrapper(&canonical_root, &dir_canon), diff --git a/crates/ide-host/src/ops/java.rs b/crates/ide-host/src/ops/java.rs index c2e72cbbc..fcae67de5 100644 --- a/crates/ide-host/src/ops/java.rs +++ b/crates/ide-host/src/ops/java.rs @@ -246,6 +246,7 @@ pub(crate) async fn resolve_launch( append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths)); } info.class_paths = class_paths; + apply_maven_system_classpath(&mut info, root, &model, &module); apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test); if build && !delegated { match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) { @@ -563,6 +564,9 @@ async fn resolve_launch_without_jdtls( }, )?; info.class_paths = class_paths; + if !by_service { + apply_maven_system_classpath(&mut info, root, &model, &module); + } 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() { @@ -681,6 +685,15 @@ fn entry_key(path: &str, windows: bool) -> String { if windows { key.to_lowercase() } else { key } } +fn apply_maven_system_classpath(info: &mut JavaLaunchInfo, root: &Path, model: &BuildModel, module: &Path) { + for path in compile::maven_system_classpath(root, model, module) { + let path = path.to_string_lossy(); + if !info.class_paths.iter().chain(&info.module_paths).any(|entry| same_entry(entry, &path, cfg!(windows))) { + info.class_paths.push(path.into_owned()); + } + } +} + fn apply_library_classpath( info: &mut JavaLaunchInfo, root: &std::path::Path, @@ -1275,6 +1288,34 @@ mod tests { assert!(info.hints[0].contains("offline dependency"), "{:?}", info.hints); } + #[test] + fn java_server_launch_classpath_includes_local_maven_system_jars() { + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap(); + let jar = root.join("src/main/resources/lib/offline.jar"); + std::fs::create_dir_all(jar.parent().unwrap()).unwrap(); + std::fs::write(&jar, "").unwrap(); + std::fs::write( + root.join("pom.xml"), + r#"demoapp1 + localoffline1 + system${pom.basedir}/src/main/resources/lib/offline.jar + "#, + ) + .unwrap(); + let model = ide_build::load(&root, &root.join("cache"), None); + let jar = jar.to_string_lossy().into_owned(); + let mut info = JavaLaunchInfo { class_paths: vec!["classes".into()], ..Default::default() }; + apply_maven_system_classpath(&mut info, &root, &model, &root); + apply_maven_system_classpath(&mut info, &root, &model, &root); + assert_eq!(info.class_paths, ["classes", &jar]); + + info.class_paths.pop(); + info.module_paths.push(jar); + apply_maven_system_classpath(&mut info, &root, &model, &root); + assert_eq!(info.class_paths, ["classes"]); + } + /// Maven's launch classpath lists the module's and its reactor siblings' outputs, which /// the launch already runs from a snapshot: listed twice, MyBatis loads each mapper XML /// twice and fails with "XML fragments parsed from previous mappers already contains value".