You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by de...@apache.org on 2025/10/27 08:49:52 UTC

(maven) branch maven-4.0.x updated (b7d21263fe -> 00a83b6a94)

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

desruisseaux pushed a change to branch maven-4.0.x
in repository https://gitbox.apache.org/repos/asf/maven.git


    from b7d21263fe Missed parts for Mimir update (#11312) (#11313)
     new a8ef06417b Remove some trailing dot after `{@return}` Javadoc tag. A dot is already automatically added by Javadoc, so these trailing dots were causing dots to appear twice in the generated Javadoc.
     new 33a4ba9d00 Refactor `DefaultSourceRoot` as a record. It removes about a third of the code and forces us to be more consistent since all constructions must pass by the canonical constructor. This refactored class should have the same behavior as the previous class (no new feature).
     new 00a83b6a94 When the value of `<targetPath>` is a relative directory, the specification in `maven.mdo` requires that we resolve against `${project.build.outputDirectory}`, which is not `baseDir`.

The 3 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../main/java/org/apache/maven/api/Project.java    |  30 ++
 .../main/java/org/apache/maven/api/SourceRoot.java |  45 ++-
 .../java/org/apache/maven/api/SourceRootTest.java  |  89 ++++++
 api/maven-api-model/src/main/mdo/maven.mdo         |  12 +-
 .../maven/project/DefaultProjectBuilder.java       |  12 +-
 .../org/apache/maven/impl/DefaultSourceRoot.java   | 355 ++++++++-------------
 .../apache/maven/impl/DefaultSourceRootTest.java   |  75 ++++-
 7 files changed, 372 insertions(+), 246 deletions(-)
 create mode 100644 api/maven-api-core/src/test/java/org/apache/maven/api/SourceRootTest.java


(maven) 01/03: Remove some trailing dot after `{@return}` Javadoc tag. A dot is already automatically added by Javadoc, so these trailing dots were causing dots to appear twice in the generated Javadoc.

Posted by de...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

desruisseaux pushed a commit to branch maven-4.0.x
in repository https://gitbox.apache.org/repos/asf/maven.git

commit a8ef06417b6255bf048bc1365797183ec5c8f61b
Author: Martin Desruisseaux <ma...@geomatys.com>
AuthorDate: Sat Oct 25 15:24:57 2025 +0200

    Remove some trailing dot after `{@return}` Javadoc tag.
    A dot is already automatically added by Javadoc, so these trailing
    dots were causing dots to appear twice in the generated Javadoc.
---
 .../main/java/org/apache/maven/api/SourceRoot.java | 22 +++++++++++-----------
 .../org/apache/maven/impl/DefaultSourceRoot.java   |  8 ++++----
 2 files changed, 15 insertions(+), 15 deletions(-)

diff --git a/api/maven-api-core/src/main/java/org/apache/maven/api/SourceRoot.java b/api/maven-api-core/src/main/java/org/apache/maven/api/SourceRoot.java
index c60f6befda..0abd9bbe6d 100644
--- a/api/maven-api-core/src/main/java/org/apache/maven/api/SourceRoot.java
+++ b/api/maven-api-core/src/main/java/org/apache/maven/api/SourceRoot.java
@@ -35,7 +35,7 @@
  */
 public interface SourceRoot {
     /**
-     * {@return the root directory where the sources are stored}.
+     * {@return the root directory where the sources are stored}
      * The path is relative to the <abbr>POM</abbr> file.
      *
      * <h4>Default implementation</h4>
@@ -62,7 +62,7 @@ default Path directory() {
     }
 
     /**
-     * {@return the list of patterns for the files to include}.
+     * {@return the list of patterns for the files to include}
      * The path separator is {@code /} on all platforms, including Windows.
      * The prefix before the {@code :} character, if present and longer than 1 character, is the syntax.
      * If no syntax is specified, or if its length is 1 character (interpreted as a Windows drive),
@@ -79,7 +79,7 @@ default List<String> includes() {
     }
 
     /**
-     * {@return the list of patterns for the files to exclude}.
+     * {@return the list of patterns for the files to exclude}
      * The exclusions are applied after the inclusions.
      * The default implementation returns an empty list.
      */
@@ -88,7 +88,7 @@ default List<String> excludes() {
     }
 
     /**
-     * {@return a matcher combining the include and exclude patterns}.
+     * {@return a matcher combining the include and exclude patterns}
      * If the user did not specify any includes, the given {@code defaultIncludes} are used.
      * These defaults depend on the plugin.
      * For example, the default include of the Java compiler plugin is <code>"**&sol;*.java"</code>.
@@ -104,7 +104,7 @@ default List<String> excludes() {
     PathMatcher matcher(Collection<String> defaultIncludes, boolean useDefaultExcludes);
 
     /**
-     * {@return in which context the source files will be used}.
+     * {@return in which context the source files will be used}
      * Not to be confused with dependency scope.
      * The default value is {@code "main"}.
      *
@@ -115,7 +115,7 @@ default ProjectScope scope() {
     }
 
     /**
-     * {@return the language of the source files}.
+     * {@return the language of the source files}
      * The default value is {@code "java"}.
      *
      * @see Language#JAVA_FAMILY
@@ -125,7 +125,7 @@ default Language language() {
     }
 
     /**
-     * {@return the name of the Java module (or other language-specific module) which is built by the sources}.
+     * {@return the name of the Java module (or other language-specific module) which is built by the sources}
      * The default value is empty.
      */
     default Optional<String> module() {
@@ -133,7 +133,7 @@ default Optional<String> module() {
     }
 
     /**
-     * {@return the version of the platform where the code will be executed}.
+     * {@return the version of the platform where the code will be executed}
      * In a Java environment, this is the value of the {@code --release} compiler option.
      * The default value is empty.
      */
@@ -142,7 +142,7 @@ default Optional<Version> targetVersion() {
     }
 
     /**
-     * {@return an explicit target path, overriding the default value}.
+     * {@return an explicit target path, overriding the default value}
      * When a target path is explicitly specified, the values of the {@link #module()} and {@link #targetVersion()}
      * elements are not used for inferring the path (they are still used as compiler options however).
      * It means that for scripts and resources, the files below the path specified by {@link #directory()}
@@ -153,7 +153,7 @@ default Optional<Path> targetPath() {
     }
 
     /**
-     * {@return whether resources are filtered to replace tokens with parameterized values}.
+     * {@return whether resources are filtered to replace tokens with parameterized values}
      * The default value is {@code false}.
      */
     default boolean stringFiltering() {
@@ -161,7 +161,7 @@ default boolean stringFiltering() {
     }
 
     /**
-     * {@return whether the directory described by this source element should be included in the build}.
+     * {@return whether the directory described by this source element should be included in the build}
      * The default value is {@code true}.
      */
     default boolean enabled() {
diff --git a/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSourceRoot.java b/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSourceRoot.java
index ec35428a51..dad9d3cdae 100644
--- a/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSourceRoot.java
+++ b/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSourceRoot.java
@@ -208,7 +208,7 @@ public List<String> excludes() {
     }
 
     /**
-     * {@return a matcher combining the include and exclude patterns}.
+     * {@return a matcher combining the include and exclude patterns}
      *
      * @param defaultIncludes the default includes if unspecified by the user
      * @param useDefaultExcludes whether to add the default set of patterns to exclude,
@@ -240,7 +240,7 @@ public Language language() {
     }
 
     /**
-     * {@return the name of the Java module (or other language-specific module) which is built by the sources}.
+     * {@return the name of the Java module (or other language-specific module) which is built by the sources}
      */
     @Override
     public Optional<String> module() {
@@ -248,7 +248,7 @@ public Optional<String> module() {
     }
 
     /**
-     * {@return the version of the platform where the code will be executed}.
+     * {@return the version of the platform where the code will be executed}
      */
     @Override
     public Optional<Version> targetVersion() {
@@ -256,7 +256,7 @@ public Optional<Version> targetVersion() {
     }
 
     /**
-     * {@return an explicit target path, overriding the default value}.
+     * {@return an explicit target path, overriding the default value}
      */
     @Override
     public Optional<Path> targetPath() {


(maven) 03/03: When the value of `` is a relative directory, the specification in `maven.mdo` requires that we resolve against `${project.build.outputDirectory}`, which is not `baseDir`.

Posted by de...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

desruisseaux pushed a commit to branch maven-4.0.x
in repository https://gitbox.apache.org/repos/asf/maven.git

commit 00a83b6a944ea05db889a6d5cc9f565856fed152
Author: Martin Desruisseaux <ma...@geomatys.com>
AuthorDate: Sat Oct 25 17:08:29 2025 +0200

    When the value of `<targetPath>` is a relative directory, the specification in `maven.mdo`
    requires that we resolve against `${project.build.outputDirectory}`, which is not `baseDir`.
    
    Also modify the specification for resolving against `${project.build.testOutputDirectory}`
    if the scope is test and `${project.build.directory}` is the scope is neither main or test.
    
    Add a `Project.getOutputDirectory(ProjectScope)` for avoiding the need to repeat the same code in the plugins.
---
 .../main/java/org/apache/maven/api/Project.java    | 30 ++++++++
 .../main/java/org/apache/maven/api/SourceRoot.java | 23 ++++++
 .../java/org/apache/maven/api/SourceRootTest.java  | 89 ++++++++++++++++++++++
 api/maven-api-model/src/main/mdo/maven.mdo         | 12 ++-
 .../maven/project/DefaultProjectBuilder.java       | 12 ++-
 .../org/apache/maven/impl/DefaultSourceRoot.java   | 16 ++--
 .../apache/maven/impl/DefaultSourceRootTest.java   | 65 +++++++++++++++-
 7 files changed, 237 insertions(+), 10 deletions(-)

diff --git a/api/maven-api-core/src/main/java/org/apache/maven/api/Project.java b/api/maven-api-core/src/main/java/org/apache/maven/api/Project.java
index 8e989ad4ae..2fb4f4f7ba 100644
--- a/api/maven-api-core/src/main/java/org/apache/maven/api/Project.java
+++ b/api/maven-api-core/src/main/java/org/apache/maven/api/Project.java
@@ -24,6 +24,7 @@
 
 import org.apache.maven.api.annotations.Experimental;
 import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
 import org.apache.maven.api.model.Build;
 import org.apache.maven.api.model.Model;
 import org.apache.maven.api.model.Profile;
@@ -172,6 +173,35 @@ default Build getBuild() {
     @Nonnull
     Path getBasedir();
 
+    /**
+     * Returns the directory where files generated by the build are placed.
+     * The directory depends on the scope:
+     *
+     * <ul>
+     *   <li>If {@link ProjectScope#MAIN}, returns the directory where compiled application classes are placed.</li>
+     *   <li>If {@link ProjectScope#TEST}, returns the directory where compiled test classes are placed.</li>
+     *   <li>Otherwise (including {@code null}), returns the parent directory where all generated files are placed.</li>
+     * </ul>
+     *
+     * @param scope the scope of the generated files for which to get the directory, or {@code null} for all
+     * @return the output directory of files that are generated for the given scope
+     *
+     * @see SourceRoot#targetPath(Project)
+     */
+    @Nonnull
+    default Path getOutputDirectory(@Nullable ProjectScope scope) {
+        String dir;
+        Build build = getBuild();
+        if (scope == ProjectScope.MAIN) {
+            dir = build.getOutputDirectory();
+        } else if (scope == ProjectScope.TEST) {
+            dir = build.getTestOutputDirectory();
+        } else {
+            dir = build.getDirectory();
+        }
+        return getBasedir().resolve(dir);
+    }
+
     /**
      * {@return the project direct dependencies (directly specified or inherited)}.
      */
diff --git a/api/maven-api-core/src/main/java/org/apache/maven/api/SourceRoot.java b/api/maven-api-core/src/main/java/org/apache/maven/api/SourceRoot.java
index 0abd9bbe6d..dc08a6f24c 100644
--- a/api/maven-api-core/src/main/java/org/apache/maven/api/SourceRoot.java
+++ b/api/maven-api-core/src/main/java/org/apache/maven/api/SourceRoot.java
@@ -24,6 +24,8 @@
 import java.util.List;
 import java.util.Optional;
 
+import org.apache.maven.api.annotations.Nonnull;
+
 /**
  * A root directory of source files.
  * The sources may be Java main classes, test classes, resources or anything else identified by the scope.
@@ -152,6 +154,27 @@ default Optional<Path> targetPath() {
         return Optional.empty();
     }
 
+    /**
+     * {@return the explicit target path resolved against the default target path}
+     * Invoking this method is equivalent to getting the default output directory
+     * by a call to {@code project.getOutputDirectory(scope())}, then resolving the
+     * {@linkplain #targetPath() target path} (if present) against that default directory.
+     * Note that if the target path is absolute, the result is that target path unchanged.
+     *
+     * @param project the project to use for getting default directories
+     *
+     * @see Project#getOutputDirectory(ProjectScope)
+     */
+    @Nonnull
+    default Path targetPath(@Nonnull Project project) {
+        Optional<Path> targetPath = targetPath();
+        // The test for `isAbsolute()` is a small optimization for avoiding the call to `getOutputDirectory(…)`.
+        return targetPath.filter(Path::isAbsolute).orElseGet(() -> {
+            Path base = project.getOutputDirectory(scope());
+            return targetPath.map(base::resolve).orElse(base);
+        });
+    }
+
     /**
      * {@return whether resources are filtered to replace tokens with parameterized values}
      * The default value is {@code false}.
diff --git a/api/maven-api-core/src/test/java/org/apache/maven/api/SourceRootTest.java b/api/maven-api-core/src/test/java/org/apache/maven/api/SourceRootTest.java
new file mode 100644
index 0000000000..a316550aee
--- /dev/null
+++ b/api/maven-api-core/src/test/java/org/apache/maven/api/SourceRootTest.java
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.api;
+
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.util.Collection;
+import java.util.Optional;
+
+import org.apache.maven.api.model.Build;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class SourceRootTest implements SourceRoot {
+    private ProjectScope scope;
+
+    private Language language;
+
+    private String moduleName;
+
+    @Override
+    public ProjectScope scope() {
+        return (scope != null) ? scope : SourceRoot.super.scope();
+    }
+
+    @Override
+    public Language language() {
+        return (language != null) ? language : SourceRoot.super.language();
+    }
+
+    @Override
+    public Optional<String> module() {
+        return Optional.ofNullable(moduleName);
+    }
+
+    @Override
+    public PathMatcher matcher(Collection<String> defaultIncludes, boolean useDefaultExcludes) {
+        return null; // Not used for this test.
+    }
+
+    @Test
+    void testDirectory() {
+        assertEquals(Path.of("src", "main", "java"), directory());
+
+        scope = ProjectScope.TEST;
+        assertEquals(Path.of("src", "test", "java"), directory());
+
+        moduleName = "org.foo";
+        assertEquals(Path.of("src", "org.foo", "test", "java"), directory());
+    }
+
+    @Test
+    void testTargetPath() {
+        Build build = mock(Build.class);
+        when(build.getDirectory()).thenReturn("target");
+        when(build.getOutputDirectory()).thenReturn("target/classes");
+        when(build.getTestOutputDirectory()).thenReturn("target/test-classes");
+
+        Project project = mock(Project.class);
+        when(project.getBuild()).thenReturn(build);
+        when(project.getBasedir()).thenReturn(Path.of("myproject"));
+        when(project.getOutputDirectory(any(ProjectScope.class))).thenCallRealMethod();
+
+        assertEquals(Path.of("myproject", "target", "classes"), targetPath(project));
+
+        scope = ProjectScope.TEST;
+        assertEquals(Path.of("myproject", "target", "test-classes"), targetPath(project));
+    }
+}
diff --git a/api/maven-api-model/src/main/mdo/maven.mdo b/api/maven-api-model/src/main/mdo/maven.mdo
index 6222040050..653b355f3f 100644
--- a/api/maven-api-model/src/main/mdo/maven.mdo
+++ b/api/maven-api-model/src/main/mdo/maven.mdo
@@ -2129,8 +2129,16 @@
           <description>
             <![CDATA[
             Specifies an explicit target path, overriding the default value.
-            The path is relative to the {@code ${project.build.outputDirectory}} directory,
-            which is typically {@code target/classes} in a Java project.
+            If unspecified, then the default value is one of the following:
+
+            <ul>
+              <li>{@code ${project.build.outputDirectory}} (typically {@code target/classes}) if {@code scope} is "main",</li>
+              <li>{@code ${project.build.testOutputDirectory}} (typically {@code target/test-classes}) if {@code scope} is "test",</li>
+              <li>{@code ${project.build.directory}} (typically {@code target}) otherwise.</li>
+            </ul>
+
+            <p>If this property is specified but is a relative path,
+            then the path is resolved against the above-cited default value.</p>
 
             <p>When a target path is explicitly specified, the values of the {@code module} and {@code targetVersion}
             elements are not used for inferring the path (they are still used as compiler options however).
diff --git a/impl/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java b/impl/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java
index 405da93e4a..1b1976c7f6 100644
--- a/impl/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java
+++ b/impl/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java
@@ -40,6 +40,7 @@
 import java.util.Properties;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Function;
 import java.util.function.Supplier;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
@@ -644,11 +645,20 @@ private void initProject(MavenProject project, ModelBuilderResult result) {
                 Build build = project.getBuild().getDelegate();
                 List<org.apache.maven.api.model.Source> sources = build.getSources();
                 Path baseDir = project.getBaseDirectory();
+                Function<ProjectScope, String> outputDirectory = (scope) -> {
+                    if (scope == ProjectScope.MAIN) {
+                        return build.getOutputDirectory();
+                    } else if (scope == ProjectScope.TEST) {
+                        return build.getTestOutputDirectory();
+                    } else {
+                        return build.getDirectory();
+                    }
+                };
                 boolean hasScript = false;
                 boolean hasMain = false;
                 boolean hasTest = false;
                 for (var source : sources) {
-                    var src = DefaultSourceRoot.fromModel(session, baseDir, source);
+                    var src = DefaultSourceRoot.fromModel(session, baseDir, outputDirectory, source);
                     project.addSourceRoot(src);
                     Language language = src.language();
                     if (Language.JAVA_FAMILY.equals(language)) {
diff --git a/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSourceRoot.java b/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSourceRoot.java
index 57994c0fe1..6ffec2ce88 100644
--- a/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSourceRoot.java
+++ b/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSourceRoot.java
@@ -24,6 +24,7 @@
 import java.util.List;
 import java.util.Objects;
 import java.util.Optional;
+import java.util.function.Function;
 
 import org.apache.maven.api.Language;
 import org.apache.maven.api.ProjectScope;
@@ -114,11 +115,13 @@ public DefaultSourceRoot(
     /**
      * Creates a new instance from the given model.
      *
-     * @param session the session of resolving extensible enumerations
-     * @param baseDir the base directory for resolving relative paths
-     * @param source a source element from the model
+     * @param session    the session of resolving extensible enumerations
+     * @param baseDir    the base directory for resolving relative paths
+     * @param outputDir  supplier of output directory relative to {@code baseDir}
+     * @param source     a source element from the model
      */
-    public static DefaultSourceRoot fromModel(final Session session, final Path baseDir, final Source source) {
+    public static DefaultSourceRoot fromModel(
+            Session session, Path baseDir, Function<ProjectScope, String> outputDir, Source source) {
         ProjectScope scope =
                 nonBlank(source.getScope()).map(session::requireProjectScope).orElse(ProjectScope.MAIN);
         Language language =
@@ -139,7 +142,10 @@ public static DefaultSourceRoot fromModel(final Session session, final Path base
                 source.getIncludes(),
                 source.getExcludes(),
                 source.isStringFiltering(),
-                nonBlank(source.getTargetPath()).map(baseDir::resolve).orElse(null),
+                nonBlank(source.getTargetPath())
+                        .map((targetPath) ->
+                                baseDir.resolve(outputDir.apply(scope)).resolve(targetPath))
+                        .orElse(null),
                 source.isEnabled());
     }
 
diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultSourceRootTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultSourceRootTest.java
index 446a0315e9..6ceedfea56 100644
--- a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultSourceRootTest.java
+++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultSourceRootTest.java
@@ -21,6 +21,7 @@
 import java.nio.file.Path;
 import java.util.List;
 import java.util.Optional;
+import java.util.function.Function;
 
 import org.apache.maven.api.Language;
 import org.apache.maven.api.ProjectScope;
@@ -56,10 +57,28 @@ public void setup() {
         stub.when(session.requireLanguage(eq("resources"))).thenReturn(Language.RESOURCES);
     }
 
+    /**
+     * Returns the output directory relative to the base directory.
+     */
+    private static Function<ProjectScope, String> outputDirectory() {
+        return (scope) -> {
+            if (scope == ProjectScope.MAIN) {
+                return "target/classes";
+            } else if (scope == ProjectScope.TEST) {
+                return "target/test-classes";
+            } else {
+                return "target";
+            }
+        };
+    }
+
     @Test
     void testMainJavaDirectory() {
         var source = DefaultSourceRoot.fromModel(
-                session, Path.of("myproject"), Source.newBuilder().build());
+                session,
+                Path.of("myproject"),
+                outputDirectory(),
+                Source.newBuilder().build());
 
         assertTrue(source.module().isEmpty());
         assertEquals(ProjectScope.MAIN, source.scope());
@@ -71,7 +90,10 @@ void testMainJavaDirectory() {
     @Test
     void testTestJavaDirectory() {
         var source = DefaultSourceRoot.fromModel(
-                session, Path.of("myproject"), Source.newBuilder().scope("test").build());
+                session,
+                Path.of("myproject"),
+                outputDirectory(),
+                Source.newBuilder().scope("test").build());
 
         assertTrue(source.module().isEmpty());
         assertEquals(ProjectScope.TEST, source.scope());
@@ -85,6 +107,7 @@ void testTestResourceDirectory() {
         var source = DefaultSourceRoot.fromModel(
                 session,
                 Path.of("myproject"),
+                outputDirectory(),
                 Source.newBuilder().scope("test").lang("resources").build());
 
         assertTrue(source.module().isEmpty());
@@ -99,6 +122,7 @@ void testModuleMainDirectory() {
         var source = DefaultSourceRoot.fromModel(
                 session,
                 Path.of("myproject"),
+                outputDirectory(),
                 Source.newBuilder().module("org.foo.bar").build());
 
         assertEquals("org.foo.bar", source.module().orElseThrow());
@@ -113,6 +137,7 @@ void testModuleTestDirectory() {
         var source = DefaultSourceRoot.fromModel(
                 session,
                 Path.of("myproject"),
+                outputDirectory(),
                 Source.newBuilder().module("org.foo.bar").scope("test").build());
 
         assertEquals("org.foo.bar", source.module().orElseThrow());
@@ -122,6 +147,42 @@ void testModuleTestDirectory() {
         assertTrue(source.targetVersion().isEmpty());
     }
 
+    /**
+     * Tests that relative target paths are resolved against the right base directory.
+     */
+    @Test
+    void testRelativeMainTargetPath() {
+        var source = DefaultSourceRoot.fromModel(
+                session,
+                Path.of("myproject"),
+                outputDirectory(),
+                Source.newBuilder().targetPath("user-output").build());
+
+        assertEquals(ProjectScope.MAIN, source.scope());
+        assertEquals(Language.JAVA_FAMILY, source.language());
+        assertEquals(
+                Path.of("myproject", "target", "classes", "user-output"),
+                source.targetPath().orElseThrow());
+    }
+
+    /**
+     * Tests that relative target paths are resolved against the right base directory.
+     */
+    @Test
+    void testRelativeTestTargetPath() {
+        var source = DefaultSourceRoot.fromModel(
+                session,
+                Path.of("myproject"),
+                outputDirectory(),
+                Source.newBuilder().targetPath("user-output").scope("test").build());
+
+        assertEquals(ProjectScope.TEST, source.scope());
+        assertEquals(Language.JAVA_FAMILY, source.language());
+        assertEquals(
+                Path.of("myproject", "target", "test-classes", "user-output"),
+                source.targetPath().orElseThrow());
+    }
+
     /*MNG-11062*/
     @Test
     void testExtractsTargetPathFromResource() {


(maven) 02/03: Refactor `DefaultSourceRoot` as a record. It removes about a third of the code and forces us to be more consistent since all constructions must pass by the canonical constructor. This refactored class should have the same behavior as the previous class (no new feature).

Posted by de...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

desruisseaux pushed a commit to branch maven-4.0.x
in repository https://gitbox.apache.org/repos/asf/maven.git

commit 33a4ba9d00190e495c4ca421005d0dde8c45e5bb
Author: Martin Desruisseaux <ma...@geomatys.com>
AuthorDate: Sat Oct 25 15:44:10 2025 +0200

    Refactor `DefaultSourceRoot` as a record. It removes about a third of the code and forces
    us to be more consistent since all constructions must pass by the canonical constructor.
    This refactored class should have the same behavior as the previous class (no new feature).
---
 .../maven/project/DefaultProjectBuilder.java       |   2 +-
 .../org/apache/maven/impl/DefaultSourceRoot.java   | 333 +++++++--------------
 .../apache/maven/impl/DefaultSourceRootTest.java   |  10 +-
 3 files changed, 122 insertions(+), 223 deletions(-)

diff --git a/impl/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java b/impl/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java
index 7a056b48e1..405da93e4a 100644
--- a/impl/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java
+++ b/impl/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java
@@ -648,7 +648,7 @@ private void initProject(MavenProject project, ModelBuilderResult result) {
                 boolean hasMain = false;
                 boolean hasTest = false;
                 for (var source : sources) {
-                    var src = new DefaultSourceRoot(session, baseDir, source);
+                    var src = DefaultSourceRoot.fromModel(session, baseDir, source);
                     project.addSourceRoot(src);
                     Language language = src.language();
                     if (Language.JAVA_FAMILY.equals(language)) {
diff --git a/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSourceRoot.java b/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSourceRoot.java
index dad9d3cdae..57994c0fe1 100644
--- a/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSourceRoot.java
+++ b/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSourceRoot.java
@@ -30,32 +30,86 @@
 import org.apache.maven.api.Session;
 import org.apache.maven.api.SourceRoot;
 import org.apache.maven.api.Version;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
 import org.apache.maven.api.model.Resource;
 import org.apache.maven.api.model.Source;
 
 /**
  * A default implementation of {@code SourceRoot} built from the model.
+ *
+ * @param scope               in which context the source files will be used (main or test)
+ * @param language            language of the source files
+ * @param moduleName          name of the Java module which is built by the sources
+ * @param targetVersionOrNull version of the platform where the code will be executed
+ * @param directory           root directory where the sources are stored
+ * @param includes            patterns for the files to include, or empty if unspecified
+ * @param excludes            patterns for the files to exclude, or empty if nothing to exclude
+ * @param stringFiltering     whether resources are filtered to replace tokens with parameterized values
+ * @param targetPathOrNull    an explicit target path, overriding the default value
+ * @param enabled             whether the directory described by this source element should be included in the build
  */
-public final class DefaultSourceRoot implements SourceRoot {
-    private final Path directory;
-
-    private final List<String> includes;
-
-    private final List<String> excludes;
-
-    private final ProjectScope scope;
-
-    private final Language language;
-
-    private final String moduleName;
-
-    private final Version targetVersion;
-
-    private final Path targetPath;
-
-    private final boolean stringFiltering;
+public record DefaultSourceRoot(
+        @Nonnull ProjectScope scope,
+        @Nonnull Language language,
+        @Nullable String moduleName,
+        @Nullable Version targetVersionOrNull,
+        @Nonnull Path directory,
+        @Nonnull List<String> includes,
+        @Nonnull List<String> excludes,
+        boolean stringFiltering,
+        @Nullable Path targetPathOrNull,
+        boolean enabled)
+        implements SourceRoot {
+
+    /**
+     * Creates a simple instance with no Java module, no target version, and no include or exclude pattern.
+     *
+     * @param scope     in which context the source files will be used (main or test)
+     * @param language  the language of the source files
+     * @param directory the root directory where the sources are stored
+     */
+    public DefaultSourceRoot(ProjectScope scope, Language language, Path directory) {
+        this(scope, language, null, null, directory, null, null, false, null, true);
+    }
 
-    private final boolean enabled;
+    /**
+     * Canonical constructor.
+     *
+     * @param scope               in which context the source files will be used (main or test)
+     * @param language            language of the source files
+     * @param moduleName          name of the Java module which is built by the sources
+     * @param targetVersionOrNull version of the platform where the code will be executed
+     * @param directory           root directory where the sources are stored
+     * @param includes            patterns for the files to include, or {@code null} or empty if unspecified
+     * @param excludes            patterns for the files to exclude, or {@code null} or empty if nothing to exclude
+     * @param stringFiltering     whether resources are filtered to replace tokens with parameterized values
+     * @param targetPathOrNull    an explicit target path, overriding the default value
+     * @param enabled             whether the directory described by this source element should be included in the build
+     */
+    @SuppressWarnings("checkstyle:ParameterNumber")
+    public DefaultSourceRoot(
+            @Nonnull ProjectScope scope,
+            @Nonnull Language language,
+            @Nullable String moduleName,
+            @Nullable Version targetVersionOrNull,
+            @Nullable Path directory,
+            @Nullable List<String> includes,
+            @Nullable List<String> excludes,
+            boolean stringFiltering,
+            @Nullable Path targetPathOrNull,
+            boolean enabled) {
+        this.scope = Objects.requireNonNull(scope);
+        this.language = Objects.requireNonNull(language);
+        this.moduleName = nonBlank(moduleName).orElse(null);
+        this.targetVersionOrNull = targetVersionOrNull;
+        this.directory = directory.normalize();
+        this.includes = (includes != null) ? List.copyOf(includes) : List.of();
+        this.excludes = (excludes != null) ? List.copyOf(excludes) : List.of();
+        this.stringFiltering = stringFiltering;
+        this.targetPathOrNull = (targetPathOrNull != null) ? targetPathOrNull.normalize() : null;
+        this.enabled = enabled;
+    }
 
     /**
      * Creates a new instance from the given model.
@@ -64,35 +118,29 @@ public final class DefaultSourceRoot implements SourceRoot {
      * @param baseDir the base directory for resolving relative paths
      * @param source a source element from the model
      */
-    public DefaultSourceRoot(final Session session, final Path baseDir, final Source source) {
-        includes = source.getIncludes();
-        excludes = source.getExcludes();
-        stringFiltering = source.isStringFiltering();
-        enabled = source.isEnabled();
-        moduleName = nonBlank(source.getModule());
-
-        String value = nonBlank(source.getScope());
-        scope = (value != null) ? session.requireProjectScope(value) : ProjectScope.MAIN;
-
-        value = nonBlank(source.getLang());
-        language = (value != null) ? session.requireLanguage(value) : Language.JAVA_FAMILY;
-
-        value = nonBlank(source.getDirectory());
-        if (value != null) {
-            directory = baseDir.resolve(value);
-        } else {
-            Path src = baseDir.resolve("src");
-            if (moduleName != null) {
-                src = src.resolve(moduleName);
-            }
-            directory = src.resolve(scope.id()).resolve(language.id());
-        }
-
-        value = nonBlank(source.getTargetVersion());
-        targetVersion = (value != null) ? session.parseVersion(value) : null;
-
-        value = nonBlank(source.getTargetPath());
-        targetPath = (value != null) ? baseDir.resolve(value) : null;
+    public static DefaultSourceRoot fromModel(final Session session, final Path baseDir, final Source source) {
+        ProjectScope scope =
+                nonBlank(source.getScope()).map(session::requireProjectScope).orElse(ProjectScope.MAIN);
+        Language language =
+                nonBlank(source.getLang()).map(session::requireLanguage).orElse(Language.JAVA_FAMILY);
+        String moduleName = nonBlank(source.getModule()).orElse(null);
+        return new DefaultSourceRoot(
+                scope,
+                language,
+                moduleName,
+                nonBlank(source.getTargetVersion()).map(session::parseVersion).orElse(null),
+                nonBlank(source.getDirectory()).map(baseDir::resolve).orElseGet(() -> {
+                    Path src = baseDir.resolve("src");
+                    if (moduleName != null) {
+                        src = src.resolve(moduleName);
+                    }
+                    return src.resolve(scope.id()).resolve(language.id());
+                }),
+                source.getIncludes(),
+                source.getExcludes(),
+                source.isStringFiltering(),
+                nonBlank(source.getTargetPath()).map(baseDir::resolve).orElse(null),
+                source.isEnabled());
     }
 
     /**
@@ -104,107 +152,32 @@ public DefaultSourceRoot(final Session session, final Path baseDir, final Source
      * @param resource a resource element from the model
      */
     public DefaultSourceRoot(final Path baseDir, ProjectScope scope, Resource resource) {
-        String value = nonBlank(resource.getDirectory());
-        if (value == null) {
-            throw new IllegalArgumentException("Source declaration without directory value.");
-        }
-        directory = baseDir.resolve(value).normalize();
-        includes = resource.getIncludes();
-        excludes = resource.getExcludes();
-        stringFiltering = Boolean.parseBoolean(resource.getFiltering());
-        enabled = true;
-        moduleName = null;
-        this.scope = scope;
-        language = Language.RESOURCES;
-        targetVersion = null;
-        value = nonBlank(resource.getTargetPath());
-        targetPath = (value != null) ? baseDir.resolve(value).normalize() : null;
-    }
-
-    /**
-     * Creates a new instance for the given directory and scope.
-     *
-     * @param scope scope of source code (main or test)
-     * @param language language of the source code
-     * @param directory directory of the source code
-     */
-    public DefaultSourceRoot(final ProjectScope scope, final Language language, final Path directory) {
-        this.scope = Objects.requireNonNull(scope);
-        this.language = Objects.requireNonNull(language);
-        this.directory = Objects.requireNonNull(directory);
-        includes = List.of();
-        excludes = List.of();
-        moduleName = null;
-        targetVersion = null;
-        targetPath = null;
-        stringFiltering = false;
-        enabled = true;
-    }
-
-    /**
-     * Creates a new instance for the given directory and scope.
-     *
-     * @param scope scope of source code (main or test)
-     * @param language language of the source code
-     * @param directory directory of the source code
-     * @param includes patterns for the files to include, or {@code null} or empty if unspecified
-     * @param excludes patterns for the files to exclude, or {@code null} or empty if nothing to exclude
-     */
-    public DefaultSourceRoot(
-            final ProjectScope scope,
-            final Language language,
-            final Path directory,
-            List<String> includes,
-            List<String> excludes) {
-        this.scope = Objects.requireNonNull(scope);
-        this.language = language;
-        this.directory = Objects.requireNonNull(directory);
-        this.includes = includes != null ? List.copyOf(includes) : List.of();
-        this.excludes = excludes != null ? List.copyOf(excludes) : List.of();
-        moduleName = null;
-        targetVersion = null;
-        targetPath = null;
-        stringFiltering = false;
-        enabled = true;
+        this(
+                scope,
+                Language.RESOURCES,
+                null,
+                null,
+                baseDir.resolve(nonBlank(resource.getDirectory())
+                        .orElseThrow(
+                                () -> new IllegalArgumentException("Source declaration without directory value."))),
+                resource.getIncludes(),
+                resource.getExcludes(),
+                Boolean.parseBoolean(resource.getFiltering()),
+                nonBlank(resource.getTargetPath()).map(baseDir::resolve).orElse(null),
+                true);
     }
 
     /**
-     * {@return the given value as a trimmed non-blank string, or null otherwise}.
+     * {@return the given value as a trimmed non-blank string, or empty otherwise}
      */
-    private static String nonBlank(String value) {
+    private static Optional<String> nonBlank(String value) {
         if (value != null) {
             value = value.trim();
-            if (value.isBlank()) {
-                value = null;
+            if (!value.isBlank()) {
+                return Optional.of(value);
             }
         }
-        return value;
-    }
-
-    /**
-     * {@return the root directory where the sources are stored}.
-     */
-    @Override
-    public Path directory() {
-        return directory;
-    }
-
-    /**
-     * {@return the patterns for the files to include}.
-     */
-    @Override
-    @SuppressWarnings("ReturnOfCollectionOrArrayField") // Safe because unmodifiable
-    public List<String> includes() {
-        return includes;
-    }
-
-    /**
-     * {@return the patterns for the files to exclude}.
-     */
-    @Override
-    @SuppressWarnings("ReturnOfCollectionOrArrayField") // Safe because unmodifiable
-    public List<String> excludes() {
-        return excludes;
+        return Optional.empty();
     }
 
     /**
@@ -223,22 +196,6 @@ public PathMatcher matcher(Collection<String> defaultIncludes, boolean useDefaul
         return PathSelector.of(directory(), actual, excludes(), useDefaultExcludes);
     }
 
-    /**
-     * {@return in which context the source files will be used}.
-     */
-    @Override
-    public ProjectScope scope() {
-        return scope;
-    }
-
-    /**
-     * {@return the language of the source files}.
-     */
-    @Override
-    public Language language() {
-        return language;
-    }
-
     /**
      * {@return the name of the Java module (or other language-specific module) which is built by the sources}
      */
@@ -252,7 +209,7 @@ public Optional<String> module() {
      */
     @Override
     public Optional<Version> targetVersion() {
-        return Optional.ofNullable(targetVersion);
+        return Optional.ofNullable(targetVersionOrNull);
     }
 
     /**
@@ -260,64 +217,6 @@ public Optional<Version> targetVersion() {
      */
     @Override
     public Optional<Path> targetPath() {
-        return Optional.ofNullable(targetPath);
-    }
-
-    /**
-     * {@return whether resources are filtered to replace tokens with parameterized values}.
-     */
-    @Override
-    public boolean stringFiltering() {
-        return stringFiltering;
-    }
-
-    /**
-     * {@return whether the directory described by this source element should be included in the build}.
-     */
-    @Override
-    public boolean enabled() {
-        return enabled;
-    }
-
-    /**
-     * {@return a hash code value computed from all properties}.
-     */
-    @Override
-    public int hashCode() {
-        return Objects.hash(
-                directory,
-                includes,
-                excludes,
-                scope,
-                language,
-                moduleName,
-                targetVersion,
-                targetPath,
-                stringFiltering,
-                enabled);
-    }
-
-    /**
-     * {@return whether the two objects are of the same class with equal property values}.
-     *
-     * @param obj the other object to compare with this object, or {@code null}
-     */
-    @Override
-    public boolean equals(Object obj) {
-        if (this == obj) {
-            return true;
-        }
-        if (obj instanceof DefaultSourceRoot other) {
-            return directory.equals(other.directory)
-                    && includes.equals(other.includes)
-                    && excludes.equals(other.excludes)
-                    && Objects.equals(scope, other.scope)
-                    && Objects.equals(language, other.language)
-                    && Objects.equals(moduleName, other.moduleName)
-                    && Objects.equals(targetVersion, other.targetVersion)
-                    && stringFiltering == other.stringFiltering
-                    && enabled == other.enabled;
-        }
-        return false;
+        return Optional.ofNullable(targetPathOrNull);
     }
 }
diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultSourceRootTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultSourceRootTest.java
index e27cfa3109..446a0315e9 100644
--- a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultSourceRootTest.java
+++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultSourceRootTest.java
@@ -58,7 +58,7 @@ public void setup() {
 
     @Test
     void testMainJavaDirectory() {
-        var source = new DefaultSourceRoot(
+        var source = DefaultSourceRoot.fromModel(
                 session, Path.of("myproject"), Source.newBuilder().build());
 
         assertTrue(source.module().isEmpty());
@@ -70,7 +70,7 @@ void testMainJavaDirectory() {
 
     @Test
     void testTestJavaDirectory() {
-        var source = new DefaultSourceRoot(
+        var source = DefaultSourceRoot.fromModel(
                 session, Path.of("myproject"), Source.newBuilder().scope("test").build());
 
         assertTrue(source.module().isEmpty());
@@ -82,7 +82,7 @@ void testTestJavaDirectory() {
 
     @Test
     void testTestResourceDirectory() {
-        var source = new DefaultSourceRoot(
+        var source = DefaultSourceRoot.fromModel(
                 session,
                 Path.of("myproject"),
                 Source.newBuilder().scope("test").lang("resources").build());
@@ -96,7 +96,7 @@ void testTestResourceDirectory() {
 
     @Test
     void testModuleMainDirectory() {
-        var source = new DefaultSourceRoot(
+        var source = DefaultSourceRoot.fromModel(
                 session,
                 Path.of("myproject"),
                 Source.newBuilder().module("org.foo.bar").build());
@@ -110,7 +110,7 @@ void testModuleMainDirectory() {
 
     @Test
     void testModuleTestDirectory() {
-        var source = new DefaultSourceRoot(
+        var source = DefaultSourceRoot.fromModel(
                 session,
                 Path.of("myproject"),
                 Source.newBuilder().module("org.foo.bar").scope("test").build());