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

commit 636b8e7dce772888016ce793fba464f6ca5bdb87
Author: Sylwester Lachiewicz <[email protected]>
AuthorDate: Sat Nov 14 13:08:54 2026 +0100

    [MDEP-746] Add get-classpath goal
---
 src/it/mrm/repository/get-classpath-lib-1.0.pom    |  56 +++++
 .../mrm/repository/get-classpath-lib-dep-1.0.pom   |  38 ++++
 .../mrm/repository/get-classpath-lib-leaf-1.0.pom  |  30 +++
 .../repository/get-classpath-lib-optional-1.0.pom  |  30 +++
 .../repository/get-classpath-lib-provided-1.0.pom  |  30 +++
 .../mrm/repository/get-classpath-lib-test-1.0.pom  |  30 +++
 src/it/projects/get-classpath/invoker.properties   |  20 ++
 src/it/projects/get-classpath/pom.xml              |  37 ++++
 src/it/projects/get-classpath/verify.groovy        |  46 +++++
 .../maven/plugins/dependency/GetClasspathMojo.java | 225 +++++++++++++++++++++
 .../plugins/dependency/utils/ResolverUtil.java     |  29 +++
 src/site/markdown/index.md                         |   1 +
 src/site/markdown/usage.md.vm                      |  13 ++
 .../plugins/dependency/GetClasspathMojoTest.java   | 187 +++++++++++++++++
 14 files changed, 772 insertions(+)

