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

slachiewicz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven-dependency-plugin.git


The following commit(s) were added to refs/heads/master by this push:
     new f12f589a [MDEP-953] Copy several artifact items with their 
dependencies in one graph
f12f589a is described below

commit f12f589aab3985618b42487732517450ad40f2ac
Author: Sylwester Lachiewicz <[email protected]>
AuthorDate: Sat Nov 14 20:18:27 2026 +0100

    [MDEP-953] Copy several artifact items with their dependencies in one graph
---
 .../dependency/fromConfiguration/CopyMojo.java     |  94 +++++++++++--
 .../plugins/dependency/utils/ResolverUtil.java     |  31 ++++-
 .../dependency/fromConfiguration/TestCopyMojo.java | 148 +++++++++++++++++++--
 3 files changed, 249 insertions(+), 24 deletions(-)

diff --git 
a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/CopyMojo.java
 
b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/CopyMojo.java
index 621a43b6..8d0ea88f 100644
--- 
a/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/CopyMojo.java
+++ 
b/src/main/java/org/apache/maven/plugins/dependency/fromConfiguration/CopyMojo.java
@@ -22,7 +22,11 @@ import javax.inject.Inject;
 
 import java.io.File;
 import java.io.IOException;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 
 import org.apache.maven.RepositoryUtils;
 import org.apache.maven.artifact.Artifact;
