From 7ff13704ff9ee12f56817070feda7f0a71424985 Mon Sep 17 00:00:00 2001 From: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:32:04 +0530 Subject: [PATCH] fix(maven): keep a model with JDK-activated modules current after a reload (#7854) When a profile activated by added a module, the Maven model stayed out of date after every reload and its resolved dependencies were dropped: the sync read the POMs without a JDK while the host loads the model with the JDK Maven runs on, so their build-file hashes never matched. The sync now gets the same JDK and records which conditions matched; switching to a JDK that flips one makes the model out of date, any other JDK change does not. The Dependency Analyzer model read by plugins loads the same way. Caches from before keep their state. Co-authored-by: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> --- crates/ide-build/src/maven.rs | 6 ++ crates/ide-build/src/sync.rs | 106 ++++++++++++++++++++++++- crates/ide-host/src/ops/build.rs | 131 +++++++++++++++++++++++-------- 3 files changed, 208 insertions(+), 35 deletions(-) diff --git a/crates/ide-build/src/maven.rs b/crates/ide-build/src/maven.rs index 4d83cb3214..770310cd34 100644 --- a/crates/ide-build/src/maven.rs +++ b/crates/ide-build/src/maven.rs @@ -43,6 +43,10 @@ pub struct MavenModel { /// Build files changed since that sync. pub stale: bool, pub sync_error: Option, + /// The `` values of the projects' own POMs that the JDK matches. + #[serde(skip)] + #[specta(skip)] + pub(crate) jdk_activations: std::collections::BTreeSet, } #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] @@ -1620,6 +1624,8 @@ pub fn load_with_linked_jdk( for p in resolver.active(&pom.profiles) { module_names.extend(p.modules.iter().cloned()); } + let jdks = pom.profiles.iter().filter_map(|p| p.activation_jdk.as_ref()); + model.jdk_activations.extend(jdks.filter(|spec| jdk_matches(spec, jdk_version)).cloned()); let mut modules: Vec = Vec::new(); for m in module_names { let mut mp = crate::gradle::normalize(&dir.join(i(&m))); diff --git a/crates/ide-build/src/sync.rs b/crates/ide-build/src/sync.rs index 18234edfc5..36dad3c24e 100644 --- a/crates/ide-build/src/sync.rs +++ b/crates/ide-build/src/sync.rs @@ -10,7 +10,7 @@ use crate::process::{self, Output}; use ide_core::{CancellationToken, IdeError, IdeResult}; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use specta::Type; -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::path::{Path, PathBuf}; use std::sync::{Arc, LazyLock, Mutex}; use std::time::SystemTime; @@ -32,6 +32,8 @@ pub struct SyncOptions { pub profiles: Vec, /// Extra environment (`JAVA_HOME`). pub env: BTreeMap, + /// Major version of the JDK Maven runs on, the same as the model is loaded with. + pub jdk_version: Option, /// Maven launcher replacing the project's `mvnw` / `mvn` (Settings › Maven home). pub maven_command: Option, /// Resolved Gradle launcher from Settings. @@ -62,6 +64,9 @@ struct MavenCache { /// The trees list omitted occurrences (`-Dverbose`); older caches are reloaded. #[serde(default)] verbose: bool, + /// [`MavenModel::jdk_activations`] of the sync; `None` in caches from before they were recorded. + #[serde(default)] + jdk_activations: Option>, } #[derive(Clone, Debug, Default, Serialize, Deserialize)] @@ -233,7 +238,9 @@ pub fn apply_maven_cache(root: &Path, cache_dir: &Path, model: &mut MavenModel) } model.synced_at = Some(cache.at_ms); model.sync_error = cache.error; - let changed = cache.hash != hash_files(&maven::build_files(root, model)); + // Another JDK can switch profiles of the same build files. + let changed = cache.hash != hash_files(&maven::build_files(root, model)) + || cache.jdk_activations.is_some_and(|jdks| jdks != model.jdk_activations); model.stale = !cache.verbose || changed; // A cache older than the current build files: its effective-POM plugins and // resolved dependencies would hide what the POMs declare now (a just added @@ -368,10 +375,11 @@ pub fn sync_maven( cancel: &CancellationToken, progress: &dyn Fn(SyncProgress), ) -> IdeResult<()> { - let mut model = maven::load_with_linked( + let mut model = maven::load_with_linked_jdk( root, maven::default_local_repo(), &options.maven_settings.profiles(&options.profiles), + options.jdk_version, &options.maven_settings.linked_projects, ); maven::UnlinkedProjects::from_model(&model, &options.maven_settings).filter(&mut model); @@ -380,6 +388,7 @@ pub fn sync_maven( version: MAVEN_CACHE_VERSION, hash: hash_files(&maven::build_files(root, &model)), verbose: true, + jdk_activations: Some(model.jdk_activations.clone()), ..MavenCache::default() }; // Where the build resolves its jars, and therefore where the plugin goals are read from. @@ -683,6 +692,7 @@ mod tests { at_ms: 5.0, error: None, verbose: true, + jdk_activations: None, projects: vec![CachedMavenProject { key: "g:a".into(), plugins: vec![maven::plugin( @@ -733,6 +743,7 @@ mod tests { at_ms: 5.0, error: None, verbose: true, + jdk_activations: None, projects: vec![CachedMavenProject { key: "g:a".into(), plugins: vec![maven::plugin( @@ -1055,6 +1066,95 @@ mod tests { assert_eq!(std::fs::metadata(&mvnw).unwrap().permissions().mode() & 0o777, 0o644); } + /// `root` with module `core`, and what `profile` adds when the JDK activates it: the module + /// `modern` or only a property. Synced with `jdk` by a launcher printing `core`'s tree. + #[cfg(unix)] + fn synced_with_a_jdk_profile(base: &Path, profile: &str, jdk: Option) -> (PathBuf, PathBuf) { + use std::os::unix::fs::PermissionsExt; + let (root, cache) = (base.join("p"), base.join("cache")); + let project = "g1"; + for module in ["core", "modern"] { + std::fs::create_dir_all(root.join(module)).unwrap(); + let pom = format!("{project}{module}"); + std::fs::write(root.join(module).join("pom.xml"), pom).unwrap(); + } + let pom = format!( + "{project}rootpomcore\ + modern[11,){profile}\ + " + ); + std::fs::write(root.join("pom.xml"), pom).unwrap(); + let launcher = base.join("mvn"); + let tree = "[INFO] --- dependency:3.8.1:tree (default-cli) @ core ---\\n[INFO] g:core:jar:1\\n\ + [INFO] \\\\- g:lib:jar:1:compile\\n[INFO] \\\\- g:transitive:jar:1:compile\\n"; + std::fs::write(&launcher, format!("#!/bin/sh\nprintf '{tree}'\n")).unwrap(); + std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap(); + let options = SyncOptions { + maven_command: Some(launcher.to_string_lossy().into_owned()), + jdk_version: jdk, + ..Default::default() + }; + sync_maven(&root, &cache, &options, &CancellationToken::new(), &|_| {}).unwrap(); + (root, cache) + } + + #[cfg(unix)] + fn loaded_with_jdk((root, cache): &(PathBuf, PathBuf), jdk: Option) -> MavenModel { + crate::load_linked_with_jdk(root, cache, None, &Default::default(), &Default::default(), jdk).maven.unwrap() + } + + #[cfg(unix)] + const MODULE: &str = "modern"; + #[cfg(unix)] + const PROPERTY: &str = "1"; + + #[cfg(unix)] + #[test] + fn a_synced_model_with_a_jdk_profile_is_current() { + for (profile, jdk, modules) in + [(MODULE, Some(17), 3), (MODULE, Some(8), 2), (MODULE, None, 2), (PROPERTY, Some(17), 2)] + { + let tmp = tempfile::tempdir().unwrap(); + let model = loaded_with_jdk(&synced_with_a_jdk_profile(tmp.path(), profile, jdk), jdk); + assert_eq!(model.projects.len(), modules, "{profile} {jdk:?}"); + assert!(!model.stale, "{profile} {jdk:?}"); + let core = model.projects.iter().find(|p| p.artifact_id == "core").unwrap(); + assert_eq!(core.dependencies[0].children[0].artifact_id, "transitive", "{profile} {jdk:?}"); + } + } + + #[cfg(unix)] + #[test] + fn a_jdk_change_is_stale_when_it_switches_a_profile() { + for profile in [MODULE, PROPERTY] { + for (synced, loaded, stale) in [ + (Some(17), Some(21), false), + (Some(17), Some(8), true), + (Some(8), Some(17), true), + (Some(17), None, true), + (None, Some(17), true), + (None, Some(8), false), + ] { + let tmp = tempfile::tempdir().unwrap(); + let model = loaded_with_jdk(&synced_with_a_jdk_profile(tmp.path(), profile, synced), loaded); + assert_eq!(model.stale, stale, "{profile} {synced:?} {loaded:?}"); + let core = model.projects.iter().find(|p| p.artifact_id == "core").unwrap(); + assert_eq!(core.dependencies.is_empty(), stale, "{profile} {synced:?} {loaded:?}"); + } + } + } + + #[cfg(unix)] + #[test] + fn a_sync_from_before_jdk_profiles_were_recorded_stays_current() { + let tmp = tempfile::tempdir().unwrap(); + let project = synced_with_a_jdk_profile(tmp.path(), PROPERTY, Some(17)); + let mut json: serde_json::Value = read_cache(&project.1, MAVEN_CACHE).unwrap(); + assert!(json.as_object_mut().unwrap().remove("jdk_activations").is_some()); + write_cache(&project.1, MAVEN_CACHE, &json).unwrap(); + assert!(!loaded_with_jdk(&project, Some(17)).stale); + } + #[cfg(unix)] #[test] fn maven_sync_runs_the_daemon_command_serially() { diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index df01bf6c55..b7928f63bf 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -74,14 +74,7 @@ fn maven_modules( /// the Maven home and options from Settings › Maven. pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel { let jdk = ide_sdk::apply::project_jdk(root, settings); - let mut model = ide_build::load_linked_with_jdk( - root, - cache, - ide_sdk::apply::maven_local_repository(root, settings), - &settings.languages.java.maven, - &settings.languages.java.gradle, - ide_sdk::apply::maven_jdk(root, settings, None).map(|jdk| jdk.major), - ); + let mut model = load_synced(root, cache, settings); if let Some(m) = &mut model.maven { let mvn = ide_sdk::apply::maven_command(root, settings); let options = ide_sdk::apply::maven_options(root, settings); @@ -127,6 +120,49 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel { model } +/// The build model as [`sync_options`] syncs it: a load that differs in the JDK or the linked +/// projects finds its own last sync out of date. +fn load_synced(root: &Path, cache: &Path, settings: &Settings) -> BuildModel { + ide_build::load_linked_with_jdk( + root, + cache, + ide_sdk::apply::maven_local_repository(root, settings), + &settings.languages.java.maven, + &settings.languages.java.gradle, + maven_jdk_version(root, settings), + ) +} + +/// The JDK `` profiles are matched against. +fn maven_jdk_version(root: &Path, settings: &Settings) -> Option { + ide_sdk::apply::maven_jdk(root, settings, None).map(|jdk| jdk.major) +} + +fn sync_options( + root: &Path, + settings: &Settings, + current: &BuildModel, + offline: bool, + profiles: &[String], +) -> SyncOptions { + let env = current + .maven + .as_ref() + .and_then(|m| m.projects.iter().find(|p| !p.env.is_empty())) + .map(|p| p.env.clone()) + .unwrap_or_default(); + SyncOptions { + offline, + profiles: profiles.to_vec(), + env, + jdk_version: maven_jdk_version(root, settings), + maven_command: ide_sdk::apply::maven_command(root, settings).map(|p| p.to_string_lossy().into_owned()), + maven_options: ide_sdk::apply::maven_options(root, settings), + maven_settings: settings.languages.java.maven.clone(), + gradle_command: None, + } +} + /// POM navigation follows the same profile choices as the last Maven sync and /// resolves JDK-activated profiles with the project's selected Maven runtime. fn pom_navigation_options(project: &Project, settings: &Settings) -> PomNavigationOptions { @@ -140,7 +176,7 @@ fn pom_navigation_options(project: &Project, settings: &Settings) -> PomNavigati local_repo: ide_sdk::apply::maven_local_repository(&project.root, settings) .or_else(ide_build::maven::default_local_repo), profiles, - jdk_version: ide_sdk::apply::maven_jdk(&project.root, settings, None).map(|jdk| jdk.major), + jdk_version: maven_jdk_version(&project.root, settings), } } @@ -524,21 +560,7 @@ pub async fn build_sync( false }); } - let env = current - .maven - .as_ref() - .and_then(|m| m.projects.iter().find(|p| !p.env.is_empty())) - .map(|p| p.env.clone()) - .unwrap_or_default(); - let options = SyncOptions { - offline, - profiles: profiles.clone(), - env, - maven_command: ide_sdk::apply::maven_command(root, settings).map(|p| p.to_string_lossy().into_owned()), - maven_options: ide_sdk::apply::maven_options(root, settings), - maven_settings: settings.languages.java.maven.clone(), - gradle_command: None, - }; + let options = sync_options(root, settings, ¤t, offline, &profiles); let progress = |p: SyncProgress| { let _ = on_progress.send(p); }; @@ -808,14 +830,7 @@ pub(crate) fn analyzed_dependencies( ) -> IdeResult { let mut graph = crate::plugins::BuildGraph::default(); for scope in workspace::scopes(project, config)?.iter().filter(|s| root == project.root || s.root == root) { - let settings = &scope.settings; - let model = ide_build::load_linked( - &scope.root, - &scope.cache, - ide_sdk::apply::maven_local_repository(&scope.root, settings), - &settings.languages.java.maven, - &settings.languages.java.gradle, - ); + let model = load_synced(&scope.root, &scope.cache, &scope.settings); graph.maven.extend(model.maven.into_iter().flat_map(|m| m.projects)); for build in &model.gradle { let reports = @@ -1740,6 +1755,58 @@ mod build_tool_settings_tests { } } + /// Each root (a project, or a member of a workspace) with its own JDK and a linked reactor. + #[cfg(unix)] + #[test] + fn a_maven_sync_is_current_for_the_jdk_of_its_root() { + use std::os::unix::fs::PermissionsExt; + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let mvn = base.join("maven/bin/mvn"); + std::fs::create_dir_all(mvn.parent().unwrap()).unwrap(); + std::fs::write(&mvn, "#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&mvn, std::fs::Permissions::from_mode(0o755)).unwrap(); + for (name, version) in [("jdk8", "1.8"), ("jdk17", "17"), ("jdk21", "21")] { + let home = base.join(name); + std::fs::create_dir_all(home.join("bin")).unwrap(); + std::fs::write(home.join("bin/java"), "").unwrap(); + std::fs::write(home.join("release"), format!("JAVA_VERSION=\"{version}\"\n")).unwrap(); + } + let reactor = |dir: &Path, jdk: &str| { + std::fs::create_dir_all(dir.join("extra")).unwrap(); + let pom = format!( + "ga1pom\ + p{jdk}\ + extra" + ); + std::fs::write(dir.join("pom.xml"), pom).unwrap(); + let module = "gextra1"; + std::fs::write(dir.join("extra/pom.xml"), module).unwrap(); + }; + let scope = |name: &str, jdk: &str| { + let mut settings = Settings::default(); + settings.languages.java.jdk = base.join(jdk).to_string_lossy().into_owned(); + settings.languages.java.maven.home = base.join("maven").to_string_lossy().into_owned(); + settings.languages.java.maven.linked_projects = vec!["linked/pom.xml".into()]; + (base.join(name), base.join(name).join("cache"), settings) + }; + let maven = |(root, cache, settings): &(PathBuf, PathBuf, Settings)| { + load(root, cache, settings).maven.map(|m| (m.projects.len(), m.stale)).unwrap() + }; + let scopes = [scope("first", "jdk8"), scope("second", "jdk17"), scope("third", "jdk21")]; + for scope in &scopes { + let (root, cache, settings) = scope; + reactor(root, "[11,)"); + reactor(&root.join("linked"), "[21,)"); + let current = load(root, cache, settings); + let options = sync_options(root, settings, ¤t, false, &[]); + ide_build::sync_maven(root, cache, &options, &ide_core::CancellationToken::new(), &|_| {}).unwrap(); + } + assert_eq!(scopes.each_ref().map(maven), [(2, false), (3, false), (4, false)]); + assert_eq!(maven(&scope("second", "jdk8")), (2, true)); + assert_eq!(maven(&scope("second", "jdk21")), (4, true)); + } + #[test] fn model_for_sync_tasks_and_compile_uses_gradle_settings() { let tmp = tempfile::tempdir().unwrap();