diff --git a/src/it/mrm/repository/get-classpath-lib-1.0.pom 
b/src/it/mrm/repository/get-classpath-lib-1.0.pom
new file mode 100644
index 00000000..a4ac4e2e
--- /dev/null
+++ b/src/it/mrm/repository/get-classpath-lib-1.0.pom
@@ -0,0 +1,56 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ 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.
+  -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0";
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd";>
+  <modelVersion>4.0.0</modelVersion>
+
+  <groupId>org.apache.maven.its.dependency</groupId>
+  <artifactId>get-classpath-lib</artifactId>
+  <version>1.0</version>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.apache.maven.its.dependency</groupId>
+      <artifactId>get-classpath-lib-dep</artifactId>
+      <version>1.0</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.maven.its.dependency</groupId>
+      <artifactId>get-classpath-lib-test</artifactId>
+      <version>1.0</version>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.maven.its.dependency</groupId>
+      <artifactId>get-classpath-lib-provided</artifactId>
+      <version>1.0</version>
+      <scope>provided</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.maven.its.dependency</groupId>
+      <artifactId>get-classpath-lib-optional</artifactId>
+      <version>1.0</version>
+      <optional>true</optional>
+    </dependency>
+  </dependencies>
+
+</project>
diff --git a/src/it/mrm/repository/get-classpath-lib-dep-1.0.pom 
b/src/it/mrm/repository/get-classpath-lib-dep-1.0.pom
new file mode 100644
index 00000000..9f7984b7
--- /dev/null
+++ b/src/it/mrm/repository/get-classpath-lib-dep-1.0.pom
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ 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.
+  -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0";
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd";>
+  <modelVersion>4.0.0</modelVersion>
+
+  <groupId>org.apache.maven.its.dependency</groupId>
+  <artifactId>get-classpath-lib-dep</artifactId>
+  <version>1.0</version>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.apache.maven.its.dependency</groupId>
+      <artifactId>get-classpath-lib-leaf</artifactId>
+      <version>1.0</version>
+    </dependency>
+  </dependencies>
+
+</project>
diff --git a/src/it/mrm/repository/get-classpath-lib-leaf-1.0.pom 
b/src/it/mrm/repository/get-classpath-lib-leaf-1.0.pom
new file mode 100644
index 00000000..9ff0b142
--- /dev/null
+++ b/src/it/mrm/repository/get-classpath-lib-leaf-1.0.pom
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ 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.
+  -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0";
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd";>
+  <modelVersion>4.0.0</modelVersion>
+
+  <groupId>org.apache.maven.its.dependency</groupId>
+  <artifactId>get-classpath-lib-leaf</artifactId>
+  <version>1.0</version>
+
+</project>
diff --git a/src/it/mrm/repository/get-classpath-lib-optional-1.0.pom 
b/src/it/mrm/repository/get-classpath-lib-optional-1.0.pom
new file mode 100644
index 00000000..58130d8f
--- /dev/null
+++ b/src/it/mrm/repository/get-classpath-lib-optional-1.0.pom
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ 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.
+  -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0";
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd";>
+  <modelVersion>4.0.0</modelVersion>
+
+  <groupId>org.apache.maven.its.dependency</groupId>
+  <artifactId>get-classpath-lib-optional</artifactId>
+  <version>1.0</version>
+
+</project>
diff --git a/src/it/mrm/repository/get-classpath-lib-provided-1.0.pom 
b/src/it/mrm/repository/get-classpath-lib-provided-1.0.pom
new file mode 100644
index 00000000..523ba818
--- /dev/null
+++ b/src/it/mrm/repository/get-classpath-lib-provided-1.0.pom
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ 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.
+  -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0";
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd";>
+  <modelVersion>4.0.0</modelVersion>
+
+  <groupId>org.apache.maven.its.dependency</groupId>
+  <artifactId>get-classpath-lib-provided</artifactId>
+  <version>1.0</version>
+
+</project>
diff --git a/src/it/mrm/repository/get-classpath-lib-test-1.0.pom 
b/src/it/mrm/repository/get-classpath-lib-test-1.0.pom
new file mode 100644
index 00000000..30c88b6c
--- /dev/null
+++ b/src/it/mrm/repository/get-classpath-lib-test-1.0.pom
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ 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.
+  -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0";
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd";>
+  <modelVersion>4.0.0</modelVersion>
+
+  <groupId>org.apache.maven.its.dependency</groupId>
+  <artifactId>get-classpath-lib-test</artifactId>
+  <version>1.0</version>
+
+</project>
diff --git a/src/it/projects/get-classpath/invoker.properties 
b/src/it/projects/get-classpath/invoker.properties
new file mode 100644
index 00000000..26bc8c96
--- /dev/null
+++ b/src/it/projects/get-classpath/invoker.properties
@@ -0,0 +1,20 @@
+# 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.
+
+# no project is needed, the artifact comes from -Dartifact
+invoker.goals.1 = 
${project.groupId}:${project.artifactId}:${project.version}:get-classpath 
-Dartifact=org.apache.maven.its.dependency:get-classpath-lib:1.0 
-Dmdep.outputFile=target/classpath.txt
+invoker.goals.2 = 
${project.groupId}:${project.artifactId}:${project.version}:get-classpath 
-Dartifact=org.apache.maven.its.dependency:get-classpath-lib:1.0 
-Dtransitive=false -Dmdep.outputFile=target/classpath-no-transitive.txt
diff --git a/src/it/projects/get-classpath/pom.xml 
b/src/it/projects/get-classpath/pom.xml
new file mode 100644
index 00000000..63f7984f
--- /dev/null
+++ b/src/it/projects/get-classpath/pom.xml
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+  ~ 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.
+  -->
+  
+<project xmlns="http://maven.apache.org/POM/4.0.0";
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd";>
+
+  <modelVersion>4.0.0</modelVersion>
+
+  <groupId>org.apache.maven.plugins.dependency.its</groupId>
+  <artifactId>get-classpath</artifactId>
+  <version>1.0-SNAPSHOT</version>
+  <url>https://issues.apache.org/jira/browse/MDEP-746</url>
+  <description>
+    Tests that get-classpath writes the classpath of an artifact named by 
-Dartifact, and of its runtime dependencies,
+    to the output file, in the order of the resolver, without test, provided 
and optional dependencies.
+  </description>
+
+</project>
diff --git a/src/it/projects/get-classpath/verify.groovy 
b/src/it/projects/get-classpath/verify.groovy
new file mode 100644
index 00000000..52be5a48
--- /dev/null
+++ b/src/it/projects/get-classpath/verify.groovy
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+import java.io.*;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+
+String jar( String artifactId )
+{
+    return new File( localRepositoryPath,
+        "org/apache/maven/its/dependency/" + artifactId + "/1.0/" + artifactId 
+ "-1.0.jar" ).getPath();
+}
+
+String read( String name )
+{
+    File file = new File( basedir, "target/" + name );
+    assert file.isFile() : "Missing file " + file;
+    return new String( Files.readAllBytes( file.toPath() ), 
StandardCharsets.UTF_8 );
+}
+
+// the artifact first, then its runtime dependencies in the order of the 
dependency graph; the test, provided
+// and optional dependencies of the artifact are not part of the classpath
+String expected = [ jar( "get-classpath-lib" ), jar( "get-classpath-lib-dep" 
), jar( "get-classpath-lib-leaf" ) ]
+    .join( File.pathSeparator );
+String actual = read( "classpath.txt" );
+assert actual.equals( expected ) : "Unexpected classpath: " + actual + ", 
expected: " + expected;
+
+String noTransitive = read( "classpath-no-transitive.txt" );
+assert noTransitive.equals( jar( "get-classpath-lib" ) ) : "Unexpected 
classpath: " + noTransitive;
+
+return true;
diff --git 
a/src/main/java/org/apache/maven/plugins/dependency/GetClasspathMojo.java 
b/src/main/java/org/apache/maven/plugins/dependency/GetClasspathMojo.java
new file mode 100644
index 00000000..0196aa1a
--- /dev/null
+++ b/src/main/java/org/apache/maven/plugins/dependency/GetClasspathMojo.java
@@ -0,0 +1,225 @@
+/*
+ * 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.plugins.dependency;
+
+import javax.inject.Inject;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.maven.RepositoryUtils;
+import org.apache.maven.plugin.AbstractMojo;
+import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugin.MojoFailureException;
+import org.apache.maven.plugins.annotations.Mojo;
+import org.apache.maven.plugins.annotations.Parameter;
+import org.apache.maven.plugins.dependency.utils.DependencyUtil;
+import org.apache.maven.plugins.dependency.utils.ParamArtifact;
+import org.apache.maven.plugins.dependency.utils.ResolverUtil;
+import org.eclipse.aether.artifact.Artifact;
+import org.eclipse.aether.repository.RemoteRepository;
+import org.eclipse.aether.repository.RepositoryPolicy;
+import org.eclipse.aether.resolution.ArtifactDescriptorException;
+import org.eclipse.aether.resolution.ArtifactResolutionException;
+import org.eclipse.aether.resolution.DependencyResolutionException;
+
+/**
+ * Resolves a single artifact, given by its coordinates, together with its 
transitive runtime dependencies, and outputs
+ * the classpath string of the resolved files from the local repository to a 
file or log. It combines
+ * <code>dependency:get</code>, which needs no project, with 
<code>dependency:build-classpath</code>. Use it to get
+ * the classpath of an ad-hoc artifact from the command line:
+ * <pre>
+ * mvn dependency:get-classpath -Dartifact=org.apache.maven:maven-model:3.9.9 
-Dmdep.outputFile=cp.txt
+ * </pre>
+ * The artifact itself comes first in the classpath, followed by its 
dependencies in the order in which the resolver
+ * of the running Maven returns them, which may differ between Maven versions. 
Test and provided dependencies, and
+ * optional ones, are not part of the classpath. As 
<code>dependency:get</code> does, this goal always checks the
+ * central repository defined in the super POM. You could use a mirror entry 
in your <code>settings.xml</code>.
+ *
+ * @since 3.12.0
+ */
+@Mojo(name = "get-classpath", requiresProject = false, threadSafe = true)
+public class GetClasspathMojo extends AbstractMojo {
+
+    private final ResolverUtil resolverUtil;
+
+    private final ParamArtifact paramArtifact = new ParamArtifact();
+
+    /**
+     * Repositories in the format {@code id::[layout::]url} or just URLs, 
separated by comma. That is,
+     * <code>
+     * 
central::default::https://repo.maven.apache.org/maven2,myrepo::https://repo.acme.com,https://repo.acme2.com
+     * </code>
+     * <p>
+     * The comma-separated form works both on the command line and as the text 
of a single
+     * <code>&lt;remoteRepositories&gt;</code> element. In a POM the 
repositories may also be listed one per element.
+     */
+    @Parameter(property = "remoteRepositories")
+    private List<String> remoteRepositories;
+
+    /**
+     * Resolve transitively, putting the artifact and all of its runtime 
dependencies on the classpath. If
+     * {@code false}, the classpath holds the artifact only.
+     */
+    @Parameter(property = "transitive", defaultValue = "true")
+    private boolean transitive = true;
+
+    /**
+     * If defined, the file to which the classpath string will be written. If 
not set, the classpath will be logged at
+     * INFO level.
+     */
+    @Parameter(property = "mdep.outputFile")
+    private File outputFile;
+
+    /**
+     * The prefix to prepend on each file name of the classpath. If undefined, 
the paths refer to the actual files
+     * stored in the local repository.
+     */
+    @Parameter(property = "mdep.prefix")
+    private String prefix;
+
+    /**
+     * Override the char used between the paths. The default is the 
system-dependent path-separator character: ':' on
+     * UNIX systems, ';' on Microsoft Windows systems.
+     */
+    @Parameter(property = "mdep.pathSeparator", defaultValue = "")
+    private String pathSeparator;
+
+    /**
+     * Override the char used between path folders. The default is the 
system-dependent file-separator character: '/'
+     * on UNIX systems, '\' on Microsoft Windows systems.
+     */
+    @Parameter(property = "mdep.fileSeparator", defaultValue = "")
+    private String fileSeparator;
+
+    /**
+     * Write out the classpath in a format compatible with filtering 
(<code>classpath=xxxxx</code>).
+     */
+    @Parameter(property = "mdep.outputFilterFile", defaultValue = "false")
+    private boolean outputFilterFile;
+
+    /**
+     * Skip plugin execution completely.
+     */
+    @Parameter(property = "mdep.skip", defaultValue = "false")
+    private boolean skip;
+
+    @Inject
+    public GetClasspathMojo(ResolverUtil resolverUtil) {
+        this.resolverUtil = resolverUtil;
+    }
+
+    @Override
+    public void execute() throws MojoExecutionException, MojoFailureException {
+        if (skip) {
+            getLog().info("Skipping plugin execution");
+            return;
+        }
+
+        if (paramArtifact.getArtifact() == null) {
+            throw new MojoFailureException("You must specify an artifact, "
+                    + "e.g. 
-Dartifact=org.apache.maven.plugins:maven-downloader-plugin:1.0");
+        }
+
+        List<Artifact> artifacts;
+        try {
+            Artifact artifact = 
resolverUtil.createArtifactFromParams(paramArtifact);
+            List<RemoteRepository> repositories =
+                    resolverUtil.remoteRepositories(remoteRepositories, 
RepositoryPolicy.UPDATE_POLICY_ALWAYS);
+            getLog().info("Resolving " + artifact + (transitive ? " with 
transitive dependencies" : ""));
+            artifacts = resolverUtil.resolveArtifactAndDependencies(artifact, 
repositories, transitive);
+        } catch (IllegalArgumentException e) {
+            throw new MojoFailureException(e.getMessage(), e);
+        } catch (ArtifactResolutionException | ArtifactDescriptorException | 
DependencyResolutionException e) {
+            throw new MojoExecutionException("Couldn't resolve artifact: " + 
e.getMessage(), e);
+        }
+
+        String classpath = toClasspath(artifacts);
+        if (outputFilterFile) {
+            classpath = "classpath=" + classpath;
+        }
+
+        if (outputFile == null) {
+            getLog().info("Classpath:" + System.lineSeparator() + classpath);
+        } else {
+            writeClasspathFile(classpath);
+        }
+    }
+
+    private String toClasspath(List<Artifact> artifacts) throws 
MojoExecutionException {
+        String separator = pathSeparator != null && !pathSeparator.isEmpty() ? 
pathSeparator : File.pathSeparator;
+
+        List<String> paths = new ArrayList<>(artifacts.size());
+        for (Artifact artifact : artifacts) {
+            paths.add(toPath(artifact));
+        }
+        return String.join(separator, paths);
+    }
+
+    private String toPath(Artifact artifact) throws MojoExecutionException {
+        String path;
+        if (prefix == null) {
+            File file = artifact.getFile();
+            if (file == null) {
+                throw new MojoExecutionException(artifact + " has no file");
+            }
+            path = file.getPath();
+        } else {
+            path = prefix
+                    + File.separator
+                    + DependencyUtil.getFormattedFileName(
+                            RepositoryUtils.toArtifact(artifact), false, 
false, true, false);
+        }
+        if (fileSeparator != null && !fileSeparator.isEmpty()) {
+            path = path.replaceAll(Pattern.quote(File.separator), 
Matcher.quoteReplacement(fileSeparator));
+        }
+        return path;
+    }
+
+    private void writeClasspathFile(String classpath) throws 
MojoExecutionException {
+        File parent = outputFile.getAbsoluteFile().getParentFile();
+        try {
+            Files.createDirectories(parent.toPath());
+            Files.write(outputFile.toPath(), 
classpath.getBytes(StandardCharsets.UTF_8));
+        } catch (IOException e) {
+            throw new MojoExecutionException("Error while writing to classpath 
file '" + outputFile + "'", e);
+        }
+        getLog().info("Wrote classpath file '" + outputFile + "'.");
+    }
+
+    /**
+     * A string of the form 
<code>groupId:artifactId:version[:packaging[:classifier]]</code>, or the form 
that
+     * Maven's error messages and <code>dependency:list</code> print,
+     * <code>groupId:artifactId:type[:classifier]:version[:scope]</code>; see 
the <code>artifact</code> parameter of
+     * <code>dependency:get</code> for how the two are told apart. The scope 
is ignored. The goal fails if it is not
+     * set.
+     *
+     * @param artifact the artifact coordinates
+     */
+    @Parameter(property = "artifact")
+    public void setArtifact(String artifact) {
+        paramArtifact.setArtifact(artifact);
+    }
+}
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 770b3654..d8458cba 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
@@ -308,6 +308,35 @@ public class ResolverUtil {
         return resolveDependencies(artifact, null, repositories);
     }
 
+    /**
+     * Resolve an artifact that is named by its coordinates alone, that is, 
without a project, and optionally its
+     * transitive dependencies, the way {@code dependency:get} does. The 
transitive dependencies are those of the
+     * runtime classpath: test and provided dependencies, and optional ones, 
are left out.
+     *
+     * @param artifact     an artifact to resolve
+     * @param repositories remote repositories list
+     * @param transitive   whether to resolve the dependencies of the artifact 
as well
+     * @return the resolved artifacts, each with its file set. The artifact 
itself comes first, followed by its
+     *         dependencies in the order in which the resolver of the running 
Maven returns them, which may differ
+     *         between Maven versions. With {@code transitive} set to {@code 
false} the list holds the artifact only.
+     * @throws ArtifactResolutionException   if the artifact could not be 
resolved
+     * @throws ArtifactDescriptorException   if the descriptor of the artifact 
could not be read
+     * @throws DependencyResolutionException if the dependency tree could not 
be built or any dependency artifact could
+     *                                       not be resolved
+     */
+    public List<Artifact> resolveArtifactAndDependencies(
+            Artifact artifact, List<RemoteRepository> repositories, boolean 
transitive)
+            throws ArtifactResolutionException, ArtifactDescriptorException, 
DependencyResolutionException {
+        if (transitive) {
+            // The artifact is a direct dependency of a rootless request, so 
the session's selectors treat its own
+            // dependencies as transitive ones: test, provided and optional 
dependencies stay out.
+            CollectRequest collectRequest =
+                    new CollectRequest(Collections.singletonList(new 
Dependency(artifact, null)), null, repositories);
+            return resolveDependencies(collectRequest, null);
+        }
+        return Collections.singletonList(resolveArtifact(artifact, 
repositories));
+    }
+
     /**
      * Resolve transitive dependencies for artifact.
      *
diff --git a/src/site/markdown/index.md b/src/site/markdown/index.md
index 1efd1fb0..8d5db8ed 100644
--- a/src/site/markdown/index.md
+++ b/src/site/markdown/index.md
@@ -46,6 +46,7 @@ The Dependency plugin has several goals:
 - [dependency:copy-dependencies](./copy-dependencies-mojo.html) takes the list 
of project direct dependencies and optionally transitive dependencies and 
copies them to a specified location, stripping the version if desired. This 
goal can also be run from the command line.
 - [dependency:display-ancestors](./display-ancestors-mojo.html) displays all 
ancestor POMs of the project. This may be useful in a continuous integration 
system where you want to know all parent poms of the project. This goal can 
also be run from the command line.
 - [dependency:get](./get-mojo.html) resolves a single artifact, eventually 
transitively, from a specified remote repository.
+- [dependency:get-classpath](./get-classpath-mojo.html) resolves a single 
artifact given by its coordinates, with its transitive runtime dependencies, 
and outputs the classpath string to a file or the log. Like `get`, it needs no 
project.
 - [dependency:go-offline](./go-offline-mojo.html) tells Maven to resolve 
everything this project is dependent on (dependencies, plugins, reports) in 
preparation for going offline.
 - [dependency:list](./list-mojo.html) alias for resolve that lists the 
dependencies for this project.
 - [dependency:list-classes](./list-classes-mojo.html) displays the fully 
package-qualified names of all classes found in a specified artifact.
diff --git a/src/site/markdown/usage.md.vm b/src/site/markdown/usage.md.vm
index a11ba7f9..4185fcd0 100644
--- a/src/site/markdown/usage.md.vm
+++ b/src/site/markdown/usage.md.vm
@@ -782,6 +782,19 @@ mvn dependency:get -DgroupId=org.apache.maven 
-DartifactId=maven-core -Dversion=
 mvn dependency:get -DgroupId=org.apache.maven -DartifactId=maven-core 
-Dversion=2.2.1 -Dpackaging=jar -Dclassifier=sources 
-DremoteRepositories=https://myrepo.com/maven2
 ```
 
+`dependency:get-classpath`
+-------------------------
+
+This goal resolves an artifact, given by its Maven coordinates, and its 
transitive runtime dependencies, and outputs the classpath string of the files 
in the local repository. It needs no project, so it works in any directory. Use 
it to get the classpath of an ad-hoc artifact for `java -cp`. The artifact 
comes first, followed by its dependencies in the order in which the resolver of 
the running Maven returns them, which may differ between Maven versions. Test, 
provided and optional depen [...]
+
+```
+mvn dependency:get-classpath -Dartifact=org.apache.maven:maven-model:3.9.9
+mvn dependency:get-classpath -Dartifact=org.apache.maven:maven-model:3.9.9 
-Dmdep.outputFile=classpath.txt
+mvn dependency:get-classpath -Dartifact=org.apache.maven:maven-model:3.9.9 
-Dtransitive=false -DremoteRepositories=https://myrepo.com/maven2
+```
+
+Without `mdep.outputFile` the classpath is logged at the INFO level. Use `-q` 
together with `mdep.outputFile` to keep the build output quiet. The separators 
and a path prefix can be changed with `mdep.pathSeparator`, 
`mdep.fileSeparator` and `mdep.prefix`, as for `dependency:build-classpath`.
+
 `dependency:analyze-exclusions`
 -------------------------------
 
diff --git 
a/src/test/java/org/apache/maven/plugins/dependency/GetClasspathMojoTest.java 
b/src/test/java/org/apache/maven/plugins/dependency/GetClasspathMojoTest.java
new file mode 100644
index 00000000..1301f849
--- /dev/null
+++ 
b/src/test/java/org/apache/maven/plugins/dependency/GetClasspathMojoTest.java
@@ -0,0 +1,187 @@
+/*
+ * 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.plugins.dependency;
+
+import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.Collections;
+
+import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugin.MojoFailureException;
+import org.apache.maven.plugins.dependency.utils.ParamArtifact;
+import org.apache.maven.plugins.dependency.utils.ResolverUtil;
+import org.eclipse.aether.artifact.Artifact;
+import org.eclipse.aether.artifact.DefaultArtifact;
+import org.eclipse.aether.repository.RemoteRepository;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class GetClasspathMojoTest {
+
+    private static final String SEP = File.pathSeparator;
+
+    @TempDir
+    private Path temp;
+
+    private ResolverUtil resolverUtil;
+
+    private GetClasspathMojo mojo;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        resolverUtil = mock(ResolverUtil.class);
+        
when(resolverUtil.createArtifactFromParams(any(ParamArtifact.class))).thenReturn(new
 DefaultArtifact("g:a:1"));
+        when(resolverUtil.remoteRepositories(any(), 
any())).thenReturn(Collections.<RemoteRepository>emptyList());
+        mojo = new GetClasspathMojo(resolverUtil);
+        mojo.setArtifact("g:a:1");
+    }
+
+    private Artifact resolved(String artifactId, String version) {
+        Path file =
+                
temp.resolve("repo").resolve(artifactId).resolve(version).resolve(artifactId + 
"-" + version + ".jar");
+        return new DefaultArtifact("g", artifactId, "jar", 
version).setFile(file.toFile());
+    }
+
+    private void resolverReturns(Artifact... artifacts) throws Exception {
+        when(resolverUtil.resolveArtifactAndDependencies(any(), any(), 
anyBoolean()))
+                .thenReturn(Arrays.asList(artifacts));
+    }
+
+    private void set(String field, Object value) throws Exception {
+        java.lang.reflect.Field f = 
GetClasspathMojo.class.getDeclaredField(field);
+        f.setAccessible(true);
+        f.set(mojo, value);
+    }
+
+    @Test
+    void writesClasspathInResolverOrder() throws Exception {
+        Artifact a = resolved("a", "1");
+        Artifact b = resolved("b", "2");
+        resolverReturns(a, b);
+        File out = temp.resolve("out/cp.txt").toFile();
+        set("outputFile", out);
+
+        mojo.execute();
+
+        assertEquals(
+                a.getFile().getPath() + SEP + b.getFile().getPath(),
+                new String(Files.readAllBytes(out.toPath()), 
StandardCharsets.UTF_8));
+        verify(resolverUtil).resolveArtifactAndDependencies(any(), any(), 
eq(true));
+    }
+
+    @Test
+    void transitiveFalseIsPassedOn() throws Exception {
+        resolverReturns(resolved("a", "1"));
+        set("transitive", false);
+        set("outputFile", temp.resolve("cp.txt").toFile());
+
+        mojo.execute();
+
+        verify(resolverUtil).resolveArtifactAndDependencies(any(), any(), 
eq(false));
+    }
+
+    @Test
+    void separatorsFilterAndPrefix() throws Exception {
+        resolverReturns(resolved("a", "1"), resolved("b", "2"));
+        File out = temp.resolve("cp.txt").toFile();
+        set("outputFile", out);
+        set("pathSeparator", ";");
+        set("prefix", "lib");
+        set("fileSeparator", "\\");
+        set("outputFilterFile", true);
+
+        mojo.execute();
+
+        assertEquals(
+                "classpath=lib\\a-1.jar;lib\\b-2.jar",
+                new String(Files.readAllBytes(out.toPath()), 
StandardCharsets.UTF_8));
+    }
+
+    @Test
+    void fileSeparatorReplacesSeparatorsInPaths() throws Exception {
+        Artifact a = resolved("a", "1");
+        resolverReturns(a);
+        File out = temp.resolve("cp.txt").toFile();
+        set("outputFile", out);
+        set("fileSeparator", "|");
+
+        mojo.execute();
+
+        assertEquals(
+                a.getFile().getPath().replace(File.separator, "|"),
+                new String(Files.readAllBytes(out.toPath()), 
StandardCharsets.UTF_8));
+    }
+
+    @Test
+    void withoutOutputFileNothingIsWritten() throws Exception {
+        resolverReturns(resolved("a", "1"));
+
+        mojo.execute();
+
+        try (java.util.stream.Stream<Path> files = Files.list(temp)) {
+            assertEquals(Collections.<Path>emptyList(), 
files.collect(java.util.stream.Collectors.<Path>toList()));
+        }
+    }
+
+    @Test
+    void missingArtifactIsAFailure() throws Exception {
+        GetClasspathMojo noArtifact = new GetClasspathMojo(resolverUtil);
+
+        assertThrows(MojoFailureException.class, noArtifact::execute);
+        verify(resolverUtil, never()).resolveArtifactAndDependencies(any(), 
any(), anyBoolean());
+    }
+
+    @Test
+    void invalidCoordinatesAreAFailure() throws Exception {
+        when(resolverUtil.createArtifactFromParams(any())).thenThrow(new 
IllegalArgumentException("bad"));
+
+        assertThrows(MojoFailureException.class, mojo::execute);
+    }
+
+    @Test
+    void resolutionProblemIsAnExecutionError() throws Exception {
+        when(resolverUtil.resolveArtifactAndDependencies(any(), any(), 
anyBoolean()))
+                .thenThrow(new 
org.eclipse.aether.resolution.DependencyResolutionException(null, "nope", 
null));
+
+        assertThrows(MojoExecutionException.class, mojo::execute);
+    }
+
+    @Test
+    void skipDoesNothing() throws Exception {
+        set("skip", true);
+
+        mojo.execute();
+
+        verify(resolverUtil, never()).resolveArtifactAndDependencies(any(), 
any(), anyBoolean());
+    }
+}

Reply via email to