From b5f7f0f4728a3f3b4dc78bc8dc8b837e4e974361 Mon Sep 17 00:00:00 2001 From: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:51:56 +0530 Subject: [PATCH] fix(maven): turn on profiles by property, file, JDK and .mvn/maven.config as Maven does (#8205) Profiles Maven turns on by a , a file that exists or is missing, -P in .mvn/maven.config or in settings.xml were left out of the IDE's Maven model: their modules were missing from the Maven tool window, Build Module on them failed with "no linked Maven project found for module", and a root mvn test never brought their test reports to the Run window. The previous matcher also compared Rust's OS names (macos, x86_64) instead of Java's, and ignored an unmet next to a matching . Profiles are now chosen by one evaluator (maven/activation.rs) that follows Maven 3.9 for the model, the reactor scans and POM navigation: every condition of an must hold, is compared with what Java reports (Mac OS X, aarch64, amd64 on Linux), a -P entry that turns a profile off wins whatever the order, activeByDefault profiles step aside for any other profile of their POM that is on, and a parent's file condition is checked in the folder of the module being built. Such profiles show as on by default and untick with -P !id. The reactor scan for test reports also gets the JDK for profiles. Refs #8171 Co-authored-by: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> --- crates/ide-build/src/lib.rs | 63 ++- crates/ide-build/src/maven.rs | 439 ++++++++++++--------- crates/ide-build/src/maven/activation.rs | 463 +++++++++++++++++++++++ crates/ide-build/src/sync.rs | 7 +- crates/ide-host/src/ops/build.rs | 69 +++- crates/ide-host/src/ops/run.rs | 9 +- src/bindings.ts | 5 + 7 files changed, 853 insertions(+), 202 deletions(-) create mode 100644 crates/ide-build/src/maven/activation.rs diff --git a/crates/ide-build/src/lib.rs b/crates/ide-build/src/lib.rs index 1a80427112..e526a082ef 100644 --- a/crates/ide-build/src/lib.rs +++ b/crates/ide-build/src/lib.rs @@ -98,9 +98,10 @@ pub fn load_linked_with_jdk( maven_jdk_version: Option, ) -> BuildModel { let maven = maven::has_projects(root, settings).then(|| { - let profiles = settings.profiles(&sync::maven_profiles(cache_dir)); + let activation = + maven::ProfileActivation::new(root, settings, &sync::maven_profiles(cache_dir), maven_jdk_version); let repo = maven_repo.or_else(maven::default_local_repo); - let mut m = maven::load_with_linked_jdk(root, repo, &profiles, maven_jdk_version, &settings.linked_projects); + let mut m = maven::load_with_activation(root, repo, &activation, &settings.linked_projects); maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m); // The user settings' profiles can be chosen too (`-P` applies to them as well). if let Some(settings_file) = maven::user_settings_file(root, settings) { @@ -111,12 +112,6 @@ pub fn load_linked_with_jdk( m.profiles.push(p); } } - let active_in_settings = maven::settings_active_profiles(&settings_file); - for existing in &mut m.profiles { - if active_in_settings.iter().any(|id| id == &existing.id) { - existing.active_by_default = true; - } - } } sync::apply_maven_cache(root, cache_dir, &mut m); m @@ -167,8 +162,8 @@ pub fn maven_external_roots( ) -> Vec { let mut dirs = maven::external_pom_dirs(root, &settings.linked_projects); if trusted { - let profiles = settings.profiles(&sync::maven_profiles(cache_dir)); - dirs.extend(maven::reactor_external_dirs(root, &profiles, &settings.unlinked_projects)); + let activation = maven::ProfileActivation::new(root, settings, &sync::maven_profiles(cache_dir), None); + dirs.extend(maven::reactor_external_dirs(root, &activation, &settings.unlinked_projects)); } let owned: Vec = dirs.iter().map(|dir| dir.to_string_lossy().into_owned()).collect(); gradle::external_roots(root, owned.iter().map(String::as_str)) @@ -344,6 +339,47 @@ mod tests { assert_eq!(roots(&settings, true), [a, e]); } + #[test] + fn a_profile_maven_turns_on_by_itself_is_shown_on_and_unticking_it_turns_it_off() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + for module in ["extras", "it"] { + std::fs::create_dir(root.join(module)).unwrap(); + std::fs::write(root.join(module).join("pom.xml"), "m").unwrap(); + } + std::fs::write( + root.join("pom.xml"), + r#"rootpom + devtrue + full!quickextras + ciit + "#, + ) + .unwrap(); + std::fs::create_dir(root.join(".mvn")).unwrap(); + std::fs::write(root.join(".mvn/maven.config"), "-Pci\n").unwrap(); + let cache = root.join("cache"); + let settings = ide_core::settings::MavenSettings { + user_settings: root.join("settings.xml").to_string_lossy().into_owned(), + ..Default::default() + }; + let load = || load_linked(root, &cache, None, &settings, &Default::default()).maven.unwrap(); + let flags = + |m: &maven::MavenModel| m.profiles.iter().map(|p| (p.id.clone(), p.active_by_default)).collect::>(); + let pair = |id: &str, on: bool| (id.to_owned(), on); + + // On by default (the tool window's grey check), so `dev` steps aside as it does in Maven. + let model = load(); + assert_eq!(flags(&model), [pair("dev", false), pair("full", true), pair("ci", true)]); + assert_eq!(model.projects[0].modules, ["extras/pom.xml", "it/pom.xml"]); + + // Unticked: off in the model, still on by default so the tool window keeps passing `-P !id`. + save_maven_profiles(&cache, &["!full".into(), "!ci".into()]).unwrap(); + let model = load(); + assert_eq!(flags(&model), [pair("dev", true), pair("full", true), pair("ci", true)]); + assert!(model.projects[0].modules.is_empty()); + } + #[test] fn settings_profiles_and_checkbox_choices_control_modules_before_sync() { let tmp = tempfile::tempdir().unwrap(); @@ -387,7 +423,7 @@ mod tests { root.join("child/pom.xml"), r#"demoroot1.0 child - child-defaulttrue"#, + child-defaultTRUE"#, ) .unwrap(); let settings_xml = root.join("settings.xml"); @@ -407,8 +443,9 @@ mod tests { flags.contains(&("test3", true)), "activeProfile from settings.xml marks POM profile active: {flags:?}" ); - assert!(flags.contains(&("dev", true)), "case-insensitive activeByDefault: {flags:?}"); - assert!(flags.contains(&("child-default", true)), "child module activeByDefault: {flags:?}"); + // As in Maven, `dev` steps aside: settings.xml turns on test3 of the same POM. + assert!(flags.contains(&("dev", false)), "activeByDefault beside an active profile: {flags:?}"); + assert!(flags.contains(&("child-default", true)), "case-insensitive activeByDefault of a module: {flags:?}"); } #[test] diff --git a/crates/ide-build/src/maven.rs b/crates/ide-build/src/maven.rs index 7830f9467e..404646103c 100644 --- a/crates/ide-build/src/maven.rs +++ b/crates/ide-build/src/maven.rs @@ -16,9 +16,13 @@ use std::io::Read; use std::path::{Path, PathBuf}; use std::sync::{Mutex, OnceLock}; +mod activation; pub mod completion; pub mod sources; +pub use activation::ProfileActivation; +use activation::{Activation, Env, MavenConfig}; + /// Lets the IDE's own Maven runs (Reload, Build) use what the local repository already /// has. Maven 3.9 re-resolves an artifact whose recorded origin repository (`_remote.repositories`) /// isn't declared in the build, such as a vendor jar downloaded through another project or @@ -258,6 +262,9 @@ pub struct MavenProfile { #[specta(optional)] pub project_root: Option, pub id: String, + /// On unless the Maven tool window turns it off: `activeByDefault` while no other profile of + /// its POM is on, its `` holds, or `.mvn/maven.config`, Settings or `settings.xml` + /// turn it on. Unticking such a profile passes `-P !id`. pub active_by_default: bool, } @@ -313,11 +320,7 @@ impl RawPlugin { #[derive(Clone, Debug, Default)] struct RawProfile { id: String, - active_by_default: bool, - /// `` (the common `1.8`, `21` and `[17,)` forms). - activation_jdk: Option, - /// `` (``, ``, ``; Maven matches all present fields). - activation_os: Option, + activation: Activation, modules: Vec, properties: Vec<(String, String)>, deps: Vec, @@ -326,55 +329,6 @@ struct RawProfile { managed_plugins: Vec, } -/// ``: the fields the POM names, all of which Maven requires to match. -#[derive(Clone, Debug, Default, PartialEq)] -struct RawOsActivation { - name: Option, - family: Option, - arch: Option, -} - -impl RawOsActivation { - /// Whether this machine satisfies the activation: every named field matches, as Maven's - /// `OsActivation` does. Families map as Maven's `OsUtils` (`windows`, `unix`/`linux`, - /// `mac`/`darwin`); a name matches the running OS name or its family alias. - fn matches(&self) -> bool { - let os = std::env::consts::OS; // "macos" | "windows" | "linux" - let arch = std::env::consts::ARCH; // "x86_64" | "aarch64" - fn family_of(name: &str) -> &str { - match name { - "macos" | "darwin" => "mac", - "windows" => "windows", - "linux" => "unix", - other => other, - } - } - let running_family = family_of(os); - // Absent fields impose no constraint (Maven matches only what the POM names); a leading - // `!` negates the field, as in Maven's `!windows`. - let ok = |value: Option<&String>, f: &dyn Fn(&str) -> bool| { - value.is_none_or(|v| match v.trim().strip_prefix('!') { - Some(negated) => !f(negated.trim()), - None => f(v.trim()), - }) - }; - let name_ok = ok(self.name.as_ref(), &|v| { - v.eq_ignore_ascii_case(os) || v.eq_ignore_ascii_case(running_family) || family_of(v) == running_family - }); - let family_ok = ok(self.family.as_ref(), &|v| { - v.eq_ignore_ascii_case(running_family) - || (v.eq_ignore_ascii_case("unix") && matches!(running_family, "mac" | "unix")) - }); - let arch_ok = ok(self.arch.as_ref(), &|v| { - v.eq_ignore_ascii_case(arch) - || (v.eq_ignore_ascii_case("amd64") && arch == "x86_64") - || (v.eq_ignore_ascii_case("aarch64") && arch == "aarch64") - || (v.eq_ignore_ascii_case("arm64") && arch == "aarch64") - }); - name_ok && family_ok && arch_ok - } -} - #[derive(Clone, Debug, Default)] struct RawPom { group_id: Option, @@ -490,18 +444,7 @@ fn read_raw(project: &Element) -> RawPom { for p in project.list("profiles", "profile") { let mut profile = RawProfile { id: p.text_of("id").unwrap_or_else(|| "default".into()), - active_by_default: p - .at("activation/activeByDefault") - .is_some_and(|a| a.text.trim().eq_ignore_ascii_case("true")), - activation_jdk: p.at("activation/jdk").map(|jdk| jdk.text.trim().to_owned()).filter(|jdk| !jdk.is_empty()), - activation_os: p - .at("activation/os") - .map(|os| RawOsActivation { - name: os.text_of("name").map(|n| n.trim().to_owned()).filter(|n| !n.is_empty()), - family: os.text_of("family").map(|f| f.trim().to_owned()).filter(|f| !f.is_empty()), - arch: os.text_of("arch").map(|a| a.trim().to_owned()).filter(|a| !a.is_empty()), - }) - .filter(|os| os.name.is_some() || os.family.is_some() || os.arch.is_some()), + activation: Activation::read(p), modules: module_names(p), properties: read_properties(p.child("properties")), deps: p.list("dependencies", "dependency").into_iter().filter_map(read_dep).collect(), @@ -581,9 +524,12 @@ struct Inherited { /// The nearest `maven-compiler-plugin` `` / ``: a module usually /// inherits its compiler level from the parent's (managed) plugin configuration. compiler_release: Option, - /// ``, `activeByDefault`, OS-activation matched on this machine: profiles of the POM and - /// its ancestors — Maven lets a child enable a parent's profiles with `-P`. - profiles: Vec<(String, bool, bool)>, + /// `` and whether it is on unless the Maven tool window turns it off: profiles of the POM + /// and its ancestors — Maven lets a child enable a parent's profiles with `-P`. + profiles: Vec<(String, bool)>, + /// A profile of the POM or an ancestor has a file condition, which looks at the folder of + /// the project being built. + per_project: bool, } fn merge_by(base: &mut Vec, own: &[T], key: impl Fn(&T) -> String) { @@ -621,12 +567,13 @@ const MAX_PARENT_DEPTH: usize = 10; struct Resolver { local_repo: Option, - /// The chosen profiles (`-P` entries; `!id` / `-id` deactivates). - profiles: Vec, - /// The JDK Maven runs on, for `` profiles. - jdk_version: Option, + activation: ProfileActivation, + /// The `.mvn/maven.config` of each project folder. + configs: HashMap)>, poms: HashMap>, - contexts: HashMap, + /// By POM and the `maven.config` it was resolved with, or the project folder when + /// [`Inherited::per_project`]. + contexts: HashMap<(PathBuf, PathBuf), Inherited>, } /// `~/.m2/repository`, or `` from `~/.m2/settings.xml`. @@ -829,31 +776,34 @@ fn required_maven_version(jar: &Path) -> Option { } impl Resolver { - fn new(local_repo: Option, profiles: &[String]) -> Self { - Self::new_with_jdk(local_repo, profiles, None) + fn new(local_repo: Option, activation: ProfileActivation) -> Self { + Self { local_repo, activation, configs: HashMap::new(), poms: HashMap::new(), contexts: HashMap::new() } } - fn new_with_jdk(local_repo: Option, profiles: &[String], jdk_version: Option) -> Self { - Self { local_repo, profiles: profiles.to_vec(), jdk_version, poms: HashMap::new(), contexts: HashMap::new() } + /// The `maven.config` file of a Maven run in project folder `dir`, and what it sets. + fn config(&mut self, dir: &Path) -> (PathBuf, std::rc::Rc) { + self.configs + .entry(dir.to_path_buf()) + .or_insert_with(|| { + let file = MavenConfig::file(dir); + let config = MavenConfig::read(&file); + (file, std::rc::Rc::new(config)) + }) + .clone() } - /// The active profiles of a POM: chosen ones, JDK- and OS-activated ones, and the - /// `activeByDefault` ones not turned off while another profile is active. - fn active<'a>(&self, profiles: &'a [RawProfile]) -> impl Iterator { - let chosen = |id: &str| profile_choice(&self.profiles, id); - let jdk_version = self.jdk_version; - let auto_active = move |p: &RawProfile| { - p.activation_jdk.as_deref().is_some_and(|spec| jdk_matches(spec, jdk_version)) - || p.activation_os.as_ref().is_some_and(RawOsActivation::matches) - }; - let any_active = profiles.iter().any(|p| { - let choice = chosen(&p.id); - choice == Some(true) || (choice.is_none() && auto_active(p)) - }); - profiles.iter().filter(move |p| match chosen(&p.id) { - Some(value) => value, - None => auto_active(p) || (p.active_by_default && !any_active), - }) + /// Which profiles of `pom` are on for the project in `project_dir`, and which of them are + /// on unless the Maven tool window turns them off. + fn selection(&mut self, pom: &RawPom, project_dir: &Path) -> (Vec, Vec) { + let (_, config) = self.config(project_dir); + let env = Env { activation: &self.activation, config: &config, basedir: project_dir }; + let conditions = env.conditions(&pom.profiles, &pom.properties, &mut Vec::new()); + (env.select(&pom.profiles, &conditions, None), env.implicit(&pom.profiles, &conditions)) + } + + fn active<'a>(&mut self, pom: &'a RawPom, project_dir: &Path) -> Vec<&'a RawProfile> { + let (on, _) = self.selection(pom, project_dir); + pom.profiles.iter().zip(on).filter_map(|(p, on)| on.then_some(p)).collect() } fn pom(&mut self, path: &Path) -> Option { @@ -894,16 +844,20 @@ impl Resolver { self.repo_pom(&parent.group_id, &parent.artifact_id, &parent.version) } - /// What the POM at `path` hands down to its children (its parents' plus its own). - fn context(&mut self, path: &Path, depth: usize) -> Inherited { - if let Some(c) = self.contexts.get(path) { - return c.clone(); + /// What the POM at `path` hands down to its children (its parents' plus its own) when the + /// project in `project_dir` is built. + fn context(&mut self, path: &Path, project_dir: &Path, depth: usize) -> Inherited { + let (config, _) = self.config(project_dir); + for scope in [config.as_path(), project_dir] { + if let Some(c) = self.contexts.get(&(path.to_path_buf(), scope.to_path_buf())) { + return c.clone(); + } } let Some(pom) = self.pom(path) else { return Inherited::default() }; let dir = path.parent().unwrap_or(Path::new("")).to_path_buf(); let mut ctx = match &pom.parent { Some(parent) if depth < MAX_PARENT_DEPTH => match self.parent_path(&dir, parent) { - Some(pp) => self.context(&pp, depth + 1), + Some(pp) => self.context(&pp, project_dir, depth + 1), None => Inherited::default(), }, _ => Inherited::default(), @@ -918,23 +872,22 @@ impl Resolver { if pom.compiler_release.is_some() { ctx.compiler_release = pom.compiler_release.clone(); } - let active = self.active(&pom.profiles).cloned().collect::>(); + let (on, implicit) = self.selection(&pom, project_dir); + let active: Vec<&RawProfile> = pom.profiles.iter().zip(on).filter_map(|(p, on)| on.then_some(p)).collect(); for p in &active { merge_by(&mut ctx.properties, &p.properties, |(k, _)| k.clone()); merge_by(&mut ctx.deps, &p.deps, RawDep::key); merge_plugins(&mut ctx.plugins, &p.plugins); merge_plugins(&mut ctx.managed_plugins, &p.managed_plugins); } - merge_by( - &mut ctx.profiles, - &pom.profiles - .iter() - .map(|p| { - (p.id.clone(), p.active_by_default, p.activation_os.as_ref().is_some_and(RawOsActivation::matches)) - }) - .collect::>(), - |(id, ..)| id.clone(), - ); + // A parent and a child declaring the same id are two profiles; `-Pid` turns on both. + for (p, on) in pom.profiles.iter().zip(implicit) { + match ctx.profiles.iter_mut().find(|(id, _)| *id == p.id) { + Some((_, known)) => *known |= on, + None => ctx.profiles.push((p.id.clone(), on)), + } + } + ctx.per_project |= pom.profiles.iter().any(|p| p.activation.checks_files()); // Managed dependencies: own entries win; imported BOMs fill the gaps. let props = self.properties_for(&pom, &ctx, &dir); let mut local_managed = pom.managed.clone(); @@ -959,15 +912,16 @@ impl Resolver { ctx.managed.push(d); } } - self.contexts.insert(path.to_path_buf(), ctx.clone()); + let scope = if ctx.per_project { project_dir.to_path_buf() } else { config }; + self.contexts.insert((path.to_path_buf(), scope), ctx.clone()); ctx } /// Managed dependencies of a BOM, interpolated with the BOM's own properties. fn resolved_managed(&mut self, bom: &Path, depth: usize) -> Vec { - let ctx = self.context(bom, depth); - let Some(pom) = self.pom(bom) else { return Vec::new() }; let dir = bom.parent().unwrap_or(Path::new("")).to_path_buf(); + let ctx = self.context(bom, &dir, depth); + let Some(pom) = self.pom(bom) else { return Vec::new() }; let props = self.properties_for(&pom, &ctx, &dir); ctx.managed .iter() @@ -1074,7 +1028,7 @@ fn project_inputs( } Some(()) } - let mut resolver = Resolver::new(local_repo.or_else(default_local_repo), &[]); + let mut resolver = Resolver::new(local_repo.or_else(default_local_repo), ProfileActivation::default()); let mut out = Vec::new(); for project in projects { let dir = root.join(&project.dir); @@ -1083,7 +1037,7 @@ fn project_inputs( out.push(dir.join("src")); } let pom = root.join(&project.pom); - resolver.context(&pom, 0); + resolver.context(&pom, &dir, 0); let mut path = pom; let mut seen = HashSet::new(); loop { @@ -1434,7 +1388,8 @@ pub fn load(root: &Path) -> MavenModel { /// [`load`] with the POMs `settings` link (Add Maven Projects). pub fn load_linked(root: &Path, settings: &ide_core::settings::MavenSettings) -> MavenModel { - load_with_linked(root, default_local_repo(), &settings.profiles(&[]), &settings.linked_projects) + let activation = ProfileActivation::new(root, settings, &[], None); + load_with_activation(root, default_local_repo(), &activation, &settings.linked_projects) } pub(crate) fn load_with_repo(root: &Path, local_repo: Option) -> MavenModel { @@ -1468,20 +1423,6 @@ fn jdk_term_matches(term: &str, jdk: u32) -> bool { java_version(term).is_some_and(|v| v == jdk) } -/// The `-P` entries' choice for profile `id`: on, off (`!id` / `-id`), or none (the last wins). -fn profile_choice(chosen: &[String], id: &str) -> Option { - chosen.iter().rev().find_map(|c| { - let c = c.trim(); - if c == id { - Some(true) - } else if c.strip_prefix('!').or_else(|| c.strip_prefix('-')) == Some(id) { - Some(false) - } else { - None - } - }) -} - pub(crate) fn load_with(root: &Path, local_repo: Option, profiles: &[String]) -> MavenModel { load_with_linked(root, local_repo, profiles, &[]) } @@ -1620,8 +1561,9 @@ fn file_stamp(path: &Path) -> FileStamp { std::fs::metadata(path).ok().map(|m| (m.modified().ok(), m.len())) } -/// The POM files a reactor walk read or looked for, the module folders it found outside the -/// root, and the folders of every project in the reactor (canonical, the root's first). +/// The files a reactor walk read or looked for (POMs, `maven.config`, files of profile +/// conditions), the module folders it found outside the root, and the folders of every project +/// in the reactor (canonical, the root's first). #[derive(Clone)] struct ReactorScan { stamps: Vec<(PathBuf, FileStamp)>, @@ -1631,43 +1573,44 @@ struct ReactorScan { /// Folders of the modules that the reactor of `root/pom.xml` lists outside `root` /// (`../service-a`), with their own modules in turn, including those of -/// the active `profiles`. An `unlinked` POM leaves out its modules too. A folder that +/// the active profiles. An `unlinked` POM leaves out its modules too. A folder that /// holds `root` (`..`) is not a module beside the project and is skipped. -/// Callers keep the outermost directory only. Memoized on the POMs' modification times and -/// sizes: content roots are read on hot paths (every references search, Find in Files). -pub fn reactor_external_dirs(root: &Path, profiles: &[String], unlinked: &[String]) -> Vec { - reactor(root, profiles, unlinked).dirs +/// Callers keep the outermost directory only. Memoized on the modification times and sizes of +/// the files it read: content roots are read on hot paths (every references search, Find in Files). +pub fn reactor_external_dirs(root: &Path, activation: &ProfileActivation, unlinked: &[String]) -> Vec { + reactor(root, activation, unlinked).dirs } /// Folders of every project in the reactor of `root/pom.xml` (canonical): `root` itself and its -/// modules, theirs in turn, including those of the active `profiles`. A POM elsewhere below `root` +/// modules, theirs in turn, including those of the active profiles. A POM elsewhere below `root` /// that no `` reaches is a separate build. -pub fn reactor_member_dirs(root: &Path, profiles: &[String]) -> Vec { - reactor(root, profiles, &[]).members +pub fn reactor_member_dirs(root: &Path, activation: &ProfileActivation) -> Vec { + reactor(root, activation, &[]).members } -fn reactor(root: &Path, profiles: &[String], unlinked: &[String]) -> ReactorScan { - type Memo = HashMap<(PathBuf, Vec, Vec), ReactorScan>; +fn reactor(root: &Path, activation: &ProfileActivation, unlinked: &[String]) -> ReactorScan { + type Memo = HashMap<(PathBuf, ProfileActivation, Vec), ReactorScan>; static MEMO: std::sync::LazyLock> = std::sync::LazyLock::new(Default::default); - let key = (root.to_path_buf(), profiles.to_vec(), unlinked.to_vec()); + let key = (root.to_path_buf(), activation.clone(), unlinked.to_vec()); if let Some(scan) = MEMO.lock().unwrap_or_else(|e| e.into_inner()).get(&key) && scan.stamps.iter().all(|(path, stamp)| file_stamp(path) == *stamp) { return scan.clone(); } - let scan = scan_reactor(root, profiles, unlinked); + let scan = scan_reactor(root, activation, unlinked); MEMO.lock().unwrap_or_else(|e| e.into_inner()).insert(key, scan.clone()); scan } /// Reads only the POMs the reactor lists (no parent resolution and no directory walk). -fn scan_reactor(root: &Path, profiles: &[String], unlinked: &[String]) -> ReactorScan { +fn scan_reactor(root: &Path, activation: &ProfileActivation, unlinked: &[String]) -> ReactorScan { let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); - let chosen = Resolver::new(None, profiles); + let mut resolver = Resolver::new(None, activation.clone()); let unlinked: HashSet = unlinked.iter().map(|p| normalized_pom(p.trim())).collect(); let first = root.join("pom.xml"); let mut scan = ReactorScan { stamps: vec![(first.clone(), file_stamp(&first))], dirs: Vec::new(), members: Vec::new() }; + let mut stamped: HashSet = HashSet::new(); let mut seen: HashSet = HashSet::new(); let mut pending = vec![first]; while let Some(path) = pending.pop() { @@ -1688,7 +1631,18 @@ fn scan_reactor(root: &Path, profiles: &[String], unlinked: &[String]) -> Reacto } scan.dirs.push(dir_canon); } - let active: Vec<&RawProfile> = chosen.active(&pom.profiles).collect(); + let (config_file, config) = resolver.config(&dir); + let env = Env { activation, config: &config, basedir: &dir }; + let mut files = vec![config_file]; + let conditions = env.conditions(&pom.profiles, &pom.properties, &mut files); + let on = env.select(&pom.profiles, &conditions, None); + for file in files { + if stamped.insert(file.clone()) { + let stamp = file_stamp(&file); + scan.stamps.push((file, stamp)); + } + } + let active: Vec<&RawProfile> = pom.profiles.iter().zip(on).filter_map(|(p, on)| on.then_some(p)).collect(); let props: HashMap = pom.properties.iter().chain(active.iter().flat_map(|p| &p.properties)).cloned().collect(); for module in pom.modules.iter().chain(active.iter().flat_map(|p| &p.modules)) { @@ -1738,7 +1692,20 @@ pub fn load_with_linked_jdk( jdk_version: Option, linked: &[String], ) -> MavenModel { - let mut resolver = Resolver::new_with_jdk(local_repo, profiles, jdk_version); + let activation = ProfileActivation { profiles: profiles.to_vec(), choices: Vec::new(), jdk: jdk_version }; + load_with_activation(root, local_repo, &activation, linked) +} + +/// [`load_with_linked`] with the profiles Maven turns on as it would build the projects: those +/// `activation` and `.mvn/maven.config` choose, and those whose conditions hold. +pub fn load_with_activation( + root: &Path, + local_repo: Option, + activation: &ProfileActivation, + linked: &[String], +) -> MavenModel { + let jdk_version = activation.jdk; + let mut resolver = Resolver::new(local_repo, activation.clone()); let mut model = MavenModel::default(); // Canonical POM → its project, for a module listed again by a later aggregator. let mut seen: HashMap> = HashMap::new(); @@ -1776,15 +1743,15 @@ pub fn load_with_linked_jdk( let Some(pom) = resolver.pom(&path) else { continue }; let dir = path.parent().unwrap_or(root).to_path_buf(); let dir_canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone()); - let ctx = resolver.context(&path, 0); + let ctx = resolver.context(&path, &dir, 0); let props = resolver.properties_for(&pom, &ctx, &dir); let i = |s: &str| interpolate(s, &props); let mut module_names: Vec = pom.modules.clone(); - for p in resolver.active(&pom.profiles) { + for p in resolver.active(&pom, &dir) { module_names.extend(p.modules.iter().cloned()); } - let jdks = pom.profiles.iter().filter_map(|p| p.activation_jdk.as_ref()); + 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 { @@ -1870,16 +1837,18 @@ pub fn load_with_linked_jdk( .map(|v| i(v).trim().to_owned()) .filter(|v| !v.is_empty() && !v.contains("${")); - // The project can activate the profiles of its own POM and its ancestors'. - // OS-activated ones count as active by default for the tool window: a click - // then disables them explicitly (-P !id), which is the only way to keep - // Maven's own activation from putting them in the build (#8171). - for (id, by_default, os_active) in &ctx.profiles { - let auto = *by_default || *os_active; + // The project can activate the profiles of its own POM and its ancestors'. One Maven + // turns on by itself (its ``, say) is unticked with an explicit `-P !id`: only that + // keeps it out of the build (#8171). + for (id, implicit) in &ctx.profiles { if let Some(existing) = model.profiles.iter_mut().find(|x| x.id == *id) { - existing.active_by_default |= auto; + existing.active_by_default |= *implicit; } else { - model.profiles.push(MavenProfile { id: id.clone(), active_by_default: auto, ..Default::default() }); + model.profiles.push(MavenProfile { + id: id.clone(), + active_by_default: *implicit, + ..Default::default() + }); } } let artifact_id = i(&pom.artifact_id); @@ -2236,6 +2205,14 @@ pub struct PomNavigationOptions { pub jdk_version: Option, } +impl PomNavigationOptions { + fn resolver(&self) -> Resolver { + let activation = + ProfileActivation { profiles: self.profiles.clone(), choices: Vec::new(), jdk: self.jdk_version }; + Resolver::new(self.local_repo.clone(), activation) + } +} + /// A Maven project of the workspace, for going to a dependency on it. #[derive(Clone, Debug)] pub struct ModulePom { @@ -2467,7 +2444,7 @@ pub fn managed_declarations_with( let mut out = Vec::new(); let mut seen = HashSet::new(); let profiles = root.list("profiles", "profile"); - let active_profiles = active_profile_ids(text, &options); + let active_profiles = active_profile_ids(text, path, &options); let mut add = |e: &Element, kind: PomGotoKind| { if e.text_of("version").is_some() { @@ -2526,8 +2503,7 @@ fn parent_target( if let Some((pom, parent_text)) = chain.get(1) { return Some(pom_goto(pom.clone(), parent_text, artifact)); } - let resolver = Resolver::new_with_jdk(options.local_repo.clone(), &options.profiles, options.jdk_version); - let pom = resolver.repo_pom(&group, &artifact, &version)?; + let pom = options.resolver().repo_pom(&group, &artifact, &version)?; let parent_text = xml::read_text(&pom)?; Some(pom_goto(pom, &parent_text, artifact)) } @@ -2541,7 +2517,7 @@ fn artifact_target( modules: &mut dyn FnMut() -> Vec, use_managed_version: bool, ) -> Option { - let mut resolver = Resolver::new_with_jdk(options.local_repo.clone(), &options.profiles, options.jdk_version); + let mut resolver = options.resolver(); let chain = parent_chain(path, text, options.local_repo.clone()); let props = properties_at(&mut resolver, &chain, 0); let (group, artifact) = coordinates(e, &props)?; @@ -2586,7 +2562,7 @@ fn pom_goto(path: PathBuf, text: &str, label: String) -> PomGoto { /// The parent POMs of the POM in `text` at `path`, child-first (its `` refs, /// via `relativePath` in the project or the local repository), with their texts. fn parent_chain(path: &Path, text: &str, local_repo: Option) -> Vec<(PathBuf, String)> { - let mut resolver = Resolver::new(local_repo, &[]); + let mut resolver = Resolver::new(local_repo, ProfileActivation::default()); let path = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); let mut chain = vec![(path.clone(), text.to_owned())]; let mut dir = path.parent().unwrap_or(Path::new("")).to_path_buf(); @@ -2609,7 +2585,7 @@ fn properties_at(resolver: &mut Resolver, chain: &[(PathBuf, String)], i: usize) let (p, text) = &chain[i]; let Some(pom) = parse_pom(text) else { return HashMap::new() }; let dir = p.parent().unwrap_or(Path::new("")).to_path_buf(); - let ctx = resolver.context(p, 0); + let ctx = resolver.context(p, &dir, 0); resolver.properties_for(&pom, &ctx, &dir) } @@ -2619,7 +2595,7 @@ fn properties_at(resolver: &mut Resolver, chain: &[(PathBuf, String)], i: usize) /// profile's counts as the POM's own). The winner's path, element range and name. fn property_target(text: &str, path: &Path, name: &str, options: &PomNavigationOptions) -> Option { let name = name.strip_prefix("pom.").map(|n| format!("project.{n}")).unwrap_or_else(|| name.to_owned()); - let resolver = Resolver::new_with_jdk(options.local_repo.clone(), &options.profiles, options.jdk_version); + let mut resolver = options.resolver(); let chain = parent_chain(path, text, options.local_repo.clone()); // `project.parent.*` (and the legacy `parent.*` spellings) are declared by the // clicked POM's own `` section. @@ -2658,7 +2634,7 @@ fn property_target(text: &str, path: &Path, name: &str, options: &PomNavigationO Some(_) => None, None if matches!(name.as_str(), "groupId" | "artifactId" | "version" | "packaging" | "name") => { // The bare shorthand of a built-in; a custom property of that name wins. - if let Some(found) = properties_target(&chain, &name, &resolver) { + if let Some(found) = properties_target(&chain, &name, &mut resolver) { return Some(found); } Some(name.as_str()) @@ -2678,16 +2654,17 @@ fn property_target(text: &str, path: &Path, name: &str, options: &PomNavigationO } return None; } - properties_target(&chain, &name, &resolver) + properties_target(&chain, &name, &mut resolver) } /// A property of ``: the first POM of the chain (child-first) that /// declares it, at project level or in an active profile. -fn properties_target(chain: &[(PathBuf, String)], name: &str, resolver: &Resolver) -> Option { +fn properties_target(chain: &[(PathBuf, String)], name: &str, resolver: &mut Resolver) -> Option { + let project_dir = chain[0].0.parent().unwrap_or(Path::new("")).to_path_buf(); for (p, text) in chain { let Some(root) = xml::parse(text).filter(|e| e.name == "project") else { continue }; let active: Vec = parse_pom(text) - .map(|pom| resolver.active(&pom.profiles).map(|pr| pr.id.clone()).collect()) + .map(|pom| resolver.active(&pom, &project_dir).into_iter().map(|pr| pr.id.clone()).collect()) .unwrap_or_default(); // Project level first, then the first active profile declaring the property. let e = root.child("properties").and_then(|props| props.child(name)).or_else(|| { @@ -2724,19 +2701,19 @@ fn managed_target( options: &PomNavigationOptions, modules: &mut dyn FnMut() -> Vec, ) -> Option { - let mut resolver = Resolver::new_with_jdk(options.local_repo.clone(), &options.profiles, options.jdk_version); + let mut resolver = options.resolver(); let chain = parent_chain(path, text, options.local_repo.clone()); let props = properties_at(&mut resolver, &chain, 0); let mut search = ManagedSearch { options, key: dependency_key(e, &props)?, kind, modules, visited: HashSet::new() }; search.in_pom(path, text, 0) } -fn active_profile_ids(text: &str, options: &PomNavigationOptions) -> HashSet { +/// The profiles of the POM in `text` that are on when the project of the POM at `project_pom` +/// is built. +fn active_profile_ids(text: &str, project_pom: &Path, options: &PomNavigationOptions) -> HashSet { let Some(pom) = parse_pom(text) else { return HashSet::new() }; - Resolver::new_with_jdk(None, &options.profiles, options.jdk_version) - .active(&pom.profiles) - .map(|profile| profile.id.clone()) - .collect() + let project_dir = project_pom.parent().unwrap_or(Path::new("")); + options.resolver().active(&pom, project_dir).into_iter().map(|profile| profile.id.clone()).collect() } /// State shared by the recursive management lookup: visited BOMs prevent import @@ -2759,8 +2736,7 @@ impl ManagedSearch<'_> { return None; } let chain = parent_chain(path, text, self.options.local_repo.clone()); - let mut resolver = - Resolver::new_with_jdk(self.options.local_repo.clone(), &self.options.profiles, self.options.jdk_version); + let mut resolver = self.options.resolver(); for (i, (p, t)) in chain.iter().enumerate() { let Some(root) = xml::parse(t).filter(|e| e.name == "project") else { continue }; let props = properties_at(&mut resolver, &chain, i); @@ -2771,7 +2747,7 @@ impl ManagedSearch<'_> { }; let imported = |entry: &&Element| entry.text_of("scope").as_deref() == Some("import"); let base = root.list(section, item); - let active = active_profile_ids(t, self.options); + let active = active_profile_ids(t, path, self.options); let profiles = root .list("profiles", "profile") .into_iter() @@ -4448,6 +4424,109 @@ mod tests { assert!(on.projects.iter().any(|project| project.artifact_id == "jdk21")); } + /// The `` of the machine running the tests. + fn os_family() -> &'static str { + if cfg!(windows) { + "windows" + } else if cfg!(target_os = "macos") { + "mac" + } else { + "unix" + } + } + + #[test] + fn profiles_maven_turns_on_by_itself_bring_their_modules() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let family = os_family(); + write( + root, + "pom.xml", + &format!( + r#"demoroot1pom + core + docs-src + + devtruedev + full!quickextras + flavorflavorxflavored + native{family}native + as400os/400as400 + with-docs${{basedir}}/${{docs}}docs + unlockedbuild.lockunlocked + modern[17,)modern + future{family}[30,)future + ciit + + "# + ), + ); + for m in ["core", "dev", "extras", "flavored", "native", "as400", "docs", "unlocked", "modern", "future", "it"] + { + write(root, &format!("{m}/pom.xml"), &format!("{m}")); + } + std::fs::create_dir(root.join("docs-src")).unwrap(); + write(root, ".mvn/maven.config", "-Pci\n-Dflavor=x\n"); + let dirs = |m: &MavenModel| m.projects.iter().map(|p| p.dir.clone()).collect::>(); + let on = |m: &MavenModel| { + m.profiles.iter().filter(|p| p.active_by_default).map(|p| p.id.clone()).collect::>() + }; + + // The reactor `mvn validate` builds from these POMs on JDK 21: every condition of a + // profile has to hold, and `dev` steps aside because other profiles of its POM are on. + let model = load_with_linked_jdk(root, None, &[], Some(21), &[]); + assert_eq!(dirs(&model), ["", "core", "extras", "flavored", "native", "docs", "unlocked", "modern", "it"]); + assert_eq!(on(&model), ["full", "flavor", "native", "with-docs", "unlocked", "modern", "ci"]); + + write(root, ".mvn/maven.config", "-Dquick\n"); + std::fs::write(root.join("build.lock"), "").unwrap(); + let model = load_with_linked_jdk(root, None, &["!native".into(), "!with-docs".into()], Some(11), &[]); + assert_eq!(dirs(&model), ["", "core", "dev"]); + assert_eq!(on(&model), ["dev"]); + } + + #[test] + fn a_parent_profile_activated_by_a_file_looks_at_each_module() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write( + root, + "pom.xml", + r#"demoparent1pom + appdocs + javasrc/main/java + org.slf4jslf4j-api2.0.16 + + "#, + ); + for m in ["app", "docs"] { + write( + root, + &format!("{m}/pom.xml"), + &format!( + "demoparent1{m}" + ), + ); + } + std::fs::create_dir_all(root.join("app/src/main/java")).unwrap(); + let model = load_with_linked_jdk(root, None, &[], None, &[]); + let slf4j = |dir: &str| { + model + .projects + .iter() + .find(|p| p.dir == dir) + .unwrap() + .dependencies + .iter() + .any(|d| d.artifact_id == "slf4j-api") + }; + // As in Maven, a parent's file condition is checked in the folder of the module being built. + assert!(slf4j("app")); + assert!(!slf4j("docs")); + assert!(!slf4j("")); + } + #[test] fn a_module_is_matched_by_group_artifact_and_version() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-build/src/maven/activation.rs b/crates/ide-build/src/maven/activation.rs new file mode 100644 index 0000000000..a04d74a8a9 --- /dev/null +++ b/crates/ide-build/src/maven/activation.rs @@ -0,0 +1,463 @@ +//! Which profiles of a POM Maven turns on for a project, decided as Maven 3.9 does +//! (`DefaultProfileSelector` and its activators): from the `-P` entries, the `-D` properties of +//! `.mvn/maven.config`, the JDK Maven runs on, the OS and the files of the project. + +use super::{RawProfile, interpolate, jdk_matches}; +use crate::xml::Element; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +/// What decides profile activation besides the POMs and the machine. The `.mvn/maven.config` +/// of each build is read with its POMs. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct ProfileActivation { + /// `-P` entries of every Maven run (`!id` or `-id` turns a profile off): Settings › Maven's + /// active profiles and the `` of the user `settings.xml`. + pub profiles: Vec, + /// `-P` entries chosen in the Maven tool window. + pub choices: Vec, + /// Feature version of the JDK Maven runs on. + pub jdk: Option, +} + +impl ProfileActivation { + /// For the builds under `root`, with the Maven tool window's `choices`. + pub fn new( + root: &Path, + settings: &ide_core::settings::MavenSettings, + choices: &[String], + jdk: Option, + ) -> Self { + let mut profiles = settings.profiles(&[]); + if let Some(file) = super::user_settings_file(root, settings) { + profiles.extend(super::settings_active_profiles(&file)); + } + Self { profiles, choices: choices.to_vec(), jdk } + } + + /// `Some(false)` when a `-P` entry turns profile `id` off (that wins in Maven, whatever the + /// order), `Some(true)` when one turns it on. The tool window's entries for `except` are + /// left out. + fn explicit(&self, config: &MavenConfig, id: &str, except: Option<&str>) -> Option { + let choices = self.choices.iter().filter(|c| except.is_none_or(|except| entry(c).1 != except)); + let mut on = None; + for (turns_on, entry) in self.profiles.iter().chain(&config.profiles).chain(choices).map(|e| entry(e)) { + if entry == id { + if !turns_on { + return Some(false); + } + on = Some(true); + } + } + on + } +} + +/// A `-P` entry as (turns the profile on, its id): `!id` and `-id` turn it off, `+id` and +/// Maven 3.9's optional `?id` turn it on. +fn entry(entry: &str) -> (bool, &str) { + let entry = entry.trim(); + let (on, id) = match entry.strip_prefix(['!', '-']) { + Some(id) => (false, id), + None => (true, entry.strip_prefix('+').unwrap_or(entry)), + }; + (on, id.strip_prefix('?').unwrap_or(id).trim()) +} + +/// The `-P` and `-D` options of the `.mvn/maven.config` Maven reads before every run. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct MavenConfig { + profiles: Vec, + properties: HashMap, +} + +impl MavenConfig { + /// The `maven.config` of a Maven run in `dir`: in the `.mvn` folder of the nearest folder + /// from `dir` up that has one, as the `mvn` script finds the build's base directory; else + /// where it would be created in `dir`. + pub(crate) fn file(dir: &Path) -> PathBuf { + let base = dir.ancestors().find(|d| !d.as_os_str().is_empty() && d.join(".mvn").is_dir()); + base.unwrap_or(dir).join(".mvn").join("maven.config") + } + + pub(crate) fn read(file: &Path) -> Self { + std::fs::read_to_string(file).map(|text| Self::parse(&text)).unwrap_or_default() + } + + /// Since Maven 3.9 each line is one argument (`-P a` and `-P` followed by `a` both work); + /// lines starting with `#` are comments. + fn parse(text: &str) -> Self { + let mut config = Self::default(); + let mut args = text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')); + while let Some(arg) = args.next() { + if let Some(value) = option_value(arg, "-P", "--activate-profiles", &mut args) { + config.profiles.extend(value.split(',').map(str::trim).filter(|p| !p.is_empty()).map(str::to_owned)); + } else if let Some(value) = option_value(arg, "-D", "--define", &mut args) { + // `-Dname` alone sets it to `true`, as on the command line. + let (name, value) = value.split_once('=').unwrap_or((value, "true")); + config.properties.insert(name.trim().to_owned(), value.to_owned()); + } + } + config + } +} + +/// The value of the option `short` / `long` given in `arg` (`-Pa`, `-P a`, `--activate-profiles=a`) +/// or as the next argument. +fn option_value<'a>( + arg: &'a str, + short: &str, + long: &str, + args: &mut impl Iterator, +) -> Option<&'a str> { + let value = match arg.strip_prefix(long) { + Some(rest) if rest.is_empty() || rest.starts_with(['=', ' ', '\t']) => rest.trim_start_matches('='), + Some(_) => return None, + None => arg.strip_prefix(short)?, + }; + match value.trim() { + "" => args.next(), + value => Some(value), + } +} + +/// A profile's ``. +#[derive(Clone, Debug, Default)] +pub(crate) struct Activation { + pub(crate) by_default: bool, + /// ``: `21`, `1.8`, `[17,)`, `!21`. + pub(crate) jdk: Option, + os: Option, + property: Option, + file: Option, +} + +#[derive(Clone, Debug, Default)] +struct OsCondition { + family: Option, + name: Option, + arch: Option, + version: Option, +} + +#[derive(Clone, Debug, Default)] +struct PropertyCondition { + name: String, + value: Option, +} + +#[derive(Clone, Debug, Default)] +struct FileCondition { + exists: Option, + missing: Option, +} + +impl Activation { + pub(crate) fn read(profile: &Element) -> Self { + let Some(a) = profile.child("activation") else { return Self::default() }; + Self { + by_default: a.text_of("activeByDefault").is_some_and(|v| v.eq_ignore_ascii_case("true")), + // Present but empty, Maven's prefix match takes any JDK. + jdk: a.child("jdk").map(|jdk| jdk.text.trim().to_owned()), + os: a.child("os").map(|os| OsCondition { + family: os.text_of("family"), + name: os.text_of("name"), + arch: os.text_of("arch"), + version: os.text_of("version"), + }), + property: a + .child("property") + .map(|p| PropertyCondition { name: p.text_of("name").unwrap_or_default(), value: p.text_of("value") }), + file: a.child("file").map(|f| FileCondition { exists: f.text_of("exists"), missing: f.text_of("missing") }), + } + } + + pub(crate) fn checks_files(&self) -> bool { + self.file.is_some() + } + + fn is_empty(&self) -> bool { + self.jdk.is_none() && self.os.is_none() && self.property.is_none() && self.file.is_none() + } +} + +/// What the profiles of one project are activated with. +pub(crate) struct Env<'a> { + pub(crate) activation: &'a ProfileActivation, + pub(crate) config: &'a MavenConfig, + /// The folder of the project being built, also for the profiles its parents declare. + pub(crate) basedir: &'a Path, +} + +impl Env<'_> { + /// Whether the `` conditions of each profile hold; the files they look at are + /// added to `files`. `properties` are the own `` of the POM declaring them. + pub(crate) fn conditions( + &self, + profiles: &[RawProfile], + properties: &[(String, String)], + files: &mut Vec, + ) -> Vec { + if profiles.iter().all(|p| p.activation.is_empty()) { + return vec![false; profiles.len()]; + } + let props = self.interpolation(properties); + profiles.iter().map(|p| self.holds(&p.activation, &props, files)).collect() + } + + /// Which profiles are on: those a `-P` entry turns on or whose `conditions` hold, unless one + /// turns them off; the `activeByDefault` ones only when no other profile of the POM is on. + /// The tool window's choice for profile `except` is left out. + pub(crate) fn select(&self, profiles: &[RawProfile], conditions: &[bool], except: Option<&str>) -> Vec { + let explicit: Vec> = + profiles.iter().map(|p| self.activation.explicit(self.config, &p.id, except)).collect(); + let mut on: Vec = explicit.iter().zip(conditions).map(|(e, &holds)| e.unwrap_or(holds)).collect(); + if !on.contains(&true) { + for ((on, p), e) in on.iter_mut().zip(profiles).zip(&explicit) { + *on = p.activation.by_default && *e != Some(false); + } + } + on + } + + /// Whether each profile is on unless the Maven tool window turns it off: what the tool + /// window shows as on by default, so that unticking it passes `-P!id`. + pub(crate) fn implicit(&self, profiles: &[RawProfile], conditions: &[bool]) -> Vec { + profiles.iter().enumerate().map(|(i, p)| self.select(profiles, conditions, Some(&p.id))[i]).collect() + } + + /// Values for `${…}` in activation conditions: the declaring POM's own properties, then the + /// `-D` ones, then the JVM's; `${basedir}` is the project's. + fn interpolation(&self, properties: &[(String, String)]) -> HashMap { + let mut props: HashMap = ["os.name", "os.arch", "user.home"] + .into_iter() + .filter_map(|k| Some((k.to_owned(), system_property(k)?))) + .collect(); + props.extend(self.config.properties.iter().map(|(k, v)| (k.clone(), v.clone()))); + props.extend(properties.iter().cloned()); + let basedir = self.basedir.to_string_lossy().into_owned(); + props.insert("project.basedir".into(), basedir.clone()); + props.insert("basedir".into(), basedir); + props + } + + /// Since Maven 3.2.2 every condition present has to hold, and one at least has to be present. + fn holds(&self, a: &Activation, props: &HashMap, files: &mut Vec) -> bool { + let jdk = self.activation.jdk; + let results = [ + a.jdk.as_ref().map(|spec| jdk.is_some() && (spec.is_empty() || jdk_matches(spec, jdk))), + a.os.as_ref().map(|os| os_matches(os, props)), + a.property.as_ref().map(|p| self.property_matches(p, props)), + a.file.as_ref().map(|f| self.file_matches(f, props, files)), + ]; + let mut present = results.into_iter().flatten().peekable(); + present.peek().is_some() && present.all(|holds| holds) + } + + fn property_matches(&self, p: &PropertyCondition, props: &HashMap) -> bool { + let name = interpolate(&p.name, props); + let (negated, name) = negation(&name); + if name.is_empty() { + return false; + } + let actual = self.config.properties.get(name).cloned().or_else(|| system_property(name)); + match p.value.as_deref().map(|v| interpolate(v, props)) { + Some(value) => { + let (negated, value) = negation(&value); + negated != (actual.as_deref() == Some(value)) + } + None => negated != actual.is_some_and(|v| !v.is_empty()), + } + } + + fn file_matches(&self, f: &FileCondition, props: &HashMap, files: &mut Vec) -> bool { + let (path, missing) = match (&f.exists, &f.missing) { + (Some(path), _) => (path, false), + (None, Some(path)) => (path, true), + (None, None) => return false, + }; + let path = crate::gradle::normalize(&self.basedir.join(interpolate(path, props))); + let exists = path.exists(); + files.push(path); + exists != missing + } +} + +fn negation(value: &str) -> (bool, &str) { + match value.strip_prefix('!') { + Some(rest) => (true, rest), + None => (false, value), + } +} + +/// `` as Maven 3.9 matches it (`org.apache.maven.utils.Os`) against what Java reports for +/// this machine. +fn os_matches(os: &OsCondition, props: &HashMap) -> bool { + let name = os_name().to_lowercase(); + let test = |value: &Option, matches: &dyn Fn(&str) -> bool| { + value.as_deref().is_none_or(|v| { + let v = interpolate(v, props).to_lowercase(); + let (negated, v) = negation(&v); + negated != matches(v) + }) + }; + (os.family.is_some() || os.name.is_some() || os.arch.is_some()) + // The OS version Java reports is not known here. + && os.version.is_none() + && test(&os.family, &|family| family_matches(family, &name)) + && test(&os.name, &|n| n == name) + && test(&os.arch, &|arch| arch == os_arch()) +} + +fn family_matches(family: &str, os_name: &str) -> bool { + let windows = os_name.contains("windows"); + let win9x = windows && ["95", "98", "me", "ce"].iter().any(|v| os_name.contains(v)); + let mac = os_name.contains("mac") || os_name.contains("darwin"); + match family { + "windows" => windows, + "win9x" => win9x, + "winnt" => windows && !win9x, + "dos" => cfg!(windows) && !os_name.contains("netware"), + "mac" => mac, + "unix" => !cfg!(windows) && !os_name.contains("openvms") && (!mac || os_name.ends_with('x')), + "tandem" => os_name.contains("nonstop_kernel"), + "z/os" => os_name.contains("z/os") || os_name.contains("os/390"), + family => os_name.contains(family), + } +} + +/// `os.name` as Java reports it; on Windows it also names the version, which is not known here. +fn os_name() -> &'static str { + match std::env::consts::OS { + "macos" => "Mac OS X", + "windows" => "Windows", + "linux" => "Linux", + "freebsd" => "FreeBSD", + "openbsd" => "OpenBSD", + "netbsd" => "NetBSD", + "solaris" | "illumos" => "SunOS", + "aix" => "AIX", + os => os, + } +} + +/// `os.arch` as Java reports it. +fn os_arch() -> &'static str { + match std::env::consts::ARCH { + "x86_64" if cfg!(target_os = "macos") => "x86_64", + "x86_64" => "amd64", + "x86" if cfg!(windows) => "x86", + "x86" => "i386", + "powerpc64" if cfg!(target_endian = "little") => "ppc64le", + "powerpc64" => "ppc64", + arch => arch, + } +} + +/// The system properties of Maven's JVM that conditions use: the environment as `env.*`, and +/// those of the JVM's own that are known here. +fn system_property(name: &str) -> Option { + if let Some(var) = name.strip_prefix("env.") { + return std::env::var(var).ok(); + } + match name { + "os.name" => Some(os_name().to_owned()), + "os.arch" => Some(os_arch().to_owned()), + "user.home" => dirs::home_dir().map(|home| home.to_string_lossy().into_owned()), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn profiles(xml: &str) -> Vec { + super::super::parse_pom(&format!("{xml}")).unwrap().profiles + } + + fn holds(env: &Env, activation: &str) -> bool { + let profiles = profiles(&format!("p{activation}")); + env.conditions(&profiles, &[], &mut Vec::new())[0] + } + + #[test] + fn maven_config_takes_one_option_per_line() { + let config = MavenConfig::parse( + "# shared options\n-Pci,!slow\n-P\nnative\n--activate-profiles=docs\n-Dflavor=x\n-Dquick\n-D\nmode=a=b\n-T4\n", + ); + assert_eq!(config.profiles, ["ci", "!slow", "native", "docs"]); + let properties = HashMap::from( + [("flavor", "x"), ("quick", "true"), ("mode", "a=b")].map(|(k, v)| (k.to_owned(), v.to_owned())), + ); + assert_eq!(config.properties, properties); + } + + #[test] + fn conditions_hold_as_mavens_activators_decide() { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("present")).unwrap(); + let activation = ProfileActivation { jdk: Some(21), ..Default::default() }; + let config = MavenConfig::parse("-Dflavor=x\n-Dempty=\n"); + let env = Env { activation: &activation, config: &config, basedir: dir.path() }; + let family = if cfg!(windows) { + "windows" + } else if cfg!(target_os = "macos") { + "mac" + } else { + "unix" + }; + let cases = [ + ("flavor".to_owned(), true), + ("!flavor".into(), false), + ("flavorx".into(), true), + ("flavor!x".into(), false), + ("empty".into(), false), + ("!unset".into(), true), + (format!("{family}"), true), + (format!("!{family}"), false), + ("os/400".into(), false), + (format!("{}", os_arch()), true), + // Maven compares what Java reports (`Mac OS X`, `aarch64`), not other spellings. + (format!("{}", os_name()), true), + ("macos".into(), false), + ("arm64".into(), false), + ("".into(), false), + ("present".into(), true), + ("${basedir}/absent".into(), true), + ("".into(), false), + ("[17,)".into(), true), + ("".into(), true), + (format!("{family}[30,)"), false), + ]; + for (activation, expected) in cases { + assert_eq!(holds(&env, &activation), expected, "{activation}"); + } + } + + #[test] + fn a_profile_turned_off_stays_off_and_active_by_default_ones_step_aside() { + let ps = profiles( + "devtrue\ + ci", + ); + let config = MavenConfig::default(); + let none = [false, false]; + let select = |profiles: &[&str], choices: &[&str], implicit: bool| { + let activation = ProfileActivation { + profiles: profiles.iter().map(|p| p.to_string()).collect(), + choices: choices.iter().map(|p| p.to_string()).collect(), + jdk: None, + }; + let env = Env { activation: &activation, config: &config, basedir: Path::new("/") }; + if implicit { env.implicit(&ps, &none) } else { env.select(&ps, &none, None) } + }; + assert_eq!(select(&[], &[], false), [true, false]); + assert_eq!(select(&[], &["ci"], false), [false, true]); + assert_eq!(select(&[], &["ci", "dev"], false), [true, true]); + // Turned off by the tool window while Settings turn it on: off, whatever the order. + assert_eq!(select(&["ci"], &["!ci"], false), [true, false]); + // Still on unless the tool window turns it off, so it keeps passing `-P!ci`. + assert_eq!(select(&["ci"], &["!ci"], true), [true, true]); + } +} diff --git a/crates/ide-build/src/sync.rs b/crates/ide-build/src/sync.rs index d0bda5c428..5c231f6f60 100644 --- a/crates/ide-build/src/sync.rs +++ b/crates/ide-build/src/sync.rs @@ -380,11 +380,12 @@ pub fn sync_maven( cancel: &CancellationToken, progress: &dyn Fn(SyncProgress), ) -> IdeResult<()> { - let mut model = maven::load_with_linked_jdk( + let activation = + maven::ProfileActivation::new(root, &options.maven_settings, &options.profiles, options.jdk_version); + let mut model = maven::load_with_activation( root, maven::default_local_repo(), - &options.maven_settings.profiles(&options.profiles), - options.jdk_version, + &activation, &options.maven_settings.linked_projects, ); maven::UnlinkedProjects::from_model(&model, &options.maven_settings).filter(&mut model); diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index 0c41967617..a739819fcb 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -142,8 +142,13 @@ pub(super) fn junit_report_modules(scope: &workspace::Scope, cwd: &Path, tool: B let cwd = ide_core::project_roots::resolve(&scope.root, cwd); match tool { BuildTool::Maven => { - let profiles = scope.settings.languages.java.maven.profiles(&ide_build::maven_profiles(&scope.cache)); - ide_build::maven::reactor_member_dirs(&cwd, &profiles) + let activation = ide_build::maven::ProfileActivation::new( + &scope.root, + &scope.settings.languages.java.maven, + &ide_build::maven_profiles(&scope.cache), + maven_jdk_version(&scope.root, &scope.settings), + ); + ide_build::maven::reactor_member_dirs(&cwd, &activation) } BuildTool::Gradle => { let model = load_synced(&scope.root, &scope.cache, &scope.settings); @@ -157,7 +162,7 @@ pub(super) fn junit_report_modules(scope: &workspace::Scope, cwd: &Path, tool: B } /// The JDK `` profiles are matched against. -fn maven_jdk_version(root: &Path, settings: &Settings) -> Option { +pub(super) fn maven_jdk_version(root: &Path, settings: &Settings) -> Option { ide_sdk::apply::maven_jdk(root, settings, None).map(|jdk| jdk.major) } @@ -189,7 +194,8 @@ fn sync_options( /// 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 { - let mut profiles = settings.languages.java.maven.profiles(&[]); + let maven = &settings.languages.java.maven; + let mut profiles = ide_build::maven::ProfileActivation::new(&project.root, maven, &[], None).profiles; for profile in ide_build::maven_profiles(&project.build_cache_dir()) { if !profiles.contains(&profile) { profiles.push(profile); @@ -1809,6 +1815,61 @@ mod junit_report_module_tests { assert_eq!(modules(&root), [sibling, root, module, nested, profile]); } + #[test] + fn maven_reports_cover_the_modules_of_profiles_maven_turns_on_by_itself() { + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let root = base.join("workspace"); + let jdk = base.join("jdk-21"); + std::fs::create_dir_all(jdk.join("bin")).unwrap(); + std::fs::write(jdk.join("bin").join(if cfg!(windows) { "java.exe" } else { "java" }), "").unwrap(); + std::fs::write(jdk.join("release"), "JAVA_VERSION=\"21.0.4\"\n").unwrap(); + let mut settings = Settings::default(); + settings.languages.java.maven.runner_jre = jdk.to_string_lossy().into_owned(); + settings.languages.java.maven.user_settings = base.join("settings.xml").to_string_lossy().into_owned(); + let scope = workspace::Scope { root: root.clone(), cache: base.join("cache"), settings }; + let family = if cfg!(windows) { + "windows" + } else if cfg!(target_os = "macos") { + "mac" + } else { + "unix" + }; + let profile = |id: &str, activation: &str| { + format!("{id}{activation}{id}") + }; + let profiles = [ + profile("extras", "!quick"), + profile("native", &format!("{family}")), + profile("docs", "${basedir}/docs-src"), + profile("modern", "[17,)"), + profile("it", ""), + ]; + std::fs::create_dir_all(root.join("docs-src")).unwrap(); + std::fs::write( + root.join("pom.xml"), + format!( + "rootcore{}", + profiles.concat() + ), + ) + .unwrap(); + for module in ["core", "extras", "native", "docs", "modern", "it"] { + std::fs::create_dir_all(root.join(module)).unwrap(); + std::fs::write(root.join(module).join("pom.xml"), "m").unwrap(); + } + std::fs::create_dir_all(root.join(".mvn")).unwrap(); + std::fs::write(root.join(".mvn/maven.config"), "-Pit\n").unwrap(); + + let mut modules = junit_report_modules(&scope, &root, BuildTool::Maven); + modules.sort(); + let mut expected: Vec = + ["core", "docs", "extras", "it", "modern", "native"].iter().map(|m| root.join(m)).collect(); + expected.push(root); + expected.sort(); + assert_eq!(modules, expected); + } + #[test] fn gradle_reports_use_the_owning_build_not_independent_linked_builds() { let temp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-host/src/ops/run.rs b/crates/ide-host/src/ops/run.rs index 5f2b492326..9d652fe8e6 100644 --- a/crates/ide-host/src/ops/run.rs +++ b/crates/ide-host/src/ops/run.rs @@ -134,7 +134,12 @@ fn linked_build_dirs( dirs }; let canonical = |dir: &Path| dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()); - let profiles = settings.languages.java.maven.profiles(&[]); + let activation = ide_build::maven::ProfileActivation::new( + root, + &settings.languages.java.maven, + &[], + super::build::maven_jdk_version(root, settings), + ); let maven_builds = found("maven"); let poms = settings.languages.java.maven.linked_projects.iter().filter_map(|pom| { let pom = root.join(pom.trim()); @@ -143,7 +148,7 @@ fn linked_build_dirs( let maven = poms.map(|dir| ide_core::project_roots::resolve(root, &dir)).filter(|dir| { let dir_canon = canonical(dir); !maven_builds.iter().any(|build| { - dir.starts_with(build) && ide_build::maven::reactor_member_dirs(build, &profiles).contains(&dir_canon) + dir.starts_with(build) && ide_build::maven::reactor_member_dirs(build, &activation).contains(&dir_canon) }) }); let models = gradle.unwrap_or_default(); diff --git a/src/bindings.ts b/src/bindings.ts index 867b750f16..0a9133cada 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -13066,6 +13066,11 @@ export type MavenProfile = { /** Owning project folder when displayed in a workspace. */ projectRoot?: string | null, id: string, + /** + * On unless the Maven tool window turns it off: `activeByDefault` while no other profile of + * its POM is on, its `` holds, or `.mvn/maven.config`, Settings or `settings.xml` + * turn it on. Unticking such a profile passes `-P !id`. + */ activeByDefault: boolean, };