@@ -99,10 +103,19 @@ public class CopyMojo extends 
AbstractFromConfigurationMojo {
     private String artifact;
 
     /**
-     * Resolve the single artifact identified by {@link #artifact} (or by a 
single-entry {@link #artifactItems})
-     * together with its transitive dependencies, directly through the 
repository system, and copy all of them.
-     * Lets this goal be used like {@code dependency:get}, but copying the 
resolved files instead of only
-     * downloading them into the local repository. Not supported together with 
more than one artifact item.
+     * Resolve the artifact identified by {@link #artifact} (or by the {@link 
#artifactItems}) together with its
+     * transitive dependencies, directly through the repository system, and 
copy all of them. With a single artifact
+     * this goal works like {@code dependency:get}, but copies the resolved 
files instead of only downloading them
+     * into the local repository.
+     * <p>
+     * With several artifact items, all of them are resolved in one dependency 
graph, as if a project declared them
+     * as dependencies, so a dependency they share is copied once, in the 
version chosen by Maven's usual mediation
+     * rules. Their own test, provided and optional dependencies are then left 
out, whereas a single artifact,
+     * being the root of the graph, keeps its optional dependencies. No 
project dependency management applies. All
+     * the artifact items must use the same output directory, and no two of 
them may name the same artifact in
+     * different versions. The {@code destFileName} and {@code overWrite} 
settings of the artifact items are not
+     * used: every resolved file is copied under the name built from {@code 
stripVersion}, {@code stripClassifier},
+     * {@code prependGroupId} and {@code useBaseVersion}.
      *
      * @since 3.12.0
      */
@@ -139,16 +152,15 @@ public class CopyMojo extends 
AbstractFromConfigurationMojo {
         verifyRequirements();
         verifyExplicitDependencies();
 
-        if (transitive && getArtifactItems().size() != 1) {
-            throw new MojoFailureException("transitive requires a single 
artifact, not "
-                    + getArtifactItems().size() + " artifactItems");
-        }
-
         List<ArtifactItem> theArtifactItems = getProcessedArtifactItems(
                 new ProcessArtifactItemsRequest(stripVersion, prependGroupId, 
useBaseVersion, stripClassifier));
 
         if (transitive) {
-            copyWithTransitiveDependencies(theArtifactItems.get(0));
+            if (theArtifactItems.size() == 1) {
+                copyWithTransitiveDependencies(theArtifactItems.get(0));
+            } else {
+                copyAllWithTransitiveDependencies(theArtifactItems);
+            }
             return;
         }
 
@@ -180,11 +192,71 @@ public class CopyMojo extends 
AbstractFromConfigurationMojo {
             throw new MojoExecutionException("Failed to resolve " + 
rootArtifact + " with its dependencies", e);
         }
 
+        copyResolved(resolved, rootItem.getOutputDirectory());
+    }
+
+    /**
+     * Resolves the artifacts of all {@code items} together with their 
transitive dependencies in one dependency
+     * graph, and copies every resolved artifact to the items' common output 
directory.
+     *
+     * @param items the configured artifact items, more than one
+     * @throws MojoFailureException   if the items use different output 
directories, or name one artifact in two
+     *                                 versions
+     * @throws MojoExecutionException if an artifact or one of its 
dependencies cannot be resolved, or if one of them
+     *                                 cannot be copied
+     */
+    private void copyAllWithTransitiveDependencies(List<ArtifactItem> items)
+            throws MojoExecutionException, MojoFailureException {
+        File outputDirectory = items.get(0).getOutputDirectory();
+        Map<String, ArtifactItem> byKey = new HashMap<>();
+        List<org.eclipse.aether.artifact.Artifact> roots = new ArrayList<>();
+        for (ArtifactItem item : items) {
+            if 
(!normalized(outputDirectory).equals(normalized(item.getOutputDirectory()))) {
+                throw new MojoFailureException("transitive requires all 
artifactItems to use the same outputDirectory,"
+                        + " but " + items.get(0) + " uses " + outputDirectory 
+ " and " + item + " uses "
+                        + item.getOutputDirectory());
+            }
+            org.eclipse.aether.artifact.Artifact root = 
RepositoryUtils.toArtifact(item.getArtifact());
+            String key = root.getGroupId()
+                    + ':'
+                    + root.getArtifactId()
+                    + ':'
+                    + root.getExtension()
+                    + ':'
+                    + root.getClassifier();
+            ArtifactItem previous = byKey.putIfAbsent(key, item);
+            if (previous == null) {
+                roots.add(root);
+            } else if (!previous.getArtifact()
+                    .getVersion()
+                    .equals(item.getArtifact().getVersion())) {
+                throw new MojoFailureException("transitive cannot copy " + 
previous + " and " + item
+                        + ": they name the same artifact in different 
versions");
+            }
+        }
+
+        List<org.eclipse.aether.artifact.Artifact> resolved;
+        try {
+            resolved = resolverUtil.resolveArtifactsAndDependencies(
+                    roots, getRemoteRepositories(), null, 
session.getRepositorySession());
+        } catch (DependencyResolutionException e) {
+            throw new MojoExecutionException("Failed to resolve " + roots + " 
with their dependencies", e);
+        }
+
+        copyResolved(resolved, outputDirectory);
+    }
+
+    private static Path normalized(File directory) {
+        return directory.toPath().toAbsolutePath().normalize();
+    }
+
+    private void copyResolved(List<org.eclipse.aether.artifact.Artifact> 
resolved, File outputDirectory)
+            throws MojoExecutionException {
         for (org.eclipse.aether.artifact.Artifact resolvedArtifact : resolved) 
{
             Artifact artifactToCopy = 
RepositoryUtils.toArtifact(resolvedArtifact);
             String destFileName = DependencyUtil.getFormattedFileName(
                     artifactToCopy, stripVersion, prependGroupId, 
useBaseVersion, stripClassifier);
-            File destFile = new File(rootItem.getOutputDirectory(), 
destFileName);
+            File destFile = new File(outputDirectory, destFileName);
             if (destFile.exists()) {
                 getLog().warn("Overwriting " + destFile);
             }
diff --git 
a/src/main/java/org/apache/maven/plugins/dependency/utils/ResolverUtil.java 
b/src/main/java/org/apache/maven/plugins/dependency/utils/ResolverUtil.java
index adf5c5a7..56be82f5 100644
--- a/src/main/java/org/apache/maven/plugins/dependency/utils/ResolverUtil.java
+++ b/src/main/java/org/apache/maven/plugins/dependency/utils/ResolverUtil.java
@@ -361,10 +361,35 @@ public class ResolverUtil {
             DependencyFilter dependencyFilter,
             RepositorySystemSession session)
             throws DependencyResolutionException {
-        // The artifact is a direct dependency of a rootless request, so the 
session's selectors treat its own
+        return resolveArtifactsAndDependencies(
+                Collections.singletonList(artifact), repositories, 
dependencyFilter, session);
+    }
+
+    /**
+     * Resolve several artifacts named by their coordinates alone, together 
with their transitive dependencies, in
+     * one dependency graph. Each artifact is a direct dependency of a 
rootless request, as if a project declared all
+     * of them, so a dependency they share is resolved to a single version by 
the usual mediation rules.
+     *
+     * @param artifacts        the artifacts to resolve
+     * @param repositories     remote repositories list
+     * @param dependencyFilter dependency filter, or {@code null}; it is 
applied to the artifacts themselves as well
+     * @param session          a repository system session
+     * @return the resolved artifacts
+     * @throws DependencyResolutionException if the dependency tree could not 
be built or any dependency artifact could
+     *                                       not be resolved
+     */
+    public List<Artifact> resolveArtifactsAndDependencies(
+            List<Artifact> artifacts,
+            List<RemoteRepository> repositories,
+            DependencyFilter dependencyFilter,
+            RepositorySystemSession session)
+            throws DependencyResolutionException {
+        // The artifacts are direct dependencies of a rootless request, so the 
session's selectors treat their own
         // dependencies as transitive ones: test, provided and optional 
dependencies stay out.
-        CollectRequest collectRequest =
-                new CollectRequest(Collections.singletonList(new 
Dependency(artifact, null)), null, repositories);
+        List<Dependency> dependencies = artifacts.stream()
+                .map(artifact -> new Dependency(artifact, null))
+                .collect(Collectors.toList());
+        CollectRequest collectRequest = new CollectRequest(dependencies, null, 
repositories);
         DependencyResult result =
                 repositorySystem.resolveDependencies(session, new 
DependencyRequest(collectRequest, dependencyFilter));
         return result.getArtifactResults().stream()
diff --git 
a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestCopyMojo.java
 
b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestCopyMojo.java
index 3cb811ac..292a1614 100644
--- 
a/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestCopyMojo.java
+++ 
b/src/test/java/org/apache/maven/plugins/dependency/fromConfiguration/TestCopyMojo.java
@@ -831,23 +831,151 @@ class TestCopyMojo {
         assertTrue(new File(mojo.getOutputDirectory(), 
"leaf-1.0.jar").isFile());
     }
 
+    private static String dependencyXml(String artifactId, String version, 
String extra) {
+        return "<dependency><groupId>transitive-test</groupId><artifactId>" + 
artifactId + "</artifactId>" + "<version>"
+                + version + "</version>" + extra + "</dependency>";
+    }
+
+    private static ArtifactItem transitiveItem(String artifactId, String 
version) {
+        ArtifactItem item = new ArtifactItem();
+        item.setGroupId("transitive-test");
+        item.setArtifactId(artifactId);
+        item.setVersion(version);
+        return item;
+    }
+
+    private static List<String> copiedFiles(File outputDirectory) {
+        // files only: a directory created for an item's output path is not a 
copied artifact
+        String[] names = outputDirectory.list((dir, name) -> new File(dir, 
name).isFile());
+        List<String> files = names == null ? new ArrayList<>() : new 
ArrayList<>(Arrays.asList(names));
+        Collections.sort(files);
+        return files;
+    }
+
+    @Test
+    @InjectMojo(goal = "copy")
+    @MojoParameter(name = "transitive", value = "true")
+    void testTransitiveMultipleItemsCopySharedDependencyOnce(CopyMojo mojo) 
throws Exception {
+        File repo = new File(tempDir, "transitive-multi-repo");
+        installRemoteArtifactWithPom(repo, "transitive-test", "shared", "1.0", 
null);
+        installRemoteArtifactWithPom(repo, "transitive-test", "shared", "2.0", 
null);
+        installRemoteArtifactWithPom(repo, "transitive-test", "first", "1.0", 
dependencyXml("shared", "1.0", ""));
+        installRemoteArtifactWithPom(repo, "transitive-test", "second", "1.0", 
dependencyXml("shared", "2.0", ""));
+
+        mojo.setArtifactItems(Arrays.asList(transitiveItem("first", "1.0"), 
transitiveItem("second", "1.0")));
+        
mojo.setRemoteRepositories(Collections.singletonList("transitive-multi-repo::default::"
 + repo.toURI()));
+
+        mojo.execute();
+
+        // both shared versions are at the same depth, so the one reached 
through the first item wins
+        assertEquals(
+                Arrays.asList("first-1.0.jar", "second-1.0.jar", 
"shared-1.0.jar"),
+                copiedFiles(mojo.getOutputDirectory()));
+    }
+
+    @Test
+    @InjectMojo(goal = "copy")
+    @MojoParameter(name = "transitive", value = "true")
+    void 
testTransitiveMultipleItemsLeaveOutTestAndOptionalDependencies(CopyMojo mojo) 
throws Exception {
+        File repo = new File(tempDir, "transitive-scope-repo");
+        installRemoteArtifactWithPom(repo, "transitive-test", "runtime-dep", 
"1.0", null);
+        installRemoteArtifactWithPom(repo, "transitive-test", "test-dep", 
"1.0", null);
+        installRemoteArtifactWithPom(repo, "transitive-test", "optional-dep", 
"1.0", null);
+        installRemoteArtifactWithPom(
+                repo,
+                "transitive-test",
+                "first",
+                "1.0",
+                dependencyXml("runtime-dep", "1.0", "<scope>runtime</scope>")
+                        + dependencyXml("test-dep", "1.0", 
"<scope>test</scope>")
+                        + dependencyXml("optional-dep", "1.0", 
"<optional>true</optional>"));
+        installRemoteArtifactWithPom(repo, "transitive-test", "second", "1.0", 
null);
+
+        mojo.setArtifactItems(Arrays.asList(transitiveItem("first", "1.0"), 
transitiveItem("second", "1.0")));
+        
mojo.setRemoteRepositories(Collections.singletonList("transitive-scope-repo::default::"
 + repo.toURI()));
+
+        mojo.execute();
+
+        assertEquals(
+                Arrays.asList("first-1.0.jar", "runtime-dep-1.0.jar", 
"second-1.0.jar"),
+                copiedFiles(mojo.getOutputDirectory()));
+    }
+
+    @Test
+    @InjectMojo(goal = "copy")
+    @MojoParameter(name = "transitive", value = "true")
+    void testTransitiveSingleItemKeepsItsOptionalDependencies(CopyMojo mojo) 
throws Exception {
+        File repo = new File(tempDir, "transitive-single-scope-repo");
+        installRemoteArtifactWithPom(repo, "transitive-test", "runtime-dep", 
"1.0", null);
+        installRemoteArtifactWithPom(repo, "transitive-test", "test-dep", 
"1.0", null);
+        installRemoteArtifactWithPom(repo, "transitive-test", "optional-dep", 
"1.0", null);
+        installRemoteArtifactWithPom(
+                repo,
+                "transitive-test",
+                "first",
+                "1.0",
+                dependencyXml("runtime-dep", "1.0", "<scope>runtime</scope>")
+                        + dependencyXml("test-dep", "1.0", 
"<scope>test</scope>")
+                        + dependencyXml("optional-dep", "1.0", 
"<optional>true</optional>"));
+
+        mojo.setArtifact("transitive-test:first:1.0");
+        
mojo.setRemoteRepositories(Collections.singletonList("transitive-single-scope-repo::default::"
 + repo.toURI()));
+
+        mojo.execute();
+
+        // a single artifact is the root of the graph, as for dependency:get, 
so its optional dependencies stay in
+        assertEquals(
+                Arrays.asList("first-1.0.jar", "optional-dep-1.0.jar", 
"runtime-dep-1.0.jar"),
+                copiedFiles(mojo.getOutputDirectory()));
+    }
+
     @Test
     @InjectMojo(goal = "copy")
     @MojoParameter(name = "transitive", value = "true")
-    void testTransitiveRejectsMultipleArtifactItems(CopyMojo mojo) {
-        ArtifactItem first = new ArtifactItem();
-        first.setGroupId("transitive-test");
-        first.setArtifactId("root");
-        first.setVersion("1.0");
-        ArtifactItem second = new ArtifactItem();
-        second.setGroupId("transitive-test");
-        second.setArtifactId("leaf");
-        second.setVersion("1.0");
+    void 
testTransitiveAcceptsTheSameItemTwiceAndEquivalentDirectories(CopyMojo mojo) 
throws Exception {
+        File repo = new File(tempDir, "transitive-twice-repo");
+        installRemoteArtifactWithPom(repo, "transitive-test", "first", "1.0", 
null);
+        
mojo.setRemoteRepositories(Collections.singletonList("transitive-twice-repo::default::"
 + repo.toURI()));
+        ArtifactItem second = transitiveItem("first", "1.0");
+        second.setOutputDirectory(new File(new File(mojo.getOutputDirectory(), 
"sub"), ".."));
+        mojo.setArtifactItems(Arrays.asList(transitiveItem("first", "1.0"), 
second));
+
+        mojo.execute();
+
+        assertEquals(Collections.singletonList("first-1.0.jar"), 
copiedFiles(mojo.getOutputDirectory()));
+    }
+
+    @Test
+    @InjectMojo(goal = "copy")
+    @MojoParameter(name = "transitive", value = "true")
+    void testTransitiveRejectsDifferentOutputDirectories(CopyMojo mojo) throws 
Exception {
+        File repo = new File(tempDir, "transitive-dirs-repo");
+        installRemoteArtifactWithPom(repo, "transitive-test", "first", "1.0", 
null);
+        installRemoteArtifactWithPom(repo, "transitive-test", "second", "1.0", 
null);
+        
mojo.setRemoteRepositories(Collections.singletonList("transitive-dirs-repo::default::"
 + repo.toURI()));
+        ArtifactItem first = transitiveItem("first", "1.0");
+        ArtifactItem second = transitiveItem("second", "1.0");
+        second.setOutputDirectory(new File(tempDir, "elsewhere"));
         mojo.setArtifactItems(Arrays.asList(first, second));
 
         MojoFailureException e = assertThrows(MojoFailureException.class, 
mojo::execute);
 
-        assertTrue(e.getMessage().contains("transitive"), e.getMessage());
+        assertTrue(e.getMessage().contains("outputDirectory"), e.getMessage());
+    }
+
+    @Test
+    @InjectMojo(goal = "copy")
+    @MojoParameter(name = "transitive", value = "true")
+    void testTransitiveRejectsOneArtifactInTwoVersions(CopyMojo mojo) throws 
Exception {
+        File repo = new File(tempDir, "transitive-versions-repo");
+        installRemoteArtifactWithPom(repo, "transitive-test", "first", "1.0", 
null);
+        installRemoteArtifactWithPom(repo, "transitive-test", "first", "2.0", 
null);
+        
mojo.setRemoteRepositories(Collections.singletonList("transitive-versions-repo::default::"
 + repo.toURI()));
+        mojo.setArtifactItems(Arrays.asList(transitiveItem("first", "1.0"), 
transitiveItem("first", "2.0")));
+
+        MojoFailureException e = assertThrows(MojoFailureException.class, 
mojo::execute);
+
+        assertTrue(e.getMessage().contains("different versions"), 
e.getMessage());
     }
 
     @Test

Reply via email to