diff --git a/crates/ide-build/src/application_update.rs b/crates/ide-build/src/application_update.rs index 632cc4454..208c280d7 100644 --- a/crates/ide-build/src/application_update.rs +++ b/crates/ide-build/src/application_update.rs @@ -26,9 +26,10 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide let module = dunce::canonicalize(root.join(module))?; if let Some(p) = model.maven.as_ref().and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module)) { let mut args = p.options.clone(); + let repo = crate::maven::local_repository_for(&p.options); args.extend([ "process-resources".into(), - "help:evaluate".into(), + crate::maven::plugin_goal("help:evaluate", repo.as_deref()), "-Dexpression=project.build.outputDirectory".into(), format!("-Doutput={}", manifest.display()), ]); diff --git a/crates/ide-build/src/compile/single.rs b/crates/ide-build/src/compile/single.rs index 8bd7c5f63..454df082d 100644 --- a/crates/ide-build/src/compile/single.rs +++ b/crates/ide-build/src/compile/single.rs @@ -361,7 +361,9 @@ fn classpaths( if compile_first { args.push("compile"); } - args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]); + let build_classpath = + maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref()); + args.extend([build_classpath.as_str(), output_arg.as_str(), scope_arg.as_str(), "-q"]); let top_dir = subdir(root, &top.dir); let owned_args: Vec = args.into_iter().map(str::to_owned).collect(); let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| { diff --git a/crates/ide-build/src/maven.rs b/crates/ide-build/src/maven.rs index 64351963f..4e1f809c1 100644 --- a/crates/ide-build/src/maven.rs +++ b/crates/ide-build/src/maven.rs @@ -517,6 +517,59 @@ pub fn local_repository_of(settings: &Path) -> Option { Some(PathBuf::from(repo.replace("${user.home}", &home))) } +/// The local repository a Maven run with these options resolves into: `-Dmaven.repo.local=` +/// first, then `` of the `-s` settings, then the user's default. +pub fn local_repository_for(options: &[String]) -> Option { + if let Some(repo) = options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")) { + return Some(PathBuf::from(repo)); + } + let mut args = options.iter(); + while let Some(arg) = args.next() { + let path = match arg.as_str() { + "-s" | "--settings" => args.next().map(String::as_str), + _ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")), + }; + if let Some(path) = path { + return local_repository_of(Path::new(path)).or_else(default_local_repo); + } + } + default_local_repo() +} + +/// A goal of the IDE's own (`help:evaluate`, `dependency:build-classpath`, …) by its plugin's +/// coordinates rather than its prefix: offline, Maven resolves a prefix only from group metadata +/// in the local repository, which a repository filled from a private mirror often lacks even when +/// the plugin itself is there. Uses the newest 3.x version already in `repo`, so nothing is +/// downloaded, else a pinned one. +pub fn plugin_goal(goal: &str, repo: Option<&Path>) -> String { + let (prefix, goal) = goal.split_once(':').expect("prefix:goal"); + let (artifact, pinned) = match prefix { + "help" => ("maven-help-plugin", "3.5.1"), + "dependency" => ("maven-dependency-plugin", "3.8.1"), + _ => unreachable!("not a goal of the IDE's own: {prefix}"), + }; + let version = repo.and_then(|repo| newest_local_plugin(repo, artifact, 3)).unwrap_or_else(|| pinned.to_owned()); + format!("org.apache.maven.plugins:{artifact}:{version}:{goal}") +} + +/// The newest release of `org.apache.maven.plugins:` whose jar is in `repo`, +/// from major version `min_major` up. +pub(crate) fn newest_local_plugin(repo: &Path, artifact: &str, min_major: u64) -> Option { + let dir = repo.join("org/apache/maven/plugins").join(artifact); + let parse = |v: &str| v.split('.').map(|n| n.parse::().ok()).collect::>>(); + std::fs::read_dir(&dir) + .ok()? + .flatten() + .filter_map(|e| e.file_name().into_string().ok()) + .filter_map(|v| parse(&v).map(|n| (n, v))) + .filter(|(n, v)| { + n.first().is_some_and(|&major| major >= min_major) + && dir.join(v).join(format!("{artifact}-{v}.jar")).is_file() + }) + .max() + .map(|(_, v)| v) +} + impl Resolver { fn new(local_repo: Option, profiles: &[String]) -> Self { Self::new_with_jdk(local_repo, profiles, None) @@ -2557,6 +2610,24 @@ mod tests { assert!(local_repository_of(&tmp.path().join("missing.xml")).is_none()); } + #[test] + fn ide_goals_resolve_from_the_repository_the_run_uses() { + let tmp = tempfile::tempdir().unwrap(); + let settings = tmp.path().join("settings.xml"); + std::fs::write(&settings, "/srv/m2").unwrap(); + let s = settings.to_string_lossy().into_owned(); + let opts = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::>(); + assert_eq!(local_repository_for(&opts(&["-s", &s])), Some(PathBuf::from("/srv/m2"))); + assert_eq!(local_repository_for(&opts(&[&format!("--settings={s}")])), Some(PathBuf::from("/srv/m2"))); + let explicit = opts(&["-s", &s, "-Dmaven.repo.local=/tmp/r"]); + assert_eq!(local_repository_for(&explicit), Some(PathBuf::from("/tmp/r"))); + // No repository known: a pinned version, still by coordinates. + assert_eq!( + plugin_goal("dependency:build-classpath", None), + "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:build-classpath" + ); + } + #[test] fn effective_pom_goals_come_from_the_local_repository_it_is_given() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-build/src/sync.rs b/crates/ide-build/src/sync.rs index 27a48dd04..f45a7d9d1 100644 --- a/crates/ide-build/src/sync.rs +++ b/crates/ide-build/src/sync.rs @@ -86,20 +86,29 @@ const MAVEN_CACHE_VERSION: u32 = 1; /// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven /// omitted (conflicts, duplicates): verbose output was dropped in 3.0 and is back since 3.2. -/// Offline, it is used only when an earlier sync downloaded it; otherwise the project's own -/// plugin version is, which may be cached instead. +/// Offline, it is used only when an earlier sync downloaded it; otherwise the newest version +/// in the local repository is. const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree"; const DEPENDENCY_TREE_JAR: &str = "org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar"; /// The goals that read the effective POM into `effective` and the verbose dependency trees; -/// `repo` is the local repository the build resolves from. +/// `repo` is the local repository the build resolves from. Both goals name their plugin by +/// coordinates: offline, a prefix resolves only from group metadata the repository may lack. fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec { let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file()); + let tree = if pinned { + DEPENDENCY_TREE.to_owned() + } else { + repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2)).map_or_else( + || "dependency:tree".to_owned(), + |v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"), + ) + }; vec![ - "help:effective-pom".into(), + maven::plugin_goal("help:effective-pom", repo), format!("-Doutput={}", effective.to_string_lossy()), - if pinned { DEPENDENCY_TREE.into() } else { "dependency:tree".into() }, + tree, "-Dverbose".into(), ] } @@ -367,25 +376,8 @@ pub fn sync_maven( verbose: true, ..MavenCache::default() }; - // Where the build resolves its jars, and therefore where the plugin goals are read - // from: `-Dmaven.repo.local=` first, then `` of the `-s` settings, - // then the user's default repository (which `plugin()` resolves itself). - let local_repo: Option = - options.maven_options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")).map(PathBuf::from).or_else( - || { - let mut args = options.maven_options.iter(); - while let Some(arg) = args.next() { - let path = match arg.as_str() { - "-s" | "--settings" => args.next().map(String::as_str), - _ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")), - }; - if let Some(path) = path { - return maven::local_repository_of(Path::new(path)); - } - } - None - }, - ); + // Where the build resolves its jars, and therefore where the plugin goals are read from. + let repo = maven::local_repository_for(&options.maven_options); let mut errors: Vec = Vec::new(); for (n, top) in model.projects.iter().filter(|p| !p.aggregated).enumerate() { let effective = cache_dir.join(format!("effective-pom-{n}.xml")); @@ -407,7 +399,6 @@ pub fn sync_maven( if !options.profiles.is_empty() { args.push(format!("-P{}", options.profiles.join(","))); } - let repo = local_repo.clone().or_else(maven::default_local_repo); args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref())); progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None }); let command = options.maven_command.as_deref().unwrap_or(&top.command); @@ -425,7 +416,7 @@ pub fn sync_maven( } })?; let effective_projects = std::fs::read_to_string(&effective) - .map(|t| maven::parse_effective_pom_in(&t, local_repo.as_deref())) + .map(|t| maven::parse_effective_pom_in(&t, repo.as_deref())) .unwrap_or_default(); let trees = maven::parse_dependency_tree(&out.text); for (key, plugins, deps) in effective_projects { @@ -953,11 +944,27 @@ mod tests { #[test] fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline_without_it() { let tmp = tempfile::tempdir().unwrap(); - let online = maven_sync_goals(Path::new("e.xml"), false, None); - assert_eq!(online, ["help:effective-pom", "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]); + let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom"; + let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path())); + assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]); + // Offline with neither plugin cached: the tree falls back to the project's own version. let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path())); - assert_eq!(offline[2], "dependency:tree"); - assert!(offline.contains(&"-Dverbose".to_owned())); + assert_eq!(offline, [help, "-Doutput=e.xml", "dependency:tree", "-Dverbose"]); + // #5757: offline, plugins in the local repository are named by their coordinates, since + // the prefix needs group metadata a repository filled from a private mirror may lack. + for (artifact, version) in + [("maven-help-plugin", "3.4.0"), ("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")] + { + let jar = + tmp.path().join(format!("org/apache/maven/plugins/{artifact}/{version}/{artifact}-{version}.jar")); + std::fs::create_dir_all(jar.parent().unwrap()).unwrap(); + std::fs::write(&jar, "").unwrap(); + } + // A version folder without its jar (only the POM was fetched) doesn't count. + std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap(); + let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path())); + assert_eq!(offline[0], "org.apache.maven.plugins:maven-help-plugin:3.4.0:effective-pom"); + assert_eq!(offline[2], "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree"); // Downloaded by an online sync: offline keeps using it, the project's version may be missing. let jar = tmp.path().join(DEPENDENCY_TREE_JAR); std::fs::create_dir_all(jar.parent().unwrap()).unwrap(); @@ -1029,7 +1036,7 @@ mod tests { let cache = tmp.path().join("cache"); sync_maven(&root, &cache, &SyncOptions::default(), &CancellationToken::new(), &|_| {}).unwrap(); let args = std::fs::read_to_string(root.join("mvnw-args")).unwrap(); - assert!(args.contains("help:effective-pom"), "args: {args}"); + assert!(args.contains("maven-help-plugin:"), "args: {args}"); let loaded = crate::load_linked(&root, &cache, None, &Default::default(), &Default::default()); let maven = loaded.maven.unwrap(); assert!(maven.synced_at.is_some() && maven.sync_error.is_none(), "{:?}", maven.sync_error); @@ -1054,6 +1061,6 @@ mod tests { let args = std::fs::read_to_string(root.join("mvnd-args")).unwrap(); // `-T1` pins the daemon serial so the dependency trees stay parseable. assert!(args.contains("-T1"), "args: {args}"); - assert!(args.contains("help:effective-pom"), "args: {args}"); + assert!(args.contains("maven-help-plugin:"), "args: {args}"); } } diff --git a/crates/ide-build/src/web.rs b/crates/ide-build/src/web.rs index dc0a3dfe8..dd2a29f83 100644 --- a/crates/ide-build/src/web.rs +++ b/crates/ide-build/src/web.rs @@ -137,19 +137,16 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu // POM's effective identity first; profiles and -D options can change its GAV. let output = cache.join("artifact-project.txt"); let mut probe = top.options.clone(); + let evaluate = + crate::maven::plugin_goal("help:evaluate", crate::maven::local_repository_for(&top.options).as_deref()); probe.extend([ "-f".into(), root.join(&p.pom).to_string_lossy().into_owned(), - "help:evaluate".into(), + evaluate.clone(), "-Dexpression=project.id".into(), format!("-Doutput={}", output.display()), ]); - args.extend([ - "-DskipTests".into(), - "package".into(), - "help:evaluate".into(), - format!("-Doutput={}", manifest.display()), - ]); + args.extend(["-DskipTests".into(), "package".into(), evaluate, format!("-Doutput={}", manifest.display())]); return Ok(WebBuild { command: top.command.clone(), args, diff --git a/crates/ide-host/tests/workspaces.rs b/crates/ide-host/tests/workspaces.rs index 6bdf91c97..4cd7e0c09 100644 --- a/crates/ide-host/tests/workspaces.rs +++ b/crates/ide-host/tests/workspaces.rs @@ -112,7 +112,7 @@ done let calls = fs::read_to_string(root.join("calls")).unwrap(); assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}"); assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}"); - assert!(calls.contains("dependency:build-classpath"), "{calls}"); + assert!(calls.contains(":build-classpath"), "{calls}"); } }