Skip to content

Commit 8b30eac

Browse files
committed
[GH-11772] Fail-fast consumer POM validation for non-4.0.0 model versions
When a POM-packaged project (parent POM) uses Maven 4.1.0 features like profile conditions that cannot be stripped during consumer POM transformation, the build now fails fast with actionable guidance instead of silently deploying a consumer POM that Maven 3 and Gradle cannot resolve. The validation applies only to: - POM-packaged projects (parent POMs) on the non-flatten path - Projects without preserve.model.version=true Also adds a maven.consumer.pom.removeUnusedManagedDependencies property (default: true) to control whether unused managed dependencies are removed during consumer POM flattening.
1 parent 9d675bb commit 8b30eac

8 files changed

Lines changed: 273 additions & 9 deletions

File tree

api/maven-api-core/src/main/java/org/apache/maven/api/Constants.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,21 @@ public final class Constants {
475475
@Config(type = "java.lang.Boolean", defaultValue = "false")
476476
public static final String MAVEN_CONSUMER_POM_FLATTEN = "maven.consumer.pom.flatten";
477477

478+
/**
479+
* User property for controlling removal of unused managed dependencies during consumer POM flattening.
480+
* When set to {@code true} (default), managed dependencies that do not appear in the resolved
481+
* dependency tree are removed from the consumer POM to keep it lean. This is important when using
482+
* BOMs like Spring Boot or Quarkus that contain hundreds of managed dependency entries.
483+
* When set to {@code false}, all managed dependencies are preserved in the consumer POM,
484+
* which may be needed in rare cases where downstream consumers override transitive dependency
485+
* versions and rely on the original managed dependencies for alignment.
486+
*
487+
* @since 4.1.0
488+
*/
489+
@Config(type = "java.lang.Boolean", defaultValue = "true")
490+
public static final String MAVEN_CONSUMER_POM_REMOVE_UNUSED_MANAGED_DEPENDENCIES =
491+
"maven.consumer.pom.removeUnusedManagedDependencies";
492+
478493
/**
479494
* User property for controlling "maven personality". If activated Maven will behave
480495
* like the previous major version, Maven 3.

api/maven-api-core/src/main/java/org/apache/maven/api/feature/Features.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,13 @@ public static boolean consumerPomFlatten(@Nullable Map<String, ?> userProperties
5454
return doGet(userProperties, Constants.MAVEN_CONSUMER_POM_FLATTEN, false);
5555
}
5656

57+
/**
58+
* Check if unused managed dependency removal is enabled during consumer POM flattening.
59+
*/
60+
public static boolean consumerPomRemoveUnusedManagedDependencies(@Nullable Map<String, ?> userProperties) {
61+
return doGet(userProperties, Constants.MAVEN_CONSUMER_POM_REMOVE_UNUSED_MANAGED_DEPENDENCIES, true);
62+
}
63+
5764
/**
5865
* Check if build POM deployment is enabled.
5966
*/

impl/maven-core/src/main/java/org/apache/maven/internal/transformation/impl/DefaultConsumerPomBuilder.java

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,30 @@ public Model build(RepositorySystemSession session, MavenProject project, ModelS
144144
if (isBom) {
145145
return buildBomWithoutFlatten(session, project, src);
146146
} else {
147-
return buildPom(session, project, src);
147+
Model result = buildPom(session, project, src);
148+
// Validate POM-packaged projects (parent POMs): if the consumer POM cannot be
149+
// downgraded to 4.0.0, Maven 3 / Gradle cannot resolve the parent.
150+
// Non-POM projects are consumed as dependencies where unknown elements are
151+
// ignored, so a higher model version is acceptable (only a warning is logged
152+
// by transformNonPom/transformPom).
153+
if (POM_PACKAGING.equals(packaging)
154+
&& !model.isPreserveModelVersion()
155+
&& !ModelBuilder.MODEL_VERSION_4_0_0.equals(result.getModelVersion())) {
156+
throw new MavenException("The consumer POM for " + project.getId()
157+
+ " cannot be downgraded to model version 4.0.0 because it contains"
158+
+ " features that require a newer model version."
159+
+ " Since consumer POM flattening is disabled, the parent reference is"
160+
+ " preserved, which requires consumers to resolve the parent POM." + System.lineSeparator()
161+
+ "You have the following options to resolve this:" + System.lineSeparator()
162+
+ " 1. Enable flattening by setting the property 'maven.consumer.pom.flatten=true'"
163+
+ " to inline parent content and produce a self-contained 4.0.0 consumer POM"
164+
+ System.lineSeparator()
165+
+ " 2. Preserve the model version by setting 'preserve.model.version=true'"
166+
+ " on the <project> element (Maven 4 consumers only)"
167+
+ System.lineSeparator()
168+
+ " 3. Remove the features that require a newer model version");
169+
}
170+
return result;
148171
}
149172
}
150173
// Default behavior: flatten the consumer POM
@@ -192,6 +215,8 @@ private Model buildEffectiveModel(RepositorySystemSession session, ModelSource s
192215
InternalSession iSession = InternalSession.from(session);
193216
ModelBuilderResult result = buildModel(session, src);
194217
Model model = result.getEffectiveModel();
218+
boolean removeUnusedManagedDeps =
219+
Features.consumerPomRemoveUnusedManagedDependencies(session.getConfigProperties());
195220

196221
if (model.getDependencyManagement() != null
197222
&& !model.getDependencyManagement().getDependencies().isEmpty()) {
@@ -210,20 +235,14 @@ private Model buildEffectiveModel(RepositorySystemSession session, ModelSource s
210235
this::merge,
211236
LinkedHashMap::new));
212237
Map<String, Dependency> managedDependencies = model.getDependencyManagement().getDependencies().stream()
213-
.filter(dependency ->
214-
nodes.containsKey(getDependencyKey(dependency)) && !"import".equals(dependency.getScope()))
238+
.filter(dependency -> !"import".equals(dependency.getScope())
239+
&& (!removeUnusedManagedDeps || nodes.containsKey(getDependencyKey(dependency))))
215240
.collect(Collectors.toMap(
216241
DefaultConsumerPomBuilder::getDependencyKey,
217242
Function.identity(),
218243
this::merge,
219244
LinkedHashMap::new));
220245

221-
// for each managed dep in the model:
222-
// * if there is no corresponding node in the tree, discard the managed dep
223-
// * if there's a direct dependency, apply the managed dependency to it and discard the managed dep
224-
// * else keep the managed dep
225-
managedDependencies.keySet().retainAll(nodes.keySet());
226-
227246
directDependencies.replaceAll((key, dependency) -> {
228247
var managedDependency = managedDependencies.get(key);
229248
if (managedDependency != null) {

impl/maven-core/src/test/java/org/apache/maven/internal/transformation/impl/ConsumerPomBuilderTest.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import org.apache.maven.api.model.Scm;
3535
import org.apache.maven.api.services.DependencyResolver;
3636
import org.apache.maven.api.services.DependencyResolverResult;
37+
import org.apache.maven.api.services.MavenException;
3738
import org.apache.maven.api.services.ModelBuilder;
3839
import org.apache.maven.api.services.ModelBuilderRequest;
3940
import org.apache.maven.api.services.Sources;
@@ -54,6 +55,7 @@
5455
import static org.junit.jupiter.api.Assertions.assertFalse;
5556
import static org.junit.jupiter.api.Assertions.assertNotNull;
5657
import static org.junit.jupiter.api.Assertions.assertNull;
58+
import static org.junit.jupiter.api.Assertions.assertThrows;
5759
import static org.junit.jupiter.api.Assertions.assertTrue;
5860

5961
public class ConsumerPomBuilderTest extends AbstractRepositoryTestCase {
@@ -181,6 +183,19 @@ void testMultiModuleConsumerPreserveModelVersion() throws Exception {
181183
assertFalse(transformed.getDependencyManagement().getDependencies().isEmpty());
182184
}
183185

186+
@Test
187+
void testParentWithConditionsFailsConsumerPom() throws Exception {
188+
setRootDirectory("parent-with-conditions");
189+
Path file = Paths.get("src/test/resources/consumer/parent-with-conditions/pom.xml");
190+
191+
MavenProject project = getEffectiveModel(file);
192+
// A parent POM with profile conditions cannot be downgraded to 4.0.0,
193+
// so building the consumer POM should fail with actionable guidance.
194+
MavenException ex =
195+
assertThrows(MavenException.class, () -> builder.build(session, project, Sources.buildSource(file)));
196+
assertTrue(ex.getMessage().contains("cannot be downgraded to model version 4.0.0"));
197+
}
198+
184199
@Test
185200
void testScmInheritance() throws Exception {
186201
Model model = Model.newBuilder()
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<project root="true" xmlns="http://maven.apache.org/POM/4.1.0">
2+
<groupId>org.my.group</groupId>
3+
<artifactId>parent</artifactId>
4+
<version>1.0-SNAPSHOT</version>
5+
<packaging>pom</packaging>
6+
7+
<dependencyManagement>
8+
<dependencies>
9+
<dependency>
10+
<groupId>org.slf4j</groupId>
11+
<artifactId>slf4j-api</artifactId>
12+
<version>2.0.9</version>
13+
</dependency>
14+
</dependencies>
15+
</dependencyManagement>
16+
17+
<profiles>
18+
<profile>
19+
<id>test-profile</id>
20+
<activation>
21+
<condition>${project.artifactId} == 'parent'</condition>
22+
</activation>
23+
<dependencies>
24+
<dependency>
25+
<groupId>org.slf4j</groupId>
26+
<artifactId>slf4j-api</artifactId>
27+
</dependency>
28+
</dependencies>
29+
</profile>
30+
</profiles>
31+
32+
</project>
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
package org.apache.maven.it;
20+
21+
import java.io.File;
22+
import java.io.Reader;
23+
import java.nio.file.Files;
24+
import java.nio.file.Path;
25+
26+
import org.apache.maven.api.model.Model;
27+
import org.apache.maven.model.v4.MavenStaxReader;
28+
import org.junit.jupiter.api.Test;
29+
30+
import static org.junit.jupiter.api.Assertions.assertEquals;
31+
import static org.junit.jupiter.api.Assertions.assertNotNull;
32+
import static org.junit.jupiter.api.Assertions.assertTrue;
33+
34+
/**
35+
* Integration test for <a href="https://github.com/apache/maven/issues/11772">GH-11772</a>.
36+
* <p>
37+
* Verifies that when a parent+child project uses model version 4.1.0 namespace
38+
* (with subprojects, root), the installed consumer POMs are model version 4.0.0,
39+
* while the build POMs retain the original 4.1.0 content.
40+
* <p>
41+
* This ensures backward compatibility with Maven 3 and Gradle for consumer POMs
42+
* while Maven 4 builds can resolve the full-fidelity build POM.
43+
*/
44+
class MavenITgh11772ConsumerPom410Test extends AbstractMavenIntegrationTestCase {
45+
46+
private static final String GROUP_ID = "org.apache.maven.its.gh11772";
47+
48+
@Test
49+
void testConsumerPomsAre400BuildPomsAre410() throws Exception {
50+
File basedir = extractResources("/gh-11772-consumer-pom-410");
51+
52+
Verifier verifier = newVerifier(basedir.getAbsolutePath());
53+
verifier.deleteArtifacts(GROUP_ID);
54+
verifier.addCliArguments("install");
55+
verifier.execute();
56+
verifier.verifyErrorFreeLog();
57+
58+
// Verify parent consumer POM (main artifact) is 4.0.0
59+
Path parentConsumerPom =
60+
Path.of(verifier.getArtifactPath(GROUP_ID, "parent", "1.0.0-SNAPSHOT", "pom"));
61+
assertTrue(Files.exists(parentConsumerPom), "Parent consumer POM should exist");
62+
Model parentConsumer = readModel(parentConsumerPom);
63+
assertEquals("4.0.0", parentConsumer.getModelVersion(), "Parent consumer POM should be 4.0.0");
64+
65+
// Verify parent build POM retains 4.1.0 features
66+
Path parentBuildPom =
67+
Path.of(verifier.getArtifactPath(GROUP_ID, "parent", "1.0.0-SNAPSHOT", "pom", "build"));
68+
assertTrue(Files.exists(parentBuildPom), "Parent build POM should exist");
69+
Model parentBuild = readModel(parentBuildPom);
70+
// Build POM should retain subprojects (4.1.0 feature)
71+
assertNotNull(parentBuild.getSubprojects(), "Build POM should retain subprojects");
72+
assertTrue(!parentBuild.getSubprojects().isEmpty(), "Build POM should retain subprojects");
73+
74+
// Verify child consumer POM is 4.0.0
75+
Path childConsumerPom =
76+
Path.of(verifier.getArtifactPath(GROUP_ID, "child", "1.0.0-SNAPSHOT", "pom"));
77+
assertTrue(Files.exists(childConsumerPom), "Child consumer POM should exist");
78+
Model childConsumer = readModel(childConsumerPom);
79+
assertEquals("4.0.0", childConsumer.getModelVersion(), "Child consumer POM should be 4.0.0");
80+
81+
// Child consumer POM should have a parent reference (not flattened by default)
82+
assertNotNull(childConsumer.getParent(), "Child consumer POM should have a parent reference");
83+
assertEquals(GROUP_ID, childConsumer.getParent().getGroupId());
84+
assertEquals("parent", childConsumer.getParent().getArtifactId());
85+
86+
// Verify child build POM exists
87+
Path childBuildPom =
88+
Path.of(verifier.getArtifactPath(GROUP_ID, "child", "1.0.0-SNAPSHOT", "pom", "build"));
89+
assertTrue(Files.exists(childBuildPom), "Child build POM should exist");
90+
}
91+
92+
private static Model readModel(Path pomFile) throws Exception {
93+
try (Reader r = Files.newBufferedReader(pomFile)) {
94+
return new MavenStaxReader().read(r);
95+
}
96+
}
97+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
Licensed to the Apache Software Foundation (ASF) under one
4+
or more contributor license agreements. See the NOTICE file
5+
distributed with this work for additional information
6+
regarding copyright ownership. The ASF licenses this file
7+
to you under the Apache License, Version 2.0 (the
8+
"License"); you may not use this file except in compliance
9+
with the License. You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing,
14+
software distributed under the License is distributed on an
15+
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16+
KIND, either express or implied. See the License for the
17+
specific language governing permissions and limitations
18+
under the License.
19+
-->
20+
<project xmlns="http://maven.apache.org/POM/4.1.0">
21+
22+
<parent>
23+
<groupId>org.apache.maven.its.gh11772</groupId>
24+
<artifactId>parent</artifactId>
25+
<version>1.0.0-SNAPSHOT</version>
26+
</parent>
27+
28+
<artifactId>child</artifactId>
29+
<packaging>pom</packaging>
30+
31+
<dependencies>
32+
<dependency>
33+
<groupId>org.slf4j</groupId>
34+
<artifactId>slf4j-api</artifactId>
35+
</dependency>
36+
</dependencies>
37+
38+
</project>
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
Licensed to the Apache Software Foundation (ASF) under one
4+
or more contributor license agreements. See the NOTICE file
5+
distributed with this work for additional information
6+
regarding copyright ownership. The ASF licenses this file
7+
to you under the Apache License, Version 2.0 (the
8+
"License"); you may not use this file except in compliance
9+
with the License. You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing,
14+
software distributed under the License is distributed on an
15+
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16+
KIND, either express or implied. See the License for the
17+
specific language governing permissions and limitations
18+
under the License.
19+
-->
20+
<project xmlns="http://maven.apache.org/POM/4.1.0" root="true">
21+
22+
<groupId>org.apache.maven.its.gh11772</groupId>
23+
<artifactId>parent</artifactId>
24+
<version>1.0.0-SNAPSHOT</version>
25+
<packaging>pom</packaging>
26+
27+
<subprojects>
28+
<subproject>child</subproject>
29+
</subprojects>
30+
31+
<dependencyManagement>
32+
<dependencies>
33+
<dependency>
34+
<groupId>org.slf4j</groupId>
35+
<artifactId>slf4j-api</artifactId>
36+
<version>2.0.9</version>
37+
</dependency>
38+
</dependencies>
39+
</dependencyManagement>
40+
41+
</project>

0 commit comments

Comments
 (0)