From c0b243f0206ff688ec6bdc2248e6b2180397b1f2 Mon Sep 17 00:00:00 2001 From: langxp Date: Fri, 20 Nov 2026 13:45:47 +0800 Subject: [PATCH] feat(maven): add POM artifact and managed-version navigation (#4699) Go to Declaration on a dependency, plugin or in a POM opens the artifact's own POM (a workspace module with matching coordinates first, then the local repository), and unversioned dependencies and plugins get a gutter icon that opens the management entry supplying their version, through active profiles (including JDK-activated ones), parent POMs, imported BOMs and plugin management. Maven element values are underlined whole, and contributed definition/hover providers that decline a position let the next one answer. Review fix: a BOM import without a version no longer ends the management search. Co-authored-by: kradme <17811095+kradme@users.noreply.github.com> --- crates/ide-build/src/lib.rs | 14 +- crates/ide-build/src/maven.rs | 955 ++++++++++++++++-- crates/ide-host/src/ops/build.rs | 139 ++- src-tauri/tests/commands.snap | 1 + src/bindings.ts | 21 +- src/editor/api.ts | 16 +- .../lsp/configurationNavigation.test.ts | 26 +- src/editor/lsp/configurationNavigation.ts | 56 +- src/editor/lsp/hover.ts | 7 +- src/editor/lsp/navigation.ts | 14 +- src/editor/lsp/navigationShared.test.ts | 51 +- .../build-tools/PomNavigation.module.css | 18 + .../build-tools/pomNavigation.test.ts | 94 +- src/features/build-tools/pomNavigation.ts | 247 ++++- src/features/database/sqlSupport.ts | 5 +- src/platform/buildFiles.ts | 5 + src/platform/locales/text/en.json | 4 +- src/platform/locales/text/zh.json | 4 +- 18 files changed, 1536 insertions(+), 141 deletions(-) create mode 100644 src/features/build-tools/PomNavigation.module.css diff --git a/crates/ide-build/src/lib.rs b/crates/ide-build/src/lib.rs index 3816d9d0f..6d86c4242 100644 --- a/crates/ide-build/src/lib.rs +++ b/crates/ide-build/src/lib.rs @@ -82,11 +82,23 @@ pub fn load_linked( maven_repo: Option, settings: &ide_core::settings::MavenSettings, gradle_settings: &ide_core::settings::GradleSettings, +) -> BuildModel { + load_linked_with_jdk(root, cache_dir, maven_repo, settings, gradle_settings, None) +} + +/// [`load_linked`] with the JDK Maven runs on, for JDK-activated Maven profiles. +pub fn load_linked_with_jdk( + root: &Path, + cache_dir: &Path, + maven_repo: Option, + settings: &ide_core::settings::MavenSettings, + gradle_settings: &ide_core::settings::GradleSettings, + maven_jdk_version: Option, ) -> BuildModel { let maven = maven::has_projects(root, settings).then(|| { let profiles = settings.profiles(&sync::maven_profiles(cache_dir)); let repo = maven_repo.or_else(maven::default_local_repo); - let mut m = maven::load_with_linked(root, repo, &profiles, &settings.linked_projects); + let mut m = maven::load_with_linked_jdk(root, repo, &profiles, maven_jdk_version, &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). for p in maven::user_settings_file(root, settings).map(|f| maven::settings_profiles(&f)).unwrap_or_default() { diff --git a/crates/ide-build/src/maven.rs b/crates/ide-build/src/maven.rs index e4817e371..1a0287ee1 100644 --- a/crates/ide-build/src/maven.rs +++ b/crates/ide-build/src/maven.rs @@ -244,10 +244,14 @@ impl RawPlugin { struct RawProfile { id: String, active_by_default: bool, + /// `` (the common `1.8`, `21` and `[17,)` forms). + activation_jdk: Option, modules: Vec, properties: Vec<(String, String)>, deps: Vec, + managed: Vec, plugins: Vec, + managed_plugins: Vec, } #[derive(Clone, Debug, Default)] @@ -365,13 +369,18 @@ fn read_raw(project: &Element) -> RawPom { 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() == "true"), + activation_jdk: p.at("activation/jdk").map(|jdk| jdk.text.trim().to_owned()).filter(|jdk| !jdk.is_empty()), modules: module_names(p), properties: read_properties(p.child("properties")), deps: p.list("dependencies", "dependency").into_iter().filter_map(read_dep).collect(), + managed: p + .list("dependencyManagement/dependencies", "dependency") + .into_iter() + .filter_map(read_dep) + .collect(), ..RawProfile::default() }; - let mut managed = Vec::new(); - read_build(p, &mut profile.plugins, &mut managed); + read_build(p, &mut profile.plugins, &mut profile.managed_plugins); pom.profiles.push(profile); } pom @@ -482,6 +491,8 @@ 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, poms: HashMap>, contexts: HashMap, } @@ -542,15 +553,30 @@ pub fn local_repository_of(settings: &Path) -> Option { impl Resolver { fn new(local_repo: Option, profiles: &[String]) -> Self { - Self { local_repo, profiles: profiles.to_vec(), poms: HashMap::new(), contexts: HashMap::new() } + Self::new_with_jdk(local_repo, profiles, None) } - /// The active profiles of a POM: the chosen ones, and the `activeByDefault` ones not turned - /// off while none of the POM's other profiles is chosen (Maven's rule). + 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 active profiles of a POM: chosen ones, JDK-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 any_chosen = profiles.iter().any(|p| chosen(&p.id) == Some(true)); - profiles.iter().filter(move |p| chosen(&p.id).unwrap_or(p.active_by_default && !any_chosen)) + let jdk_version = self.jdk_version; + let any_active = profiles.iter().any(|p| { + let choice = chosen(&p.id); + choice == Some(true) + || (choice.is_none() && p.activation_jdk.as_deref().is_some_and(|spec| jdk_matches(spec, jdk_version))) + }); + profiles.iter().filter(move |p| match chosen(&p.id) { + Some(value) => value, + None => { + p.activation_jdk.as_deref().is_some_and(|spec| jdk_matches(spec, jdk_version)) + || (p.active_by_default && !any_active) + } + }) } fn pom(&mut self, path: &Path) -> Option { @@ -615,10 +641,12 @@ impl Resolver { if pom.compiler_release.is_some() { ctx.compiler_release = pom.compiler_release.clone(); } - for p in self.active(&pom.profiles) { + let active = self.active(&pom.profiles).cloned().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, @@ -627,8 +655,12 @@ impl Resolver { ); // 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(); + for p in &active { + merge_by(&mut local_managed, &p.managed, RawDep::key); + } let mut imported: Vec = Vec::new(); - for m in &pom.managed { + for m in &local_managed { if m.scope.as_deref() == Some("import") && depth < MAX_PARENT_DEPTH { let (g, a) = (interpolate(&m.group_id, &props), interpolate(&m.artifact_id, &props)); let v = interpolate(m.version.as_deref().unwrap_or_default(), &props); @@ -637,7 +669,7 @@ impl Resolver { } } } - let own: Vec = pom.managed.iter().filter(|m| m.scope.as_deref() != Some("import")).cloned().collect(); + let own: Vec = local_managed.iter().filter(|m| m.scope.as_deref() != Some("import")).cloned().collect(); merge_by(&mut ctx.managed, &own, RawDep::key); let mut known: HashSet = ctx.managed.iter().map(RawDep::key).collect(); for d in imported { @@ -1105,6 +1137,33 @@ pub(crate) fn load_with_repo(root: &Path, local_repo: Option) -> MavenM load_with(root, local_repo, &[]) } +/// Maven `` matching for the forms used by real POMs: exact/prefix +/// (`21`, `1.8`), negation (`!21`) and major-version ranges (`[17,)`). +fn jdk_matches(spec: &str, jdk_version: Option) -> bool { + let Some(jdk) = jdk_version else { return false }; + let spec = spec.trim(); + match spec.strip_prefix('!') { + Some(spec) => !jdk_term_matches(spec.trim(), jdk), + None => jdk_term_matches(spec, jdk), + } +} + +fn jdk_term_matches(term: &str, jdk: u32) -> bool { + let term = term.trim(); + if let Some(range) = term.strip_prefix('[').or_else(|| term.strip_prefix('(')) + && let Some((lower, upper)) = range.split_once(',') + { + let lower = lower.trim().trim_end_matches([']', ')']); + let upper = upper.trim().trim_end_matches([']', ')']); + let lower_ok = lower.is_empty() + || java_version(lower).is_some_and(|v| if term.starts_with('[') { jdk >= v } else { jdk > v }); + let upper_ok = upper.is_empty() + || java_version(upper).is_some_and(|v| if term.ends_with(']') { jdk <= v } else { jdk < v }); + return lower_ok && upper_ok; + } + 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| { @@ -1347,7 +1406,19 @@ pub fn load_with_linked( profiles: &[String], linked: &[String], ) -> MavenModel { - let mut resolver = Resolver::new(local_repo, profiles); + load_with_linked_jdk(root, local_repo, profiles, None, linked) +} + +/// [`load_with_linked`] with the JDK Maven runs on, so `` +/// profiles contribute the same modules, properties and management as the build. +pub fn load_with_linked_jdk( + root: &Path, + local_repo: Option, + profiles: &[String], + jdk_version: Option, + linked: &[String], +) -> MavenModel { + let mut resolver = Resolver::new_with_jdk(local_repo, profiles, jdk_version); let mut model = MavenModel::default(); // Canonical POM → its project, for a module listed again by a later aggregator. let mut seen: HashMap> = HashMap::new(); @@ -1788,13 +1859,61 @@ pub enum PomGotoKind { ArtifactPom, } +/// A dependency or plugin whose version comes from a management declaration. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PomManagedDeclaration { + /// 0-based line of the `` or `` declaration. + pub line: u32, + /// The interpolated version the management entry provides, when it has one. + pub version: Option, + /// The management entry, possibly in a parent POM or an imported BOM. + pub target: PomGoto, +} + +/// Resolution settings shared by POM navigation and managed-version gutters. +#[derive(Clone, Debug, Default)] +pub struct PomNavigationOptions { + pub local_repo: Option, + /// `-P` choices that decide which profile's management and properties apply. + pub profiles: Vec, + /// Maven's runtime JDK major, for ``. + pub jdk_version: Option, +} + /// A Maven project of the workspace, for going to a dependency on it. +#[derive(Clone, Debug)] pub struct ModulePom { pub group_id: String, pub artifact_id: String, + pub version: String, pub pom: PathBuf, } +/// The coordinates that select a `` entry. Type and +/// classifier participate because Maven can manage the same artifact in several +/// classifier-specific variants (the common `jdk8` / `jdk21` setup). +#[derive(Clone, Debug, PartialEq, Eq)] +struct DependencyKey { + group_id: String, + artifact_id: String, + kind: String, + classifier: String, +} + +impl DependencyKey { + fn label(&self) -> String { + format!("{}:{}", self.group_id, self.artifact_id) + } +} + +/// A management declaration plus the version it supplies, used to resolve the +/// artifact POM for dependencies that omit ``. +struct ManagedDeclaration { + target: PomGoto, + version: Option, +} + /// Byte offset of `pos` (0-based line / UTF-16 column), clamped to `text`. fn offset_at(text: &str, pos: Pos) -> usize { let (mut line_seen, mut at) = (0usize, 0usize); @@ -1872,7 +1991,13 @@ fn coordinates(e: &Element, props: &HashMap) -> Option<(String, /// the local repository when it is not in the project). `None` when there is no /// resolvable declaration here. pub fn goto_declaration(text: &str, path: &Path, pos: Pos, local_repo: Option) -> Option { - goto_declaration_in(text, path, pos, local_repo, Vec::new) + goto_declaration_with( + text, + path, + pos, + PomNavigationOptions { local_repo, ..PomNavigationOptions::default() }, + Vec::new, + ) } /// The declaration of the property `name` in the pom at `path`, for files it configures @@ -1880,7 +2005,7 @@ pub fn goto_declaration(text: &str, path: &Path, pos: Pos, local_repo: Option) -> Option { let text = xml::read_text(pom)?; - property_target(&text, pom, name, local_repo) + property_target(&text, pom, name, &PomNavigationOptions { local_repo, ..PomNavigationOptions::default() }) } /// [`goto_declaration`], where a `` and a dependency or plugin whose version no @@ -1893,35 +2018,163 @@ pub fn goto_declaration_in( pos: Pos, local_repo: Option, modules: impl FnOnce() -> Vec, +) -> Option { + goto_declaration_with( + text, + path, + pos, + PomNavigationOptions { local_repo, ..PomNavigationOptions::default() }, + modules, + ) +} + +/// [`goto_declaration_in`] with the active profiles and Maven runtime JDK that decide +/// profile properties and `` entries. +pub fn goto_declaration_with( + text: &str, + path: &Path, + pos: Pos, + options: PomNavigationOptions, + modules: impl FnOnce() -> Vec, ) -> Option { let root = xml::parse(text).filter(|e| e.name == "project")?; let at = offset_at(text, pos); if let Some((name, _, _)) = property_ref_at(text, at) && !name.is_empty() { - return property_target(text, path, name, local_repo); + return property_target(text, path, name, &options); } - // A `` / `` in a declaration position: its version may come - // from a management entry of this POM or an ancestor's. + + // The build model is expensive to assemble and most navigation targets do not + // need it (properties, parent POMs in the local repository, BOM imports), so + // only read it when a project module can be the answer. + let module_cache = std::cell::OnceCell::new(); + let mut load_modules = Some(modules); + let mut module_poms = + || module_cache.get_or_init(|| load_modules.take().expect("the module loader runs at most once")()).clone(); + let elements = element_path(&root, at); if elements.get(1).is_some_and(|e| e.name == "parent") { - let chain = parent_chain(path, text, local_repo); - let (pom, parent_text) = chain.get(1)?; - let label = elements[1].text_of("artifactId").unwrap_or_default(); - return Some(pom_goto(pom.clone(), parent_text, label)); + return parent_target(elements[1], path, text, &options, &mut module_poms); } let e = elements.iter().rev().find(|e| e.name == "dependency" || e.name == "plugin")?; - // A management entry declares the version: it goes to the artifact (a BOM import, say). - if !elements.iter().any(|a| a.name == "dependencyManagement" || a.name == "pluginManagement") { - let kind = match e.name.as_str() { - "dependency" => PomGotoKind::ManagedDependency, - _ => PomGotoKind::ManagedPlugin, + if elements.iter().any(|a| a.name == "dependencyManagement" || a.name == "pluginManagement") { + // A management entry itself describes an artifact (a BOM import, for example), + // not a declaration whose version is inherited from another management entry. + return artifact_target(text, path, e, &options, &mut module_poms, false); + } + + // IDEA's Ctrl/Cmd-click on a coordinate opens the artifact POM. A dependency on a + // reactor module therefore opens that module even when the root POM also manages + // its version. If the artifact POM is unavailable, the management entry remains a + // useful fallback instead of leaving the coordinate without navigation. + if let Some(found) = artifact_target(text, path, e, &options, &mut module_poms, true) { + return Some(found); + } + // An explicit version wins over dependencyManagement. If its artifact POM is not + // available, never navigate to a management entry for a different version. + if e.text_of("version").is_some() { + return None; + } + let kind = if e.name == "dependency" { PomGotoKind::ManagedDependency } else { PomGotoKind::ManagedPlugin }; + managed_target(text, path, e, kind, &options, &mut module_poms).map(|m| m.target) +} + +/// Where every unversioned direct dependency / plugin gets its version. These are +/// the gutter markers IDEA labels "Navigate to managing dependency"; a declaration +/// with its own `` is intentionally absent because that value wins. +pub fn managed_declarations( + text: &str, + path: &Path, + local_repo: Option, + modules: impl FnOnce() -> Vec, +) -> Vec { + managed_declarations_with( + text, + path, + PomNavigationOptions { local_repo, ..PomNavigationOptions::default() }, + modules, + ) +} + +/// [`managed_declarations`] with active profiles and the Maven runtime JDK. +pub fn managed_declarations_with( + text: &str, + path: &Path, + options: PomNavigationOptions, + modules: impl FnOnce() -> Vec, +) -> Vec { + let Some(root) = xml::parse(text).filter(|e| e.name == "project") else { return Vec::new() }; + let module_cache = std::cell::OnceCell::new(); + let mut load_modules = Some(modules); + let mut module_poms = + || module_cache.get_or_init(|| load_modules.take().expect("the module loader runs at most once")()).clone(); + 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 mut add = |e: &Element, kind: PomGotoKind| { + if e.text_of("version").is_some() { + return; + } + let Some(managed) = managed_target(text, path, e, kind, &options, &mut module_poms) else { + return; }; - if let Some(found) = managed_target(text, path, e, kind, local_repo.clone()) { - return Some(found); + let line = pos_at(text, e.start).line; + if seen.insert(line) { + out.push(PomManagedDeclaration { line, version: managed.version, target: managed.target }); + } + }; + + for dependency in root.list("dependencies", "dependency") { + add(dependency, PomGotoKind::ManagedDependency); + } + for plugin in root.list("build/plugins", "plugin") { + add(plugin, PomGotoKind::ManagedPlugin); + } + for profile in + profiles.into_iter().filter(|profile| profile.text_of("id").is_some_and(|id| active_profiles.contains(&id))) + { + for dependency in profile.list("dependencies", "dependency") { + add(dependency, PomGotoKind::ManagedDependency); + } + for plugin in profile.list("build/plugins", "plugin") { + add(plugin, PomGotoKind::ManagedPlugin); } } - artifact_target(text, path, e, local_repo, modules) + out.sort_by_key(|d| d.line); + out +} + +/// The `` target: the POM found through `relativePath` / the local repository, +/// else a project module from another opened build with the same coordinates. +fn parent_target( + parent: &Element, + path: &Path, + text: &str, + options: &PomNavigationOptions, + modules: &mut dyn FnMut() -> Vec, +) -> Option { + let group = parent.text_of("groupId")?; + let artifact = parent.text_of("artifactId")?; + let version = parent.text_of("version").unwrap_or_default(); + // Prefer the source POM when the parent is another project in the workspace; + // an installed copy in the local repository is only the fallback. A stale module + // entry must not hide that fallback when its file has since disappeared. + if let Some(module) = modules().into_iter().find(|m| module_matches(m, &group, &artifact, Some(&version))) + && let Some(module_text) = xml::read_text(&module.pom) + { + return Some(pom_goto(module.pom, &module_text, artifact)); + } + let chain = parent_chain(path, text, options.local_repo.clone()); + 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 parent_text = xml::read_text(&pom)?; + Some(pom_goto(pom, &parent_text, artifact)) } /// The artifact's own POM for a dependency or plugin element `e`. @@ -1929,24 +2182,43 @@ fn artifact_target( text: &str, path: &Path, e: &Element, - local_repo: Option, - modules: impl FnOnce() -> Vec, + options: &PomNavigationOptions, + modules: &mut dyn FnMut() -> Vec, + use_managed_version: bool, ) -> Option { - let mut resolver = Resolver::new(local_repo.clone(), &[]); - let chain = parent_chain(path, text, local_repo); + let mut resolver = Resolver::new_with_jdk(options.local_repo.clone(), &options.profiles, options.jdk_version); + let chain = parent_chain(path, text, options.local_repo.clone()); let props = properties_at(&mut resolver, &chain, 0); let (group, artifact) = coordinates(e, &props)?; let label = format!("{group}:{artifact}"); - if let Some(module) = modules().into_iter().find(|m| m.group_id == group && m.artifact_id == artifact) { - let module_text = xml::read_text(&module.pom)?; + let explicit = e.text_of("version").map(|v| interpolate(&v, &props)); + let managed = if explicit.is_none() && use_managed_version { + let kind = if e.name == "plugin" { PomGotoKind::ManagedPlugin } else { PomGotoKind::ManagedDependency }; + managed_target(text, path, e, kind, options, modules) + } else { + None + }; + let version = explicit.clone().or_else(|| managed.as_ref().and_then(|m| m.version.clone())); + if let Some(module) = modules().into_iter().find(|m| module_matches(m, &group, &artifact, version.as_deref())) + && let Some(module_text) = xml::read_text(&module.pom) + { return Some(pom_goto(module.pom, &module_text, label)); } - let version = interpolate(&e.text_of("version")?, &props); + + let version = version.or_else(|| managed.and_then(|m| m.version))?; let pom = resolver.repo_pom(&group, &artifact, &version)?; let pom_text = xml::read_text(&pom)?; Some(pom_goto(pom, &pom_text, label)) } +/// A versioned dependency resolves only to the workspace module with the same +/// version; unresolved/property versions fall back to coordinates alone. +fn module_matches(module: &ModulePom, group: &str, artifact: &str, version: Option<&str>) -> bool { + module.group_id == group + && module.artifact_id == artifact + && version.is_none_or(|v| v.is_empty() || v.contains("${") || module.version == v) +} + /// The POM at `path` as a target, at its ``. fn pom_goto(path: PathBuf, text: &str, label: String) -> PomGoto { let range = xml::parse(text) @@ -1990,10 +2262,10 @@ fn properties_at(resolver: &mut Resolver, chain: &[(PathBuf, String)], i: usize) /// coordinate elements, the rest to the first `` entry along the parent /// chain declaring it (a child's definition wins over a parent's; an active /// 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, local_repo: Option) -> Option { +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(local_repo.clone(), &[]); - let chain = parent_chain(path, text, local_repo); + let resolver = Resolver::new_with_jdk(options.local_repo.clone(), &options.profiles, options.jdk_version); + 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. let parent_key = match name.as_str() { @@ -2086,39 +2358,135 @@ fn properties_target(chain: &[(PathBuf, String)], name: &str, resolver: &Resolve } /// The `` / `` entry providing the version -/// of the dependency / plugin element `e`: this POM's own management first, then the -/// parent chain, child-first (the nearest declaration wins). Coordinates are matched -/// after interpolation with each POM's effective properties. +/// of the dependency / plugin element `e`. Direct entries in the current POM win, +/// then its imported BOMs, then the same order in each parent (the nearest model +/// wins). Coordinates include type and classifier, matching Maven's management key. fn managed_target( text: &str, path: &Path, e: &Element, kind: PomGotoKind, - local_repo: Option, -) -> Option { - let mut resolver = Resolver::new(local_repo.clone(), &[]); - let chain = parent_chain(path, text, local_repo); - let key = coordinates(e, &properties_at(&mut resolver, &chain, 0))?; - let (section, item) = match kind { - PomGotoKind::ManagedDependency => ("dependencyManagement/dependencies", "dependency"), - _ => ("build/pluginManagement/plugins", "plugin"), - }; - for (i, (p, text)) in chain.iter().enumerate() { - let root = xml::parse(text).filter(|e| e.name == "project")?; - let props = properties_at(&mut resolver, &chain, i); - let Some(hit) = root.list(section, item).into_iter().find(|m| coordinates(m, &props).as_ref() == Some(&key)) - else { - continue; - }; - let target = hit.child("artifactId").unwrap_or(hit); - return Some(PomGoto { - path: p.clone(), - range: range_of(text, target), - kind, - label: format!("{}:{}", key.0, key.1), - }); + 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 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 { + 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() +} + +/// State shared by the recursive management lookup: visited BOMs prevent import +/// cycles, and the module loader stays lazy until a project BOM is encountered. +struct ManagedSearch<'a> { + options: &'a PomNavigationOptions, + key: DependencyKey, + kind: PomGotoKind, + modules: &'a mut dyn FnMut() -> Vec, + visited: HashSet, +} + +impl ManagedSearch<'_> { + fn in_pom(&mut self, path: &Path, text: &str, depth: usize) -> Option { + if depth >= MAX_PARENT_DEPTH { + return None; + } + let canonical = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + if !self.visited.insert(canonical) { + 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); + 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); + let (section, item) = match self.kind { + PomGotoKind::ManagedDependency => ("dependencyManagement/dependencies", "dependency"), + PomGotoKind::ManagedPlugin => ("build/pluginManagement/plugins", "plugin"), + _ => return None, + }; + 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 profiles = root + .list("profiles", "profile") + .into_iter() + .filter(|profile| profile.text_of("id").is_some_and(|id| active.contains(&id))) + .flat_map(|profile| profile.list(section, item)) + .collect::>(); + // Profile entries overlay the POM's base model; later active profiles win. + let mut direct = profiles.iter().rev().copied().filter(|entry| !imported(entry)).collect::>(); + direct.extend(base.iter().copied().filter(|entry| !imported(entry))); + if let Some(hit) = + direct.into_iter().find(|entry| dependency_key(entry, &props).as_ref() == Some(&self.key)) + { + let version = hit.text_of("version").map(|v| interpolate(&v, &props)); + let target = hit.child("artifactId").unwrap_or(hit); + return Some(ManagedDeclaration { + target: PomGoto { + path: p.clone(), + range: range_of(t, target), + kind: self.kind, + label: self.key.label(), + }, + version, + }); + } + if self.kind != PomGotoKind::ManagedDependency { + continue; + } + // An imported BOM contributes management entries at the importing POM's + // position, so direct entries above win; profile imports overlay the base. + let imports = profiles + .iter() + .rev() + .copied() + .filter(|entry| imported(entry)) + .chain(base.iter().copied().filter(|entry| imported(entry))); + for import in imports { + let Some((group, artifact)) = coordinates(import, &props) else { continue }; + // An import without a version can't be resolved; the remaining imports and parents still can. + let Some(version) = import.text_of("version").map(|v| interpolate(&v, &props)) else { continue }; + // A source module is authoritative over an installed copy: the local + // repository may be stale or may not contain current workspace edits. + let bom = (self.modules)() + .into_iter() + .find(|m| module_matches(m, &group, &artifact, Some(&version))) + .map(|m| m.pom) + .or_else(|| resolver.repo_pom(&group, &artifact, &version)); + let Some(bom) = bom else { continue }; + let Some(bom_text) = xml::read_text(&bom) else { continue }; + if let Some(found) = self.in_pom(&bom, &bom_text, depth + 1) { + return Some(found); + } + } + } + None } - None +} + +/// Maven's dependency-management key: group, artifact, type (default `jar`) and +/// classifier all have to match. Plugins are keyed by group and artifact. +fn dependency_key(e: &Element, props: &HashMap) -> Option { + let (group_id, artifact_id) = coordinates(e, props)?; + let (kind, classifier) = if e.name == "plugin" { + ("plugin".to_owned(), String::new()) + } else { + ( + interpolate(e.text_of("type").as_deref().unwrap_or("jar"), props), + e.text_of("classifier").map(|c| interpolate(&c, props)).unwrap_or_default(), + ) + }; + Some(DependencyKey { group_id, artifact_id, kind, classifier }) } /// The range of element `e` in `text`. @@ -3404,6 +3772,453 @@ mod tests { assert_eq!(goto_declaration("", &path, Pos::new(0, 3), None), None); } + #[test] + fn an_explicit_version_never_falls_back_to_management() { + let tmp = tempfile::tempdir().unwrap(); + let parent = format!( + r#"{PARENT_HEADER} + + com.examplelib1.0 + + +"# + ); + let child = format!( + r#"{CHILD_HEADER} + + com.example + lib + 2.0 + + +"# + ); + write_parent_child(tmp.path(), &parent, &child); + let path = tmp.path().join("app/pom.xml"); + let text = std::fs::read_to_string(&path).unwrap(); + assert_eq!(goto_declaration(&text, &path, at(&text, "lib"), None), None); + } + + #[test] + fn a_jdk_profile_controls_both_the_management_target_and_version() { + let tmp = tempfile::tempdir().unwrap(); + let parent = format!( + r#"{PARENT_HEADER} + + jdk8 + true + 1.8 + + com.examplelib${{managed.version}} + + com.examplelib + + + jdk21 + 21 + 21.0 + + com.examplelib${{managed.version}} + + +"# + ); + let child = format!( + r#"{CHILD_HEADER} + com.examplelib + +"# + ); + write_parent_child(tmp.path(), &parent, &child); + let path = tmp.path().join("app/pom.xml"); + let text = std::fs::read_to_string(&path).unwrap(); + let options = PomNavigationOptions { jdk_version: Some(21), ..PomNavigationOptions::default() }; + let links = managed_declarations_with(&text, &path, options, Vec::new); + assert_eq!(links.len(), 1); + assert_eq!(links[0].version.as_deref(), Some("21.0")); + assert_eq!(links[0].target.path, canon(&tmp.path().join("pom.xml"))); + + let jdk8 = managed_declarations_with( + &text, + &path, + PomNavigationOptions { jdk_version: Some(8), ..PomNavigationOptions::default() }, + Vec::new, + ); + assert_eq!(jdk8[0].version.as_deref(), Some("1.8")); + + let selected = managed_declarations_with( + &text, + &path, + PomNavigationOptions { profiles: vec!["jdk21".into()], ..PomNavigationOptions::default() }, + Vec::new, + ); + assert_eq!(selected[0].version.as_deref(), Some("21.0")); + } + + #[test] + fn jdk_profile_activation_supports_ranges_and_negation() { + assert!(jdk_matches("21", Some(21))); + assert!(jdk_matches("1.8", Some(8))); + assert!(jdk_matches("[17,)", Some(21))); + assert!(!jdk_matches("[17,21)", Some(21))); + assert!(jdk_matches("![17,)", Some(8))); + } + + #[test] + fn jdk_activated_profiles_contribute_modules_to_the_build_model() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(tmp.path().join("jdk21")).unwrap(); + std::fs::write(tmp.path().join("jdk21/pom.xml"), "jdk21").unwrap(); + std::fs::write( + tmp.path().join("pom.xml"), + r#"com.exampleroot1pom +jdk2121jdk21 +"#, + ) + .unwrap(); + let off = load_with_linked_jdk(tmp.path(), None, &[], Some(17), &[]); + assert!(!off.projects.iter().any(|project| project.artifact_id == "jdk21")); + let on = load_with_linked_jdk(tmp.path(), None, &[], Some(21), &[]); + assert!(on.projects.iter().any(|project| project.artifact_id == "jdk21")); + } + + #[test] + fn a_module_is_matched_by_group_artifact_and_version() { + let tmp = tempfile::tempdir().unwrap(); + let parent = format!(r#"{PARENT_HEADER}"#); + let child = format!( + r#"{CHILD_HEADER} + com.examplecore1.0 + +"# + ); + write_parent_child(tmp.path(), &parent, &child); + let v2 = tmp.path().join("core-v2/pom.xml"); + let v1 = tmp.path().join("core-v1/pom.xml"); + for (path, version) in [(&v2, "2.0"), (&v1, "1.0")] { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write( + path, + format!( + "com.examplecore{version}" + ), + ) + .unwrap(); + } + let path = tmp.path().join("app/pom.xml"); + let text = std::fs::read_to_string(&path).unwrap(); + let modules = || { + vec![ + ModulePom { + group_id: "com.example".into(), + artifact_id: "core".into(), + version: "2.0".into(), + pom: v2.clone(), + }, + ModulePom { + group_id: "com.example".into(), + artifact_id: "core".into(), + version: "1.0".into(), + pom: v1.clone(), + }, + ] + }; + let goto = goto_declaration_in(&text, &path, at(&text, "core"), None, modules).unwrap(); + assert_eq!(goto.path, v1); + } + + #[test] + fn a_managed_reactor_module_opens_its_pom_and_keeps_a_management_gutter() { + let tmp = tempfile::tempdir().unwrap(); + let parent = format!( + r#"{PARENT_HEADER} + + + com.example + core + 2.0 + + + +"# + ); + let child = format!( + r#"{CHILD_HEADER} + + com.example + core + + +"# + ); + write_parent_child(tmp.path(), &parent, &child); + let core = tmp.path().join("core/pom.xml"); + std::fs::create_dir_all(core.parent().unwrap()).unwrap(); + std::fs::write( + &core, + "com.examplecore2.0", + ) + .unwrap(); + let modules = || { + vec![ModulePom { + group_id: "com.example".into(), + artifact_id: "core".into(), + version: "2.0".into(), + pom: core.clone(), + }] + }; + + let path = tmp.path().join("app/pom.xml"); + let text = std::fs::read_to_string(&path).unwrap(); + let goto = goto_declaration_in(&text, &path, at(&text, "core"), None, modules).unwrap(); + assert_eq!((goto.path.as_path(), goto.kind), (core.as_path(), PomGotoKind::ArtifactPom)); + + let links = managed_declarations(&text, &path, None, modules); + assert_eq!(links.len(), 1); + assert_eq!(links[0].version.as_deref(), Some("2.0")); + assert_eq!(links[0].target.path, canon(&tmp.path().join("pom.xml"))); + assert_eq!(links[0].target.kind, PomGotoKind::ManagedDependency); + } + + #[test] + fn a_parent_module_in_the_workspace_wins_over_its_installed_pom() { + let tmp = tempfile::tempdir().unwrap(); + let app = tmp.path().join("app"); + let parent = tmp.path().join("parent/pom.xml"); + std::fs::create_dir_all(&app).unwrap(); + std::fs::create_dir_all(parent.parent().unwrap()).unwrap(); + let child = r#" + + com.example + parent + 1.0 + + + app +"#; + std::fs::write(app.join("pom.xml"), child).unwrap(); + let parent_text = + "com.exampleparent1.0"; + std::fs::write(&parent, parent_text).unwrap(); + let modules = || { + vec![ModulePom { + group_id: "com.example".into(), + artifact_id: "parent".into(), + version: "1.0".into(), + pom: parent.clone(), + }] + }; + + let path = app.join("pom.xml"); + let goto = goto_declaration_in(child, &path, at(child, "parent"), None, modules).unwrap(); + assert_eq!(goto.path, parent); + assert_eq!(goto.range.start, at(parent_text, "parent")); + } + + #[test] + fn management_matches_the_classifier_that_actually_controls_the_version() { + let tmp = tempfile::tempdir().unwrap(); + let parent = format!( + r#"{PARENT_HEADER} + jdk21 + + + + + com.example + api + jdk8 + 8.0 + + + com.example + api + jdk21 + 21.0 + + + +"# + ); + let child = format!( + r#"{CHILD_HEADER} + + com.example + api + ${{active.classifier}} + + +"# + ); + write_parent_child(tmp.path(), &parent, &child); + let path = tmp.path().join("app/pom.xml"); + let text = std::fs::read_to_string(&path).unwrap(); + + let links = managed_declarations(&text, &path, None, Vec::new); + assert_eq!(links.len(), 1); + assert_eq!(links[0].version.as_deref(), Some("21.0")); + assert_eq!(links[0].target.range.start, at(&parent, "api\n jdk21")); + } + + #[test] + fn an_imported_bom_supplies_the_gutter_target_and_version() { + let tmp = tempfile::tempdir().unwrap(); + let repo = tmp.path().join("repo"); + let bom_path = repo.join("com/example/platform-bom/1.0/platform-bom-1.0.pom"); + std::fs::create_dir_all(bom_path.parent().unwrap()).unwrap(); + let bom = r#" + com.example + platform-bom + 1.0 + 2.3 + + + + com.example + bom-lib + ${managed.version} + + + +"#; + std::fs::write(&bom_path, bom).unwrap(); + let parent = format!( + r#"{PARENT_HEADER} + + + com.example + platform-bom + 1.0 + pom + import + + + +"# + ); + let child = format!( + r#"{CHILD_HEADER} + + com.example + bom-lib + + +"# + ); + write_parent_child(tmp.path(), &parent, &child); + let path = tmp.path().join("app/pom.xml"); + let text = std::fs::read_to_string(&path).unwrap(); + let links = managed_declarations(&text, &path, Some(repo), Vec::new); + assert_eq!(links.len(), 1); + assert_eq!(links[0].version.as_deref(), Some("2.3")); + assert_eq!(links[0].target.path, canon(&bom_path)); + assert_eq!(links[0].target.range.start, at(bom, "bom-lib")); + } + + #[test] + fn an_import_without_a_version_does_not_hide_the_next_bom() { + let tmp = tempfile::tempdir().unwrap(); + let repo = tmp.path().join("repo"); + let bom_path = repo.join("com/example/platform-bom/1.0/platform-bom-1.0.pom"); + std::fs::create_dir_all(bom_path.parent().unwrap()).unwrap(); + let bom = "com.exampleplatform-bom1.0com.examplelib3.0"; + std::fs::write(&bom_path, bom).unwrap(); + let parent = format!( + r#"{PARENT_HEADER} + com.exampleunversioned-bompomimport + com.exampleplatform-bom1.0pomimport +"# + ); + let child = format!( + r#"{CHILD_HEADER}com.examplelib"# + ); + write_parent_child(tmp.path(), &parent, &child); + let path = tmp.path().join("app/pom.xml"); + let text = std::fs::read_to_string(&path).unwrap(); + let links = managed_declarations(&text, &path, Some(repo), Vec::new); + assert_eq!(links.len(), 1); + assert_eq!(links[0].version.as_deref(), Some("3.0")); + assert_eq!(links[0].target.path, canon(&bom_path)); + } + + #[test] + fn a_workspace_bom_wins_over_an_installed_copy() { + let tmp = tempfile::tempdir().unwrap(); + let repo = tmp.path().join("repo"); + let installed = repo.join("com/example/platform-bom/1.0/platform-bom-1.0.pom"); + std::fs::create_dir_all(installed.parent().unwrap()).unwrap(); + std::fs::write( + &installed, + "com.exampleplatform-bom1.0com.examplelib1.0", + ) + .unwrap(); + let workspace = tmp.path().join("platform-bom/pom.xml"); + std::fs::create_dir_all(workspace.parent().unwrap()).unwrap(); + let workspace_text = "com.exampleplatform-bom1.0com.examplelib2.0"; + std::fs::write(&workspace, workspace_text).unwrap(); + let parent = format!( + r#"{PARENT_HEADER} + com.exampleplatform-bom1.0pomimport +"# + ); + let child = format!( + r#"{CHILD_HEADER}com.examplelib"# + ); + write_parent_child(tmp.path(), &parent, &child); + let modules = || { + vec![ModulePom { + group_id: "com.example".into(), + artifact_id: "platform-bom".into(), + version: "1.0".into(), + pom: workspace.clone(), + }] + }; + let path = tmp.path().join("app/pom.xml"); + let text = std::fs::read_to_string(&path).unwrap(); + let links = managed_declarations(&text, &path, Some(repo), modules); + assert_eq!(links.len(), 1); + assert_eq!(links[0].version.as_deref(), Some("2.0")); + assert_eq!(links[0].target.path, canon(&workspace)); + } + + #[test] + fn gutter_links_cover_unversioned_dependencies_and_plugins_only() { + let tmp = tempfile::tempdir().unwrap(); + let parent = format!( + r#"{PARENT_HEADER} + + com.examplemanaged-lib1.0 + + + + com.examplebuilder2.0 + +"# + ); + let child = format!( + r#"{CHILD_HEADER}3.0 + + com.examplemanaged-lib + com.exampleexplicit-lib3.0 + com.exampleproperty-lib${{own.version}} + + + com.examplebuilder + +"# + ); + write_parent_child(tmp.path(), &parent, &child); + let path = tmp.path().join("app/pom.xml"); + let text = std::fs::read_to_string(&path).unwrap(); + let links = managed_declarations(&text, &path, None, Vec::new); + assert_eq!(links.len(), 2); + assert_eq!( + links.iter().map(|l| (l.line, l.version.as_deref())).collect::>(), + [(9, Some("1.0")), (14, Some("2.0"))] + ); + assert!(links.iter().all(|l| l.target.path == canon(&tmp.path().join("pom.xml")))); + } + #[test] fn artifacts_go_to_their_own_pom_in_the_project_or_the_local_repository() { let tmp = tempfile::tempdir().unwrap(); @@ -3445,8 +4260,14 @@ mod tests { "\n com.example\n core\n", ) .unwrap(); - let modules = - || vec![ModulePom { group_id: "com.example".into(), artifact_id: "core".into(), pom: core.clone() }]; + let modules = || { + vec![ModulePom { + group_id: "com.example".into(), + artifact_id: "core".into(), + version: "1.0".into(), + pom: core.clone(), + }] + }; // A BOM import in opens the BOM from the local repository. let parent_path = tmp.path().join("pom.xml"); diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index a5859c04f..ee1466247 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -8,30 +8,79 @@ use crate::{Host, Project}; use ide_command::command; use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult}; -use ide_build::maven::PomGoto; use ide_build::maven::completion::{PomCompletion, PomCompletionOption}; +use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions}; use ide_build::pom_edit::{ArtifactKey, Exclusion}; use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress}; use ide_core::settings::Settings; use ide_core::{DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit}; +use std::collections::HashMap; use std::path::Path; -use std::sync::Arc; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; fn join_err(e: tokio::task::JoinError) -> IdeError { IdeError::internal(e.to_string()) } +/// POM gutters in several editors refresh together. A very short cache lets those +/// requests share one reactor scan without serving a stale module list after edits settle. +const MAVEN_MODULE_CACHE_TTL: Duration = Duration::from_millis(250); +type MavenModuleCache = HashMap)>; +static MAVEN_MODULES: OnceLock> = OnceLock::new(); + +fn maven_modules( + project: &Project, + settings: &Settings, + options: &PomNavigationOptions, +) -> Vec { + let key = format!( + "{}\0{:?}\0{:?}\0{:?}\0{:?}", + project.root.display(), + project.build_cache_dir(), + settings.languages.java.maven.linked_projects, + options.profiles, + options.jdk_version + ); + let cache = MAVEN_MODULES.get_or_init(|| Mutex::new(HashMap::new())); + if let Some((_at, modules)) = cache.lock().ok().and_then(|mut cache| { + let fresh = cache.get(&key).filter(|(at, _)| at.elapsed() < MAVEN_MODULE_CACHE_TTL).cloned(); + if fresh.is_none() { + cache.remove(&key); + } + fresh + }) { + return modules; + } + let model = load(&project.root, &project.build_cache_dir(), settings).maven.unwrap_or_default(); + let modules = model + .projects + .into_iter() + .map(|p| ide_build::maven::ModulePom { + group_id: p.group_id, + artifact_id: p.artifact_id, + version: p.version, + pom: project.root.join(&p.pom), + }) + .collect::>(); + if let Ok(mut cache) = cache.lock() { + cache.insert(key, (Instant::now(), modules.clone())); + } + modules +} + /// The build model with the launch settings applied: the JDK (`JAVA_HOME`), and /// the Maven home and options from Settings › Maven. pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel { - let mut model = ide_build::load_linked( + 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 jdk = ide_sdk::apply::project_jdk(root, 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); @@ -77,6 +126,23 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel { model } +/// 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(&[]); + for profile in ide_build::maven_profiles(&project.build_cache_dir()) { + if !profiles.contains(&profile) { + profiles.push(profile); + } + } + PomNavigationOptions { + 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), + } +} + /// Build and Run use the same selected toolchain and module-local runtime discovery. fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings) -> compile::BuildPlan { let kind = match plan.system { @@ -547,8 +613,9 @@ pub async fn maven_dependency_declaration( } /// The go-to-declaration target at `pos` of a Maven POM: the definition of the -/// `${property}` at the caret, or the `` / `` -/// entry providing the dependency's / plugin's version, along the parent chain. +/// `${property}` at the caret, the parent POM, or the dependency / plugin's own POM +/// (a project module first, then the local repository). A dependency without a +/// resolvable artifact POM falls back to its management entry. #[command(trust = trusted)] pub async fn maven_goto_declaration(host: &Host, window: &str, pom: String, pos: Pos) -> IdeResult> { // `pom` is project-relative, or absolute for a parent POM opened from the local repository. @@ -561,26 +628,55 @@ pub async fn maven_goto_declaration(host: &Host, window: &str, pom: String, pos: let path = if given.is_absolute() { given.to_path_buf() } else { project.root.join(given) }; let text = project.text_of(&path)?; let settings = project.settings.effective(); - let repo = ide_sdk::apply::maven_local_repository(&project.root, &settings) - .or_else(ide_build::maven::default_local_repo); - let modules = || { - let model = load(&project.root, &project.build_cache_dir(), &settings).maven.unwrap_or_default(); - model - .projects - .into_iter() - .map(|p| ide_build::maven::ModulePom { - group_id: p.group_id, - artifact_id: p.artifact_id, - pom: project.root.join(&p.pom), - }) - .collect() - }; - Ok(ide_build::maven::goto_declaration_in(&text, &path, pos, repo, modules)) + let options = pom_navigation_options(&project, &settings); + let module_options = options.clone(); + let modules = || maven_modules(&project, &settings, &module_options); + Ok(ide_build::maven::goto_declaration_with(&text, &path, pos, options, modules)) }) .await .map_err(join_err)? } +/// Gutter targets of the unversioned dependencies and plugins in a Maven POM: +/// the management declarations that actually supply their versions, including +/// parent POMs and imported BOMs. Cancel with `cancel_request(request)`. +#[command(trust = trusted)] +pub async fn maven_managed_declarations( + host: &Host, + window: &str, + pom: String, + request: RequestId, +) -> IdeResult> { + let project = host.project(window)?; + let cancel = host.begin_project_read_request(window, request); + let result = tokio::task::spawn_blocking(move || { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let given = Path::new(&pom); + let path = if given.is_absolute() { given.to_path_buf() } else { project.root.join(given) }; + let text = project.text_of(&path)?; + let settings = project.settings.effective(); + let options = pom_navigation_options(&project, &settings); + let cancelled = cancel.clone(); + let module_options = options.clone(); + let modules = || { + if cancelled.is_cancelled() { + return Vec::new(); + } + maven_modules(&project, &settings, &module_options) + }; + let declarations = ide_build::maven::managed_declarations_with(&text, &path, options, modules); + if cancel.is_cancelled() { Err(IdeError::cancelled()) } else { Ok(declarations) } + }) + .await; + host.end_request(request); + match result { + Ok(result) => result, + Err(error) => Err(join_err(error)), + } +} + /// How long completion waits for Maven Central before answering from the local repository. const CENTRAL_WAIT: std::time::Duration = std::time::Duration::from_secs(1); @@ -1333,4 +1429,5 @@ ide_command::domain!( maven_dependency_declaration, maven_exclude_dependency, maven_goto_declaration, + maven_managed_declarations, ); diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index deb5860a2..4461f767e 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -375,6 +375,7 @@ maven_dependency_completion trusted project_host bin maven_dependency_declaration trusted project_host bindings async maven_exclude_dependency trusted project_host bindings async maven_goto_declaration trusted project_host bindings async +maven_managed_declarations trusted project_host bindings async mcp_agent_run_closed trusted project_host bindings sync mcp_background_projects always project_host bindings sync mcp_regenerate_token outside_restricted project_host bindings sync diff --git a/src/bindings.ts b/src/bindings.ts index c73a8bdcf..4f3650f11 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -960,8 +960,9 @@ export const commands = { mavenExcludeDependency: (pom: string, dependency: ArtifactKey, exclusion: ArtifactKey) => typedError(__TAURI_INVOKE("maven_exclude_dependency", { pom, dependency, exclusion })), /** * The go-to-declaration target at `pos` of a Maven POM: the definition of the - * `${property}` at the caret, or the `` / `` - * entry providing the dependency's / plugin's version, along the parent chain. + * `${property}` at the caret, the parent POM, or the dependency / plugin's own POM + * (a project module first, then the local repository). A dependency without a + * resolvable artifact POM falls back to its management entry. */ mavenGotoDeclaration: (pom: string, pos: Pos) => typedError<{ /** @@ -975,6 +976,12 @@ export const commands = { /** The declaration as named for the user (`example.version`, `com.example:example-lib`). */ label: string, } | null, IdeError>(__TAURI_INVOKE("maven_goto_declaration", { pom, pos })), + /** + * Gutter targets of the unversioned dependencies and plugins in a Maven POM: + * the management declarations that actually supply their versions, including + * parent POMs and imported BOMs. Cancel with `cancel_request(request)`. + */ + mavenManagedDeclarations: (pom: string, request: RequestId) => typedError(__TAURI_INVOKE("maven_managed_declarations", { pom, request })), /** The user closed the Run tool window tab of an agent command (`run_command`). */ mcpAgentRunClosed: (name: string) => typedError(__TAURI_INVOKE("mcp_agent_run_closed", { name })), /** @@ -9753,6 +9760,16 @@ export type PomGotoKind = /** The POM of the artifact itself: a project module's, else the local repository's. */ "artifactPom"; +/** A dependency or plugin whose version comes from a management declaration. */ +export type PomManagedDeclaration = { + /** 0-based line of the `` or `` declaration. */ + line: number, + /** The interpolated version the management entry provides, when it has one. */ + version: string | null, + /** The management entry, possibly in a parent POM or an imported BOM. */ + target: PomGoto, +}; + /** A 0-based line / UTF-16 column position. */ export type Pos = { line: number, diff --git a/src/editor/api.ts b/src/editor/api.ts index bd0f102c6..a259f5586 100644 --- a/src/editor/api.ts +++ b/src/editor/api.ts @@ -490,7 +490,11 @@ export type ContributedFormatter = ( range: { from: number; to: number } | null, ) => Array<{ from: number; to: number; insert: string }>; /** Go to Declaration / ⌘-click: `true` when it handled `pos`. */ -export type ContributedDefinition = (view: EditorView, pos: number) => boolean; +export interface ContributedDefinition { + (view: EditorView, pos: number): boolean; + /** Cheap, side-effect-free eligibility for hover underline and navigation probing. */ + canHandle?(state: EditorState, pos: number): boolean; +} /** Hover and Quick Documentation: Markdown about the symbol at `pos`. */ export type ContributedHover = ( state: EditorState, @@ -501,6 +505,16 @@ export function contributedAt(state: EditorState, key: string, pos: number): return state.languageDataAt(key, pos)[0]; } +/** + * Every provider registered for a contributed language-data key at `pos`. A provider may + * be present for the document but decline this particular position (the MyBatis SQL + * provider on a Maven POM, for example), so callers that dispatch a request must not stop + * at the first entry when it returns "not handled". + */ +export function contributedAtAll(state: EditorState, key: string, pos: number): readonly T[] { + return state.languageDataAt(key, pos); +} + /** A context action a feature offers at the caret, listed by Show Context Actions (⌥↵). */ export interface ContributedIntention { id: string; diff --git a/src/editor/lsp/configurationNavigation.test.ts b/src/editor/lsp/configurationNavigation.test.ts index 55b37ce87..647ba454e 100644 --- a/src/editor/lsp/configurationNavigation.test.ts +++ b/src/editor/lsp/configurationNavigation.test.ts @@ -21,20 +21,36 @@ const target: Location = { range: { start: { line: 3, col: 4 }, end: { line: 3, col: 9 } }, }; const views: EditorView[] = []; -function editor(doc = 1, language = "yaml", text = "server:\n port: 8080\n") { +function editor(doc = 1, language = "yaml", text = "server:\n port: 8080\n", path = `/p/${doc}.${language}`) { const view = new EditorView({ state: EditorState.create({ doc: text, - extensions: [ - lspDoc.of({ doc, path: `/p/${doc}.${language}`, language, uiMode: language, readOnly: false }), - navigationExtension(), - ], + extensions: [lspDoc.of({ doc, path, language, uiMode: language, readOnly: false }), navigationExtension()], }), parent: document.body, }); views.push(view); return view; } + +it("uses the whole Maven element value for the navigation underline", () => { + const text = " cdf-parent\n ${revision}"; + const view = editor(1, "xml", text, "/p/pom.xml"); + const parent = text.indexOf("cdf-parent"); + for (const offset of [parent, parent + 3, parent + 4, parent + "cdf-parent".length]) { + const range = navigationWord(view, offset)!; + expect(view.state.sliceDoc(range.from, range.to)).toBe("cdf-parent"); + } + const revision = text.indexOf("${revision}"); + const range = navigationWord(view, revision + 4)!; + expect(view.state.sliceDoc(range.from, range.to)).toBe("${revision}"); + + const multiline = "\n cdf-parent\n "; + const multilineView = editor(2, "xml", multiline, "/p/multiline/pom.xml"); + const multilineRange = navigationWord(multilineView, multiline.indexOf("parent"))!; + expect(multilineView.state.sliceDoc(multilineRange.from, multilineRange.to)).toBe("cdf-parent"); +}); + let off: () => void; beforeEach(() => { vi.useFakeTimers(); diff --git a/src/editor/lsp/configurationNavigation.ts b/src/editor/lsp/configurationNavigation.ts index c7d795d46..e67fe9401 100644 --- a/src/editor/lsp/configurationNavigation.ts +++ b/src/editor/lsp/configurationNavigation.ts @@ -5,6 +5,7 @@ import type { Text } from "@codemirror/state"; import type { EditorView } from "@codemirror/view"; import { onEditorEvent } from "@/editor/api"; +import { isMavenPom } from "@/platform/buildFiles"; import { commands, IpcError, onIdeEvent, type GotoKind, type Location } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { onServerSettled } from "./availability"; @@ -54,9 +55,60 @@ export function isConfigurationDocument(view: EditorView): boolean { return language === "yaml" || language === "properties"; } -/** Configuration names include hyphens and dots even when the editor's - * language word rules split them. Share this range between decoration and lookup. */ +const XML_VALUE_SCAN_LINES = 256; + +/** The text of the XML element, trimmed to the value itself. */ +function pomElementValueAt(view: EditorView, offset: number): { from: number; to: number } | null { + const doc = view.state.doc; + const line = doc.lineAt(offset); + let open = -1; + const onLine = line.text.lastIndexOf(">", offset - line.from); + if (onLine >= 0) open = line.from + onLine; + else { + for (let number = line.number - 1; number >= 1 && line.number - number <= XML_VALUE_SCAN_LINES; number--) { + const previous = doc.line(number); + const col = previous.text.lastIndexOf(">"); + if (col >= 0) { + open = previous.from + col; + break; + } + } + } + if (open < 0 || offset <= open) return null; + + const afterOpen = doc.lineAt(Math.min(open + 1, doc.length)); + let close = -1; + for ( + let number = afterOpen.number; + number <= doc.lines && number - afterOpen.number <= XML_VALUE_SCAN_LINES; + number++ + ) { + const current = doc.line(number); + const col = current.text.indexOf("<", number === afterOpen.number ? open + 1 - current.from : 0); + if (col >= 0) { + close = current.from + col; + break; + } + } + if (close < 0 || offset > close) return null; + + let from = open + 1; + let to = close; + const raw = doc.sliceString(from, to); + from += raw.length - raw.trimStart().length; + to -= raw.length - raw.trimEnd().length; + return from < to ? { from, to } : null; +} + +/** Configuration names include hyphens and dots even when the editor's language word + * rules split them. Maven element values use the whole value (`cdf-parent`, not its + * hyphenated words). Share this range between decoration and lookup. */ export function navigationWord(view: EditorView, offset: number): { from: number; to: number } | null { + const doc = docOf(view); + if (doc && isMavenPom(doc.path)) { + const value = pomElementValueAt(view, offset); + if (value) return value; + } if (!isConfigurationDocument(view)) return view.state.wordAt(offset); const line = view.state.doc.lineAt(offset); const nameChar = /[\p{L}\p{N}_.$-]/u; diff --git a/src/editor/lsp/hover.ts b/src/editor/lsp/hover.ts index a84f29c57..6e4f9f94a 100644 --- a/src/editor/lsp/hover.ts +++ b/src/editor/lsp/hover.ts @@ -35,7 +35,7 @@ import { basename } from "@/platform/project"; import { iconNode } from "@/ui/iconNode"; import { applyCodeAction, quickFixesAt } from "./intentions"; import { editorPrefs } from "@/platform/editorSettings"; -import { CONTRIBUTED_HOVER, contributedAt, type ContributedHover } from "@/editor/api"; +import { CONTRIBUTED_HOVER, contributedAtAll, type ContributedHover } from "@/editor/api"; import { navigationModifierHeld, onNavigationModifier, pointerTarget } from "@/platform/navigationModifier"; import { languageSemantics } from "./semantic"; @@ -47,10 +47,9 @@ function constructAt(state: EditorView["state"], pos: number, language: string | } export async function requestHover(view: EditorView, pos: number): Promise { - const own = contributedAt(view.state, CONTRIBUTED_HOVER, pos); - if (own) { + for (const own of contributedAtAll(view.state, CONTRIBUTED_HOVER, pos)) { const h = own(view.state, pos); - if (!h) return null; + if (!h) continue; const range = { start: offsetToPos(view.state.doc, h.from), end: offsetToPos(view.state.doc, h.to) }; return { contents: { kind: "markdown", value: h.markdown }, range }; } diff --git a/src/editor/lsp/navigation.ts b/src/editor/lsp/navigation.ts index 18c9a9a51..11c783efe 100644 --- a/src/editor/lsp/navigation.ts +++ b/src/editor/lsp/navigation.ts @@ -46,8 +46,8 @@ import { } from "@/platform/ipc"; import { CONTRIBUTED_DEFINITION, + contributedAtAll, activeEditor, - contributedAt, whenSynced, type ContributedDefinition, type EditorDocContext, @@ -444,8 +444,12 @@ async function gotoResolved( done: () => void, ) { if (kind === "definition" || kind === "declaration") { - const own = contributedAt(view.state, CONTRIBUTED_DEFINITION, offset); - if (own?.(view, offset)) return; + // More than one feature can attach a definition provider to the same file (the + // MyBatis SQL support and the Maven POM navigator both see XML). Providers decline + // positions they do not own, so try every one instead of letting the first false + // result hide the real target. + const own = contributedAtAll(view.state, CONTRIBUTED_DEFINITION, offset); + if (own.some((definition) => definition(view, offset))) return; if (showPhpConstructDocumentation(view, offset)) return; const before = view.state.doc; const plugin = await contributedNavigation(view, offset).catch(() => null); @@ -873,7 +877,9 @@ async function probeNavigation( const plugin = await contributedNavigation(view, offset).catch(() => null); if (plugin) return { info: null, plugin }; const doc = docOf(view); - let navigable = !!contributedAt(view.state, CONTRIBUTED_DEFINITION, offset); + let navigable = contributedAtAll(view.state, CONTRIBUTED_DEFINITION, offset).some( + (definition) => definition.canHandle?.(view.state, offset) ?? true, + ); if (!navigable && doc) { const pos = offsetToPos(view.state.doc, offset); let fromSyntax = false; diff --git a/src/editor/lsp/navigationShared.test.ts b/src/editor/lsp/navigationShared.test.ts index 0f4f88bcb..b7bb3fbd6 100644 --- a/src/editor/lsp/navigationShared.test.ts +++ b/src/editor/lsp/navigationShared.test.ts @@ -1,6 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { EditorState } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; +import { + CONTRIBUTED_DEFINITION, + CONTRIBUTED_HOVER, + type ContributedDefinition, + type ContributedHover, +} from "@/editor/api"; import type { commands, Location } from "@/platform/ipc"; import { usePlatform } from "@/platform/platformInfo"; import { resetNavigationModifier } from "@/platform/navigationModifier"; @@ -18,7 +24,7 @@ vi.mock("@/platform/ipc", async (orig) => { const { gotoTargets, navigationExtension } = await import("./navigation"); const { lspDoc } = await import("./lsp"); -const { quickDefinition } = await import("./hover"); +const { quickDefinition, requestHover } = await import("./hover"); const { invalidateConfigurationNavigation } = await import("./configurationNavigation"); const { closePopup } = await import("./popupStore"); const { provideEditorService } = await import("@/workbench/contributions"); @@ -97,6 +103,49 @@ afterEach(() => { vi.restoreAllMocks(); }); +it("tries a later contributed definition when an earlier provider declines", async () => { + const declined = vi.fn(() => false); + const handled = vi.fn((_view, _pos) => { + openFile("/p/Handled.java", {}); + return true; + }); + view = new EditorView({ + state: EditorState.create({ + doc: "maven", + extensions: [ + EditorState.languageData.of(() => [{ [CONTRIBUTED_DEFINITION]: declined }]), + EditorState.languageData.of(() => [{ [CONTRIBUTED_DEFINITION]: handled }]), + ], + }), + parent: document.body, + }); + + await gotoTargets(view, "definition", 0); + expect(declined).toHaveBeenCalledOnce(); + expect(handled).toHaveBeenCalledOnce(); + expect(openFile).toHaveBeenCalledWith("/p/Handled.java", {}); + expect(lspGoto).not.toHaveBeenCalled(); +}); + +it("tries a later contributed hover when an earlier provider declines", async () => { + const declined = vi.fn(() => null); + const handled = vi.fn(() => ({ from: 1, to: 3, markdown: "handled" })); + view = new EditorView({ + state: EditorState.create({ + doc: "maven", + extensions: [ + EditorState.languageData.of(() => [{ [CONTRIBUTED_HOVER]: declined }]), + EditorState.languageData.of(() => [{ [CONTRIBUTED_HOVER]: handled }]), + ], + }), + parent: document.body, + }); + + expect((await requestHover(view, 1))?.contents.value).toBe("handled"); + expect(declined).toHaveBeenCalledOnce(); + expect(handled).toHaveBeenCalledOnce(); +}); + describe.each(cases)("shared definition requests in $language", (c) => { it("lets a click reuse the hover probe's request for the same word", async () => { editor(c); diff --git a/src/features/build-tools/PomNavigation.module.css b/src/features/build-tools/PomNavigation.module.css new file mode 100644 index 000000000..fa7870a96 --- /dev/null +++ b/src/features/build-tools/PomNavigation.module.css @@ -0,0 +1,18 @@ +/* IDEA's Navigate to Managing Dependency icon in the shared editor icon area. */ +.managedMarker { + width: 14px; + height: 14px; + display: flex; + align-items: center; + justify-content: center; + padding: 0; + border: 0; + border-radius: var(--radius-small); + background: transparent; + cursor: pointer; +} + +.managedMarker:hover, +.managedMarker:focus-visible { + background: var(--bg-hover); +} diff --git a/src/features/build-tools/pomNavigation.test.ts b/src/features/build-tools/pomNavigation.test.ts index 76b16570f..063d0c090 100644 --- a/src/features/build-tools/pomNavigation.test.ts +++ b/src/features/build-tools/pomNavigation.test.ts @@ -1,10 +1,19 @@ -import { describe, expect, it, vi } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { fireEvent } from "@testing-library/react"; -const ipc = vi.hoisted(() => ({ mavenGotoDeclaration: vi.fn() })); +const ipc = vi.hoisted(() => ({ + mavenGotoDeclaration: vi.fn(), + mavenManagedDeclarations: vi.fn(), + cancelRequest: vi.fn(), +})); const workbench = vi.hoisted(() => ({ openFile: vi.fn() })); const hints = vi.hoisted(() => ({ showHint: vi.fn() })); vi.mock("@/platform/ipc", () => ({ + isTauri: () => false, + isCancelled: () => false, + nextRequestId: () => 7, + onIdeEvent: () => () => {}, call: async (p: Promise<{ status: string; data?: unknown; error?: unknown }>) => { const r = await p; if (r.status !== "ok") throw r.error; @@ -16,15 +25,25 @@ vi.mock("@/workbench/contributions", () => ({ editorService: () => workbench, })); vi.mock("@/editor/lsp/hint", () => ({ showHint: hints.showHint })); -vi.mock("@/editor/api", () => ({ - CONTRIBUTED_DEFINITION: "openideaDefinition", +vi.mock("@/editor/api", async (importOriginal) => ({ + ...(await importOriginal()), whenSynced: () => Promise.resolve(), })); import { EditorState } from "@codemirror/state"; -import { inArtifactElement, pomNavigationExtension, propertyRefAt } from "./pomNavigation"; +import { EditorView } from "@codemirror/view"; +import { iconAreaExtension } from "@/editor/core/cm/iconArea"; +import type { ContributedDefinition } from "@/editor/api"; +import { inArtifactElement, placeManagedMarks, pomNavigationExtension, propertyRefAt } from "./pomNavigation"; const DEFINITION = "openideaDefinition"; +let view: EditorView | null = null; + +afterEach(() => { + view?.destroy(); + view = null; + vi.clearAllMocks(); +}); /** An editor state over `text` with the contribution for `path` installed. */ function state(text: string, path = "/p/app/pom.xml") { @@ -32,20 +51,22 @@ function state(text: string, path = "/p/app/pom.xml") { doc: text, extensions: [ pomNavigationExtension({ + doc: 1, path, language: "xml", uiMode: "XML", readOnly: false, } as Parameters[0]), + iconAreaExtension, ], }); } const definitionAt = (s: ReturnType, pos: number) => - s.languageDataAt<(v: { state: typeof s }, p: number) => boolean>(DEFINITION, pos)[0]; + s.languageDataAt(DEFINITION, pos)[0]; /** The definition only reads `view.state`; a bare handle is enough. */ -const run = (s: ReturnType, pos: number) => definitionAt(s, pos)!({ state: s }, pos); +const run = (s: ReturnType, pos: number) => definitionAt(s, pos)!({ state: s } as EditorView, pos); const pom = ` @@ -130,6 +151,13 @@ describe("POM go to declaration", () => { expect(definitionAt(s, pom.indexOf(""))).toBeUndefined(); }); + it("declines non-navigation POM positions without invoking the definition", () => { + const s = state(pom); + const definition = definitionAt(s, pom.indexOf("other-lib"))!; + expect(definition.canHandle?.(s, pom.indexOf("other-lib"))).toBe(true); + expect(definition.canHandle?.(s, pom.indexOf(""))).toBe(false); + }); + it("opens the declaration the backend resolved", async () => { const target = { path: "/p/pom.xml", @@ -152,6 +180,58 @@ describe("POM go to declaration", () => { }); }); + it("places one managed-dependency marker per backend line", () => { + const s = state(pom); + const target = { + path: "/p/pom.xml", + range: { start: { line: 1, col: 2 }, end: { line: 1, col: 8 } }, + kind: "managedDependency" as const, + label: "com.example:other-lib", + }; + expect( + placeManagedMarks(s.doc, [ + { line: 15, version: "1.2.3", target }, + { line: 15, version: "ignored", target }, + { line: 999, version: null, target }, + ]), + ).toEqual([{ pos: s.doc.line(16).from, link: { line: 15, version: "1.2.3", target } }]); + }); + + it("opens the managing declaration from its gutter icon", async () => { + const target = { + path: "/p/pom.xml", + range: { start: { line: 4, col: 6 }, end: { line: 4, col: 14 } }, + kind: "managedDependency" as const, + label: "com.example:other-lib", + }; + ipc.mavenManagedDeclarations.mockResolvedValue({ + status: "ok", + data: [ + { line: pom.slice(0, pom.indexOf("other-lib")).split("\n").length - 1, version: "1.0", target }, + ], + }); + view = new EditorView({ state: state(pom), parent: document.body }); + await vi.waitFor(() => expect(ipc.mavenManagedDeclarations).toHaveBeenCalledWith("/p/app/pom.xml", 7)); + await vi.waitFor(() => expect(view!.dom.querySelector("[data-managed-dependency]")).not.toBeNull()); + + fireEvent.click(view.dom.querySelector("[data-managed-dependency]")!); + await vi.waitFor(() => + expect(workbench.openFile).toHaveBeenCalledWith("/p/pom.xml", { + selection: { line: 4, col: 6, endLine: 4, endCol: 14 }, + }), + ); + }); + + it("cancels an in-flight gutter refresh when the document changes", async () => { + let finish!: (value: unknown) => void; + ipc.mavenManagedDeclarations.mockImplementation(() => new Promise((resolve) => (finish = resolve))); + view = new EditorView({ state: state(pom), parent: document.body }); + await vi.waitFor(() => expect(ipc.mavenManagedDeclarations).toHaveBeenCalledOnce()); + view.dispatch({ changes: { from: 0, insert: " " } }); + await vi.waitFor(() => expect(ipc.cancelRequest).toHaveBeenCalledWith(7)); + finish({ status: "ok", data: [] }); + }); + it("says so when nothing resolves, without navigating", async () => { ipc.mavenGotoDeclaration.mockResolvedValue({ status: "ok", data: null }); const s = state(pom); diff --git a/src/features/build-tools/pomNavigation.ts b/src/features/build-tools/pomNavigation.ts index d440a0b48..9385f224e 100644 --- a/src/features/build-tools/pomNavigation.ts +++ b/src/features/build-tools/pomNavigation.ts @@ -2,21 +2,41 @@ * Go to declaration in `pom.xml`: ⌘/Ctrl-click (or ⌘B) on a `${property}` reference * opens the `` entry that defines it — the POM's own, else one inherited * along the parent chain (a parent POM outside the project opens from the local - * repository, read-only as a plain file) — and a dependency / plugin whose version a - * `` / `` entry provides opens that managing - * declaration; otherwise a dependency, plugin or `` opens the artifact's own POM - * (a project module's, else the local repository's). The backend resolves both with the build model's POM reader and parent - * resolver; here only cheap eligibility is computed (a reference span, an artifact - * element), so the ⌘-hover underline stays out of the rest of the file, and nothing - * resolves to no jump at all: an unresolvable property or parent never navigates - * somewhere unrelated. + * repository, read-only as a plain file). A dependency, plugin or `` opens the + * artifact's own POM (a project module first, then the local repository). Unversioned + * declarations also get IDEA's "Navigate to managing dependency" gutter icon, which + * opens the exact `` / `` entry — including + * one in a parent POM or imported BOM — that controls the version. The backend does + * the resolution; here only cheap eligibility is computed, so the ⌘-hover underline + * stays out of the rest of the file and no marker promises a target that does not exist. */ -import { EditorState, type Extension } from "@codemirror/state"; -import { CONTRIBUTED_DEFINITION, type ContributedDefinition, type EditorDocContext, whenSynced } from "@/editor/api"; +import { EditorState, RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state"; +import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view"; +import { + CONTRIBUTED_DEFINITION, + iconAreaSource, + mapLineStart, + onEditorEvent, + whenSynced, + type ContributedDefinition, + type EditorDocContext, +} from "@/editor/api"; import { showHint } from "@/editor/lsp/hint"; +import { isMavenPom } from "@/platform/buildFiles"; import { tx } from "@/platform/i18n"; -import { call, commands } from "@/platform/ipc"; +import { + call, + commands, + isCancelled, + nextRequestId, + onIdeEvent, + type PomGoto, + type PomManagedDeclaration, + type RequestId, +} from "@/platform/ipc"; +import { gutterIconMarkup } from "@/ui"; import { editorService } from "@/workbench/contributions"; +import styles from "./PomNavigation.module.css"; /** The `${property}` reference covering `at`, if any (clicking the `$` counts). */ export function propertyRefAt(text: string, at: number): { from: number; to: number } | null { @@ -43,9 +63,193 @@ export function inArtifactElement(text: string, at: number): boolean { return inside("dependency", text, at) || inside("plugin", text, at) || inside("parent", text, at); } +export interface ManagedMark { + pos: number; + link: PomManagedDeclaration; +} + +/** Places the backend's 0-based lines in a document, one icon per declaration line. */ +export function placeManagedMarks(doc: Text, links: readonly PomManagedDeclaration[]): ManagedMark[] { + const seen = new Set(); + const out: ManagedMark[] = []; + for (const link of links) { + if (!Number.isInteger(link.line) || link.line < 0 || link.line >= doc.lines || seen.has(link.line)) continue; + seen.add(link.line); + out.push({ pos: doc.line(link.line + 1).from, link }); + } + return out; +} + +const setManagedMarks = StateEffect.define(); + +const managedMarksField = StateField.define({ + create: () => [], + update(value, tr) { + for (const effect of tr.effects) if (effect.is(setManagedMarks)) return effect.value; + if (!tr.docChanged || !value.length) return value; + return value.map((mark) => ({ ...mark, pos: mapLineStart(tr, mark.pos) })); + }, +}); + +const fileName = (path: string) => path.split(/[\\/]/).pop() || path; + +function managedTitle(link: PomManagedDeclaration): string { + const location = `${fileName(link.target.path)}:${link.target.range.start.line + 1}`; + return link.version ? tx`Managed version ${link.version} in ${location}` : tx`Managed in ${location}`; +} + +class ManagedMarker extends GutterMarker { + constructor( + readonly mark: ManagedMark, + readonly open: () => void, + ) { + super(); + } + + override eq(other: GutterMarker): boolean { + const a = this.mark.link; + const b = other instanceof ManagedMarker ? other.mark.link : null; + return ( + !!b && + a.version === b.version && + a.target.path === b.target.path && + a.target.range.start.line === b.target.range.start.line && + a.target.range.start.col === b.target.range.start.col + ); + } + + override toDOM(): Node { + const button = document.createElement("button"); + button.type = "button"; + button.className = styles.managedMarker ?? ""; + button.dataset.managedDependency = ""; + button.title = managedTitle(this.mark.link); + button.setAttribute("aria-label", button.title); + button.innerHTML = gutterIconMarkup("gutter-navigate") ?? ""; + // Keep the editor caret where it was; a normal click then runs the navigation, + // so the icon also works from the keyboard. + button.addEventListener("mousedown", (event) => { + event.preventDefault(); + event.stopPropagation(); + }); + button.addEventListener("click", (event) => { + event.preventDefault(); + event.stopPropagation(); + this.open(); + }); + return button; + } +} + +function openGoto(goto: PomGoto): Promise | void { + return editorService().openFile(goto.path, { + selection: { + line: goto.range.start.line, + col: goto.range.start.col, + endLine: goto.range.end.line, + endCol: goto.range.end.col, + }, + }); +} + +function openManaged(view: EditorView, target: PomGoto): void { + void Promise.resolve(openGoto(target)).catch((e: unknown) => + showHint(view, e instanceof Error ? e.message : String(e), { tone: "error" }), + ); +} + +/** The icon area is shared with run, inheritance and plugin markers; press handling is source-scoped. */ +function managedGutter(ctx: EditorDocContext): Extension { + if (ctx.doc < 0) return []; + return [ + managedMarksField, + ViewPlugin.fromClass( + class { + private timer: ReturnType | undefined; + private generation = 0; + private inFlight: RequestId | undefined; + private off: () => void; + + constructor(readonly view: EditorView) { + this.schedule(0); + const offEditor = onEditorEvent((event) => { + if ( + (event.type === "docChanged" || event.type === "docSaved") && + event.path !== ctx.path && + isMavenPom(event.path) + ) + this.schedule(500); + }); + const offFiles = onIdeEvent("fsChanged", (event) => { + if ([...event.created, ...event.modified, ...event.removed].some(isMavenPom)) this.schedule(500); + }); + const offRoots = onIdeEvent("projectRootsChanged", () => this.schedule(300)); + const offSettings = onIdeEvent("settingsChanged", (event) => { + if (event.key.startsWith("languages.java.")) this.schedule(300); + }); + this.off = () => { + offEditor(); + offFiles(); + offRoots(); + offSettings(); + }; + } + + update(update: ViewUpdate) { + if (update.docChanged) this.schedule(); + } + + schedule(delay = 300) { + clearTimeout(this.timer); + if (this.inFlight !== undefined) { + void commands.cancelRequest(this.inFlight); + this.inFlight = undefined; + } + this.timer = setTimeout(() => void this.refresh(), delay); + } + + async refresh() { + const generation = ++this.generation; + const current = this.view.state.doc; + const request = nextRequestId(); + this.inFlight = request; + try { + await whenSynced(this.view); + if (generation !== this.generation || this.view.state.doc !== current) return; + const links = await call(commands.mavenManagedDeclarations(ctx.path, request)); + if (generation !== this.generation || this.inFlight !== request || this.view.state.doc !== current) return; + this.view.dispatch({ effects: setManagedMarks.of(placeManagedMarks(current, links)) }); + } catch (e) { + if (!isCancelled(e) && generation === this.generation) console.debug("[POM managed dependencies]", e); + } finally { + if (this.inFlight === request) this.inFlight = undefined; + } + } + + destroy() { + this.off(); + clearTimeout(this.timer); + if (this.inFlight !== undefined) void commands.cancelRequest(this.inFlight); + this.generation++; + } + }, + ), + iconAreaSource.of({ + order: 25, + markers: (view) => + RangeSet.of( + view.state + .field(managedMarksField) + .map((mark) => new ManagedMarker(mark, () => openManaged(view, mark.link.target)).range(mark.pos)), + true, + ), + }), + ]; +} + /** Go to declaration in a POM of the project (or an opened parent POM of the local repository). */ export function pomNavigationExtension(ctx: EditorDocContext): Extension { - if (ctx.virtual || !/(^|\/)pom\.xml$/.test(ctx.path)) return []; + if (ctx.virtual || !isMavenPom(ctx.path)) return []; const eligible = (state: EditorState, pos: number) => { const text = state.doc.toString(); return propertyRefAt(text, pos) !== null || inArtifactElement(text, pos); @@ -69,14 +273,7 @@ export function pomNavigationExtension(ctx: EditorDocContext): Extension { return; } if (view.state.doc !== doc) return; // The user kept typing while the POM resolved. - void editorService().openFile(goto.path, { - selection: { - line: goto.range.start.line, - col: goto.range.start.col, - endLine: goto.range.end.line, - endCol: goto.range.end.col, - }, - }); + void openGoto(goto); }) .catch((e: unknown) => showHint(view, e instanceof Error ? e.message : String(e), { @@ -85,7 +282,11 @@ export function pomNavigationExtension(ctx: EditorDocContext): Extension { ); return true; }; - return EditorState.languageData.of((state, pos) => - eligible(state, pos) ? [{ [CONTRIBUTED_DEFINITION]: definition }] : [], - ); + definition.canHandle = eligible; + return [ + EditorState.languageData.of((state, pos) => + eligible(state, pos) ? [{ [CONTRIBUTED_DEFINITION]: definition }] : [], + ), + managedGutter(ctx), + ]; } diff --git a/src/features/database/sqlSupport.ts b/src/features/database/sqlSupport.ts index 120bbabec..81ee6fc19 100644 --- a/src/features/database/sqlSupport.ts +++ b/src/features/database/sqlSupport.ts @@ -108,7 +108,7 @@ function inspections(path: string, sql: SqlText): Extension { } function definition(path: string, sql: SqlText): ContributedDefinition { - return (view, pos) => { + const handle: ContributedDefinition = (view, pos) => { if (sql.at && !sql.at(view.state, pos)) return false; const r = resolver(path, view.state, sql).resolveAt(pos); const sym = r?.symbol; @@ -143,6 +143,9 @@ function definition(path: string, sql: SqlText): ContributedDefinition { return true; } }; + const at = sql.at; + if (at) handle.canHandle = (state, pos) => at(state, pos); + return handle; } const code = (s: string) => `\`${s.replace(/`/g, "")}\``; diff --git a/src/platform/buildFiles.ts b/src/platform/buildFiles.ts index 3929b71f9..0e316886c 100644 --- a/src/platform/buildFiles.ts +++ b/src/platform/buildFiles.ts @@ -4,3 +4,8 @@ export function isGradleBuildInput(path: string): boolean { path, ); } + +/** A project POM or a POM installed in the local Maven repository. */ +export function isMavenPom(path: string): boolean { + return /(^|[\\/])(?:pom\.xml|[^\\/]+\.pom)$/i.test(path); +} diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index c32dda360..534896dee 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2730,5 +2730,7 @@ "Caret": "Caret", "Code Structure": "Code Structure", "Presentation": "Presentation", - "Code Assistance": "Code Assistance" + "Code Assistance": "Code Assistance", + "Managed version {version} in {location}": "Managed version {version} in {location}", + "Managed in {location}": "Managed in {location}" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index cd63d8809..03b3ebfa8 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -9096,5 +9096,7 @@ "Remove All Watches": "移除所有监视", "GitHub account": "GitHub 账号", "Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "留空则使用 GitHub CLI 当前登录的账号。OpenIDEA 在启动时获取令牌,不会保存它。", - "github-username": "GitHub 用户名" + "github-username": "GitHub 用户名", + "Managed version {version} in {location}": "版本 {version} 由 {location} 管理", + "Managed in {location}": "由 {location} 管理" }