diff --git a/rewrite-maven/src/main/java/org/openrewrite/maven/tree/ResolvedPom.java b/rewrite-maven/src/main/java/org/openrewrite/maven/tree/ResolvedPom.java index 97c66d4502a..9af63ac08ea 100644 --- a/rewrite-maven/src/main/java/org/openrewrite/maven/tree/ResolvedPom.java +++ b/rewrite-maven/src/main/java/org/openrewrite/maven/tree/ResolvedPom.java @@ -825,9 +825,10 @@ public List resolveDependencies(Scope scope, Map dependenciesAtNextDepth = new ArrayList<>(); for (DependencyAndDependent dd : dependenciesAtDepth) { - //First get the dependency (relative to the pom it was defined in) - Dependency d = dd.getDefinedIn().getValues(dd.getDependency(), depth); - //The dependency may be modified by the current pom's managed dependencies + // First get the dependency (relative to the pom it was defined in) + // Depth 0 prevents its dependency management from overriding versions of its own direct dependencies + Dependency d = dd.getDefinedIn().getValues(dd.getDependency(), 0); + // The dependency may be modified by the current pom's dependency management d = getValues(d, depth); try { if (d.getVersion() == null) { diff --git a/rewrite-maven/src/test/java/org/openrewrite/maven/MavenParserTest.java b/rewrite-maven/src/test/java/org/openrewrite/maven/MavenParserTest.java index 7fda40e4ddf..3b287fbfd45 100644 --- a/rewrite-maven/src/test/java/org/openrewrite/maven/MavenParserTest.java +++ b/rewrite-maven/src/test/java/org/openrewrite/maven/MavenParserTest.java @@ -2936,4 +2936,76 @@ void escapedA() { ) ); } + + @Test + void transitiveDependencyManagement() { + rewriteRun( + mavenProject("depends-on-guava", + pomXml(""" + + 4.0.0 + org.example + depends-on-guava + 0.0.1 + + + com.google.guava + guava + 29.0-jre + + + + + + com.google.guava + guava + 30.0-jre + + + + + """, + spec -> spec.afterRecipe(pom -> { + //noinspection OptionalGetWithoutIsPresent + List guava = pom.getMarkers().findFirst(MavenResolutionResult.class) + .map(mrr -> mrr.findDependencies("com.google.guava", "guava", Scope.Compile)) + .get(); + + assertThat(guava) + .singleElement() + .as("Dependency management cannot override the version of a direct dependency") + .matches(it -> "29.0-jre".equals(it.getVersion())); + }) + )), + mavenProject("transitively-depends-on-guava", + pomXml(""" + + 4.0.0 + org.example + transitively-depends-on-guava + 0.0.1 + + + org.example + depends-on-guava + 0.0.1 + + + + """, + spec -> spec.afterRecipe(pom -> { + //noinspection OptionalGetWithoutIsPresent + List guava = pom.getMarkers().findFirst(MavenResolutionResult.class) + .map(mrr -> mrr.findDependencies("com.google.guava", "guava", Scope.Compile)) + .get(); + + assertThat(guava) + .singleElement() + .as("The dependency management of dependency does not override the versions of its own direct dependencies") + .matches(it -> "29.0-jre".equals(it.getVersion())); + }) + ) + ) + ); + } }