You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by gn...@apache.org on 2026/08/28 13:25:44 UTC

(maven) branch master updated: Wire ModelBuilderRequest.isLocationTracking() to XML parser (#12655)

This is an automated email from the ASF dual-hosted git repository.

gnodet pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven.git


The following commit(s) were added to refs/heads/master by this push:
     new 4554df07f4 Wire ModelBuilderRequest.isLocationTracking() to XML parser (#12655)
4554df07f4 is described below

commit 4554df07f44da403f5cf23e85a190e8391e1ef3e
Author: Guillaume Nodet <gn...@gmail.com>
AuthorDate: Fri Aug 28 15:25:38 2026 +0200

    Wire ModelBuilderRequest.isLocationTracking() to XML parser (#12655)
    
    * Wire ModelBuilderRequest.isLocationTracking() to XML parser
    
    Add isAddLocationInformation() to XmlReaderRequest and wire it to
    MavenStaxReader so callers can skip location tracking when not needed.
    DefaultModelBuilder propagates the flag from ModelBuilderRequest to the
    XML parser, and forwards the parent's setting to BOM import sub-requests
    instead of hardcoding it off.
    
    Co-Authored-By: Claude Opus 4.6 <no...@anthropic.com>
    
    * Remove premature wiring of isLocationTracking() to XML parser
    
    Do not pass ModelBuilderRequest.isLocationTracking() as the
    addLocationInformation flag for XmlReaderRequest.  These are
    different concerns:
    
    - isLocationTracking() controls whether the model building pipeline
      retains location data (used by DefaultDependencyManagementImporter
      and DefaultProjectBuilder)
    - isAddLocationInformation() controls whether the XML parser tracks
      line/column positions during parsing
    
    Wiring one to the other broke hasSubprojectsDefined(), which relies on
    model.getLocation("modules") to detect <modules> presence.  When
    DefaultConsumerPomBuilder sets locationTracking(false) for consumer POM
    generation, the XML parser skipped location tracking, causing spurious
    auto-discovery of subprojects alongside explicit <modules> entries.
    
    The XmlReaderRequest API + DefaultModelXmlFactory wiring remain as
    correct infrastructure for future selective optimization by callers
    who know they don't need XML-level locations.
    
    Co-Authored-By: Claude Opus 4.6 <no...@anthropic.com>
    
    * Add maven.project.discoverSubprojects property to replace location-based opt-out
    
    Replace the fragile location-tracking-based detection of empty <modules/>
    elements with a simple non-empty list check, and add a new user property
    (maven.project.discoverSubprojects) as the explicit opt-out mechanism for
    subproject auto-discovery.
    
    The previous approach relied on model.getLocation("modules") != null to
    distinguish "no <modules> element" from "empty <modules/> element", which
    broke whenever location tracking was disabled (e.g. by
    DefaultConsumerPomBuilder). The new approach:
    
    - hasSubprojectsDefined() now checks !getSubprojects().isEmpty() ||
      !getModules().isEmpty()
    - Users who want to suppress auto-discovery without listing subprojects
      can set -Dmaven.project.discoverSubprojects=false
    - ModelBuilderRequest.locationTracking default reverted to false since
      subproject detection no longer depends on it
    
    Co-Authored-By: Claude Opus 4.6 <no...@anthropic.com>
    
    ---------
    
    Co-authored-by: Claude Opus 4.6 <no...@anthropic.com>
---
 .../main/java/org/apache/maven/api/Constants.java  | 13 ++++++++
 .../org/apache/maven/api/feature/Features.java     |  7 +++++
 .../maven/api/services/xml/XmlReaderRequest.java   | 33 ++++++++++++++++++--
 .../project/DefaultMavenProjectBuilderTest.java    | 35 +++++++++++++++-------
 .../apache/maven/impl/DefaultModelXmlFactory.java  |  1 +
 .../maven/impl/model/DefaultModelBuilder.java      | 19 ++++++------
 6 files changed, 86 insertions(+), 22 deletions(-)

diff --git a/api/maven-api-core/src/main/java/org/apache/maven/api/Constants.java b/api/maven-api-core/src/main/java/org/apache/maven/api/Constants.java
index 7d01a7c1a7..7ed3befffa 100644
--- a/api/maven-api-core/src/main/java/org/apache/maven/api/Constants.java
+++ b/api/maven-api-core/src/main/java/org/apache/maven/api/Constants.java
@@ -489,6 +489,19 @@ public final class Constants {
     @Config
     public static final String MAVEN_PLUGIN_VALIDATION_EXCLUDES = "maven.plugin.validation.excludes";
 
+    /**
+     * User property for enabling/disabling automatic subproject discovery for POM-packaged projects.
+     * When set to {@code true} (default), Maven 4.1+ POM-packaged projects that do not declare
+     * {@code <subprojects>} or {@code <modules>} will automatically discover subprojects
+     * by scanning subdirectories for POM files.
+     * When set to {@code false}, automatic discovery is disabled regardless of whether
+     * {@code <subprojects>} or {@code <modules>} is declared.
+     *
+     * @since 4.1.0
+     */
+    @Config(type = "java.lang.Boolean", defaultValue = "true")
+    public static final String MAVEN_PROJECT_DISCOVER_SUBPROJECTS = "maven.project.discoverSubprojects";
+
     /**
      * ProjectBuilder parallelism.
      *
diff --git a/api/maven-api-core/src/main/java/org/apache/maven/api/feature/Features.java b/api/maven-api-core/src/main/java/org/apache/maven/api/feature/Features.java
index 12f044f607..45c56d9c1d 100644
--- a/api/maven-api-core/src/main/java/org/apache/maven/api/feature/Features.java
+++ b/api/maven-api-core/src/main/java/org/apache/maven/api/feature/Features.java
@@ -61,6 +61,13 @@ public static boolean consumerPomRemoveUnusedManagedDependencies(@Nullable Map<S
         return doGet(userProperties, Constants.MAVEN_CONSUMER_POM_REMOVE_UNUSED_MANAGED_DEPENDENCIES, true);
     }
 
+    /**
+     * Check if automatic subproject discovery is enabled for POM-packaged projects.
+     */
+    public static boolean discoverSubprojects(@Nullable Map<String, ?> userProperties) {
+        return doGet(userProperties, Constants.MAVEN_PROJECT_DISCOVER_SUBPROJECTS, true);
+    }
+
     /**
      * Check if build POM deployment is enabled.
      */
diff --git a/api/maven-api-core/src/main/java/org/apache/maven/api/services/xml/XmlReaderRequest.java b/api/maven-api-core/src/main/java/org/apache/maven/api/services/xml/XmlReaderRequest.java
index 41733eb08b..07fd999b9f 100644
--- a/api/maven-api-core/src/main/java/org/apache/maven/api/services/xml/XmlReaderRequest.java
+++ b/api/maven-api-core/src/main/java/org/apache/maven/api/services/xml/XmlReaderRequest.java
@@ -66,6 +66,20 @@ public interface XmlReaderRequest {
 
     boolean isAddDefaultEntities();
 
+    /**
+     * Indicates whether location information (line/column tracking) should be
+     * recorded during parsing. Defaults to {@code true}. Setting this to
+     * {@code false} for imported dependency management POMs avoids allocating
+     * location maps that are never read, significantly reducing memory churn
+     * in large reactors.
+     *
+     * @return {@code true} if location information should be tracked
+     * @since 4.0.0
+     */
+    default boolean isAddLocationInformation() {
+        return true;
+    }
+
     interface Transformer {
         /**
          * Interpolate the value read from the xml document
@@ -95,6 +109,7 @@ class XmlReaderRequestBuilder {
         String modelId;
         String location;
         boolean addDefaultEntities = true;
+        boolean addLocationInformation = true;
 
         public XmlReaderRequestBuilder path(Path path) {
             this.path = path;
@@ -146,6 +161,11 @@ public XmlReaderRequestBuilder addDefaultEntities(boolean addDefaultEntities) {
             return this;
         }
 
+        public XmlReaderRequestBuilder addLocationInformation(boolean addLocationInformation) {
+            this.addLocationInformation = addLocationInformation;
+            return this;
+        }
+
         public XmlReaderRequest build() {
             return new DefaultXmlReaderRequest(
                     path,
@@ -157,7 +177,8 @@ public XmlReaderRequest build() {
                     strict,
                     modelId,
                     location,
-                    addDefaultEntities);
+                    addDefaultEntities,
+                    addLocationInformation);
         }
 
         private static class DefaultXmlReaderRequest implements XmlReaderRequest {
@@ -171,6 +192,7 @@ private static class DefaultXmlReaderRequest implements XmlReaderRequest {
             final String modelId;
             final String location;
             final boolean addDefaultEntities;
+            final boolean addLocationInformation;
 
             @SuppressWarnings("checkstyle:ParameterNumber")
             DefaultXmlReaderRequest(
@@ -183,7 +205,8 @@ private static class DefaultXmlReaderRequest implements XmlReaderRequest {
                     boolean strict,
                     String modelId,
                     String location,
-                    boolean addDefaultEntities) {
+                    boolean addDefaultEntities,
+                    boolean addLocationInformation) {
                 this.path = path;
                 this.rootDirectory = rootDirectory;
                 this.url = url;
@@ -194,6 +217,7 @@ private static class DefaultXmlReaderRequest implements XmlReaderRequest {
                 this.modelId = modelId;
                 this.location = location;
                 this.addDefaultEntities = addDefaultEntities;
+                this.addLocationInformation = addLocationInformation;
             }
 
             @Override
@@ -245,6 +269,11 @@ public String getLocation() {
             public boolean isAddDefaultEntities() {
                 return addDefaultEntities;
             }
+
+            @Override
+            public boolean isAddLocationInformation() {
+                return addLocationInformation;
+            }
         }
     }
 }
diff --git a/impl/maven-core/src/test/java/org/apache/maven/project/DefaultMavenProjectBuilderTest.java b/impl/maven-core/src/test/java/org/apache/maven/project/DefaultMavenProjectBuilderTest.java
index 4cffff903f..81919c28e7 100644
--- a/impl/maven-core/src/test/java/org/apache/maven/project/DefaultMavenProjectBuilderTest.java
+++ b/impl/maven-core/src/test/java/org/apache/maven/project/DefaultMavenProjectBuilderTest.java
@@ -29,6 +29,7 @@
 
 import com.google.common.jimfs.Configuration;
 import com.google.common.jimfs.Jimfs;
+import org.apache.maven.api.Constants;
 import org.apache.maven.api.model.InputLocation;
 import org.apache.maven.api.model.InputSource;
 import org.apache.maven.api.services.ModelSource;
@@ -662,7 +663,7 @@ public void testSubprojectDiscovery() throws Exception {
     }
 
     @Test
-    public void testEmptySubprojectsElementPreventsDiscovery() throws Exception {
+    public void testEmptySubprojectsElementDoesNotPreventDiscovery() throws Exception {
         File pom = getTestFile("src/test/resources/projects/subprojects-empty/pom.xml");
         ProjectBuildingRequest configuration = newBuildingRequest();
         InternalSession internalSession = InternalSession.from(configuration.getRepositorySession());
@@ -673,16 +674,12 @@ public void testEmptySubprojectsElementPreventsDiscovery() throws Exception {
                 .setRootDirectory(pom.toPath().getParent());
 
         List<ProjectBuildingResult> results = projectBuilder.build(List.of(pom), true, configuration);
-        // Should only build the parent project, not discover the child
-        assertEquals(1, results.size());
-        MavenProject parent = results.get(0).getProject();
-        assertEquals("parent", parent.getArtifactId());
-        // The subprojects list should be empty since we explicitly defined an empty <subprojects /> element
-        assertTrue(parent.getModel().getDelegate().getSubprojects().isEmpty());
+        // Empty <subprojects /> no longer prevents discovery; use the property to opt out
+        assertEquals(2, results.size());
     }
 
     @Test
-    public void testEmptyModulesElementPreventsDiscovery() throws Exception {
+    public void testEmptyModulesElementDoesNotPreventDiscovery() throws Exception {
         File pom = getTestFile("src/test/resources/projects/modules-empty/pom.xml");
         ProjectBuildingRequest configuration = newBuildingRequest();
         InternalSession internalSession = InternalSession.from(configuration.getRepositorySession());
@@ -693,12 +690,28 @@ public void testEmptyModulesElementPreventsDiscovery() throws Exception {
                 .setRootDirectory(pom.toPath().getParent());
 
         List<ProjectBuildingResult> results = projectBuilder.build(List.of(pom), true, configuration);
-        // Should only build the parent project, not discover the child
+        // Empty <modules /> no longer prevents discovery; use the property to opt out
+        assertEquals(2, results.size());
+    }
+
+    @Test
+    public void testDiscoverSubprojectsPropertyDisablesDiscovery() throws Exception {
+        File pom = getTestFile("src/test/resources/projects/subprojects-empty/pom.xml");
+        ProjectBuildingRequest configuration = newBuildingRequest();
+        InternalSession internalSession = InternalSession.from(configuration.getRepositorySession());
+        InternalMavenSession mavenSession = InternalMavenSession.from(internalSession);
+        mavenSession
+                .getMavenSession()
+                .getRequest()
+                .setRootDirectory(pom.toPath().getParent());
+        mavenSession.getMavenSession().getUserProperties().put(Constants.MAVEN_PROJECT_DISCOVER_SUBPROJECTS, "false");
+
+        List<ProjectBuildingResult> results = projectBuilder.build(List.of(pom), true, configuration);
+        // Discovery disabled via property: only the parent project should be built
         assertEquals(1, results.size());
         MavenProject parent = results.get(0).getProject();
         assertEquals("parent", parent.getArtifactId());
-        // The modules list should be empty since we explicitly defined an empty <modules /> element
-        assertTrue(parent.getModel().getDelegate().getModules().isEmpty());
+        assertTrue(parent.getModel().getDelegate().getSubprojects().isEmpty());
     }
 
     @Test
diff --git a/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultModelXmlFactory.java b/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultModelXmlFactory.java
index 575d35e230..c87ce50343 100644
--- a/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultModelXmlFactory.java
+++ b/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultModelXmlFactory.java
@@ -132,6 +132,7 @@ private Model doRead(XmlReaderRequest request) throws XmlReaderException {
                     ? new MavenStaxReader(request.getTransformer()::transform)
                     : new MavenStaxReader();
             xml.setAddDefaultEntities(request.isAddDefaultEntities());
+            xml.setAddLocationInformation(request.isAddLocationInformation());
             if (inputStream != null) {
                 return xml.read(inputStream, request.isStrict(), source);
             } else if (reader != null) {
diff --git a/impl/maven-impl/src/main/java/org/apache/maven/impl/model/DefaultModelBuilder.java b/impl/maven-impl/src/main/java/org/apache/maven/impl/model/DefaultModelBuilder.java
index 317ff4f640..1b4dd2450c 100644
--- a/impl/maven-impl/src/main/java/org/apache/maven/impl/model/DefaultModelBuilder.java
+++ b/impl/maven-impl/src/main/java/org/apache/maven/impl/model/DefaultModelBuilder.java
@@ -1721,7 +1721,9 @@ Model doReadFileModel(Set<Path> activeModelReads) throws ModelBuilderException {
                             && !MODEL_VERSION_4_0_0.equals(model.getModelVersion())
                             // and if packaging is POM (we check type, but the session is not yet available,
                             // we would require the project realm if we want to support extensions
-                            && Type.POM.equals(model.getPackaging())) {
+                            && Type.POM.equals(model.getPackaging())
+                            // and if discovery is not disabled via property
+                            && Features.discoverSubprojects(request.getUserProperties())) {
                         List<String> subprojects = new ArrayList<>();
                         try (Stream<Path> files = Files.list(model.getProjectDirectory())) {
                             for (Path f : files.toList()) {
@@ -2336,17 +2338,16 @@ private static List<String> getSubprojects(Model activated) {
     }
 
     /**
-     * Checks if subprojects are explicitly defined in the main model.
-     * This method distinguishes between:
-     * 1. No subprojects/modules element present - returns false (should auto-discover)
-     * 2. Empty subprojects/modules element present - returns true (should NOT auto-discover)
-     * 3. Non-empty subprojects/modules - returns true (should NOT auto-discover)
+     * Checks whether the model has a non-empty {@code <subprojects>} or {@code <modules>} element.
+     * <p>
+     * When this returns {@code false} and auto-discovery is enabled (via
+     * {@link Features#discoverSubprojects(Map)}), Maven will scan subdirectories
+     * for POM files. Users who want to suppress discovery without listing subprojects
+     * can set {@code -Dmaven.project.discoverSubprojects=false}.
      */
     @SuppressWarnings("deprecation")
     private static boolean hasSubprojectsDefined(Model model) {
-        // Only consider the main model: profiles do not influence auto-discovery
-        // Inline the check for explicit elements using location tracking
-        return model.getLocation("subprojects") != null || model.getLocation("modules") != null;
+        return !model.getSubprojects().isEmpty() || !model.getModules().isEmpty();
     }
 
     @Override