diff --git a/.github/workflows/maven-verify.yml b/.github/workflows/maven-verify.yml
index 065619be..56062b54 100644
--- a/.github/workflows/maven-verify.yml
+++ b/.github/workflows/maven-verify.yml
@@ -26,5 +26,6 @@ jobs:
name: Verify
uses: apache/maven-gh-actions-shared/.github/workflows/maven-verify.yml@v4
with:
- maven4-enabled: true
-
+ ff-maven: "4.0.0-beta-3" # Maven version for fail-fast-build
+ maven-matrix: '[ "4.0.0-beta-3" ]'
+ jdk-matrix: '[ "17", "21" ]'
diff --git a/pom.xml b/pom.xml
index 14543269..ae5699cb 100644
--- a/pom.xml
+++ b/pom.xml
@@ -28,7 +28,7 @@ under the License.
maven-deploy-plugin
- 3.1.3-SNAPSHOT
+ 4.0.0-SNAPSHOT
maven-plugin
Apache Maven Deploy Plugin
@@ -43,7 +43,7 @@ under the License.
- 3.6.3
+ ${mavenVersion}
@@ -68,14 +68,10 @@ under the License.
- 8
- 3.9.6
-
- 1.7.36
-
- 1.9.20
+ 17
+ 4.0.0-beta-3
-
+ 6.0.0
${version.maven-antrun-plugin}
${version.maven-compiler-plugin}
${version.maven-enforcer-plugin}
@@ -87,139 +83,118 @@ under the License.
${version.maven-source-plugin}
${version.maven-surefire}
${version.maven-war-plugin}
+ 4.0.0-alpha-3-SNAPSHOT
+ 2.0.0-alpha-11
+ 5.12.0
+ 2.0.13
+ 4.0.3
+ 4.0.0-SNAPSHOT
+ 3.7.0
2024-04-26T10:30:44Z
+
+
+
+ com.google.guava
+ guava
+ 33.2.1-jre
+
+
+
+
org.apache.maven
- maven-plugin-api
+ maven-api-core
${mavenVersion}
provided
org.apache.maven
- maven-core
+ maven-api-di
${mavenVersion}
provided
org.apache.maven
- maven-model
+ maven-api-meta
${mavenVersion}
provided
org.apache.maven
- maven-artifact
+ maven-api-model
${mavenVersion}
provided
-
- org.slf4j
- slf4j-api
- ${slf4jVersion}
- provided
-
-
- org.codehaus.plexus
- plexus-utils
-
-
- org.codehaus.plexus
- plexus-xml
-
-
- org.apache.maven.resolver
- maven-resolver-api
- ${resolverVersion}
- provided
-
-
- org.apache.maven.resolver
- maven-resolver-util
- ${resolverVersion}
-
- compile
-
-
-
-
- org.apache.maven.plugin-tools
- maven-plugin-annotations
- provided
-
-
org.apache.maven.plugin-testing
maven-plugin-testing-harness
- 3.3.0
+ ${mavenPluginTestingVersion}
test
-
org.apache.maven
- maven-compat
+ maven-core
${mavenVersion}
test
- org.apache.maven
- maven-resolver-provider
- ${mavenVersion}
+ org.apache.maven.resolver
+ maven-resolver-api
+ ${mavenResolverVersion}
test
- org.apache.maven.resolver
- maven-resolver-connector-basic
- ${resolverVersion}
+ org.apache.maven
+ maven-api-impl
+ ${mavenVersion}
test
- org.apache.maven.resolver
- maven-resolver-transport-file
- ${resolverVersion}
+ com.google.inject
+ guice
+ ${guiceVersion}
test
- org.apache.maven.resolver
- maven-resolver-transport-http
- ${resolverVersion}
+ org.mockito
+ mockito-junit-jupiter
+ ${mockitoVersion}
test
org.mockito
mockito-core
- 4.11.0
+ ${mockitoVersion}
test
- junit
- junit
- 4.13.2
+ org.slf4j
+ slf4j-api
+ ${slf4jVersion}
test
org.slf4j
- slf4j-nop
+ slf4j-simple
${slf4jVersion}
test
+
+ org.junit.jupiter
+ junit-jupiter-api
+ test
+
+
-
- org.apache.maven.plugins
- maven-compiler-plugin
-
- none
- true
-
-
com.diffplug.spotless
spotless-maven-plugin
diff --git a/src/it/deploy-attached-sources/pom.xml b/src/it/deploy-attached-sources/pom.xml
index 4205241c..f5afec98 100644
--- a/src/it/deploy-attached-sources/pom.xml
+++ b/src/it/deploy-attached-sources/pom.xml
@@ -75,7 +75,7 @@ under the License.
@project.version@
- mine::default::file://${basedir}/target
+ mine::default::file://${project.basedir}/target
diff --git a/src/it/deploy-attached-sources/test.properties b/src/it/deploy-attached-sources/test.properties
index c1c2cd31..d9700072 100644
--- a/src/it/deploy-attached-sources/test.properties
+++ b/src/it/deploy-attached-sources/test.properties
@@ -16,10 +16,10 @@
# under the License.
# Properties passed to invocations of the deploy plugin
-pomFile = ${basedir}/pom.xml
+pomFile = ${project.basedir}/pom.xml
-file = ${basedir}/target/${project.artifactId}-${project.version}.jar
-sources = ${basedir}/target/${project.artifactId}-${project.version}-sources.jar
-javadoc = ${basedir}/target/${project.artifactId}-${project.version}-javadoc.jar
+file = ${project.basedir}/target/${project.artifactId}-${project.version}.jar
+sources = ${project.basedir}/target/${project.artifactId}-${project.version}-sources.jar
+javadoc = ${project.basedir}/target/${project.artifactId}-${project.version}-javadoc.jar
-url = file://${basedir}/target/repo
+url = file://${project.basedir}/target/repo
diff --git a/src/it/deploy-default-packaging/pom.xml b/src/it/deploy-default-packaging/pom.xml
index e452c7cd..ff46461c 100644
--- a/src/it/deploy-default-packaging/pom.xml
+++ b/src/it/deploy-default-packaging/pom.xml
@@ -75,7 +75,7 @@ under the License.
@project.version@
- mine::default::file://${basedir}/target
+ mine::default::file://${project.basedir}/target
diff --git a/src/it/deploy-default-packaging/test.properties b/src/it/deploy-default-packaging/test.properties
index d663c307..5e05d5fa 100644
--- a/src/it/deploy-default-packaging/test.properties
+++ b/src/it/deploy-default-packaging/test.properties
@@ -19,5 +19,5 @@
groupId = org.apache.maven.test
artifactId = test
version = 1.1
-file = ${basedir}/lib/test-1.1.jar
-url = file://${basedir}/target/repo
+file = ${project.basedir}/lib/test-1.1.jar
+url = file://${project.basedir}/target/repo
diff --git a/src/it/gav-validation/invoker.properties b/src/it/gav-validation/invoker.properties
index 6635374e..051dc7ed 100644
--- a/src/it/gav-validation/invoker.properties
+++ b/src/it/gav-validation/invoker.properties
@@ -18,5 +18,5 @@
invoker.goals = org.apache.maven.plugins:maven-deploy-plugin:${project.version}:deploy-file
invoker.buildResult = failure
-invoker.systemPropertiesFile.1 = test-invalid.properties
-invoker.systemPropertiesFile.2 = test-missing.properties
+invoker.userPropertiesFile.1 = test-invalid.properties
+invoker.userPropertiesFile.2 = test-missing.properties
diff --git a/src/it/settings.xml b/src/it/settings.xml
index 7467f662..7fe15992 100644
--- a/src/it/settings.xml
+++ b/src/it/settings.xml
@@ -32,9 +32,11 @@ under the License.
@localRepositoryUrl@
true
+ ignore
true
+ ignore
@@ -44,9 +46,11 @@ under the License.
@localRepositoryUrl@
true
+ ignore
true
+ ignore
diff --git a/src/main/java/org/apache/maven/plugins/deploy/AbstractDeployMojo.java b/src/main/java/org/apache/maven/plugins/deploy/AbstractDeployMojo.java
index d8da6922..7612a690 100644
--- a/src/main/java/org/apache/maven/plugins/deploy/AbstractDeployMojo.java
+++ b/src/main/java/org/apache/maven/plugins/deploy/AbstractDeployMojo.java
@@ -18,25 +18,29 @@
*/
package org.apache.maven.plugins.deploy;
-import org.apache.maven.execution.MavenSession;
-import org.apache.maven.plugin.AbstractMojo;
-import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.plugin.MojoFailureException;
-import org.apache.maven.plugins.annotations.Component;
-import org.apache.maven.plugins.annotations.Parameter;
-import org.apache.maven.rtinfo.RuntimeInformation;
-import org.eclipse.aether.RepositorySystem;
-import org.eclipse.aether.deployment.DeployRequest;
-import org.eclipse.aether.deployment.DeploymentException;
-import org.eclipse.aether.repository.RemoteRepository;
-import org.eclipse.aether.util.version.GenericVersionScheme;
-import org.eclipse.aether.version.InvalidVersionSpecificationException;
-import org.eclipse.aether.version.Version;
+import org.apache.maven.api.RemoteRepository;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Version;
+import org.apache.maven.api.di.Inject;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.Mojo;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.plugin.annotations.Parameter;
/**
* Abstract class for Deploy mojo's.
*/
-public abstract class AbstractDeployMojo extends AbstractMojo {
+public abstract class AbstractDeployMojo implements Mojo {
+ private static final String AFFECTED_MAVEN_PACKAGING = "maven-plugin";
+
+ private static final String FIXED_MAVEN_VERSION = "3.9.0";
+
+ @Inject
+ protected Log logger;
+
+ @Inject
+ protected Session session;
+
/**
* Flag whether Maven is currently in online/offline mode.
*/
@@ -52,45 +56,31 @@ public abstract class AbstractDeployMojo extends AbstractMojo {
@Parameter(property = "retryFailedDeploymentCount", defaultValue = "1")
private int retryFailedDeploymentCount;
- @Component
- private RuntimeInformation runtimeInformation;
-
- @Parameter(defaultValue = "${session}", readonly = true, required = true)
- protected MavenSession session;
-
- @Component
- protected RepositorySystem repositorySystem;
-
- private static final String AFFECTED_MAVEN_PACKAGING = "maven-plugin";
-
- private static final String FIXED_MAVEN_VERSION = "3.9.0";
-
/* Setters and Getters */
- void failIfOffline() throws MojoFailureException {
+ void failIfOffline() throws MojoException {
if (offline) {
- throw new MojoFailureException("Cannot deploy artifacts when Maven is in offline mode");
+ throw new MojoException("Cannot deploy artifacts when Maven is in offline mode");
}
}
+ public int getRetryFailedDeploymentCount() {
+ return retryFailedDeploymentCount;
+ }
+
/**
* If this plugin used in pre-3.9.0 Maven, the packaging {@code maven-plugin} will not deploy G level metadata.
*/
- protected void warnIfAffectedPackagingAndMaven(final String packaging) {
+ protected void warnIfAffectedPackagingAndMaven(String packaging) {
if (AFFECTED_MAVEN_PACKAGING.equals(packaging)) {
- try {
- GenericVersionScheme versionScheme = new GenericVersionScheme();
- Version fixedMavenVersion = versionScheme.parseVersion(FIXED_MAVEN_VERSION);
- Version currentMavenVersion = versionScheme.parseVersion(runtimeInformation.getMavenVersion());
- if (fixedMavenVersion.compareTo(currentMavenVersion) > 0) {
- getLog().warn("");
- getLog().warn("You are about to deploy a maven-plugin using Maven " + currentMavenVersion + ".");
- getLog().warn("This plugin should be used ONLY with Maven 3.9.0 and newer, as MNG-7055");
- getLog().warn("is fixed in those versions of Maven only!");
- getLog().warn("");
- }
- } catch (InvalidVersionSpecificationException e) {
- // skip it: Generic does not throw, only API contains this exception
+ Version fixedMavenVersion = session.parseVersion(FIXED_MAVEN_VERSION);
+ Version currentMavenVersion = session.getMavenVersion();
+ if (fixedMavenVersion.compareTo(currentMavenVersion) > 0) {
+ getLog().warn("");
+ getLog().warn("You are about to deploy a maven-plugin using Maven " + currentMavenVersion + ".");
+ getLog().warn("This plugin should be used ONLY with Maven 3.9.0 and newer, as MNG-7055");
+ getLog().warn("is fixed in those versions of Maven only!");
+ getLog().warn("");
}
}
}
@@ -98,60 +88,15 @@ protected void warnIfAffectedPackagingAndMaven(final String packaging) {
/**
* Creates resolver {@link RemoteRepository} equipped with needed whistles and bells.
*/
- protected RemoteRepository getRemoteRepository(final String repositoryId, final String url) {
- // TODO: RepositorySystem#newDeploymentRepository does this very same thing!
- RemoteRepository result = new RemoteRepository.Builder(repositoryId, "default", url).build();
-
- if (result.getAuthentication() == null || result.getProxy() == null) {
- RemoteRepository.Builder builder = new RemoteRepository.Builder(result);
-
- if (result.getAuthentication() == null) {
- builder.setAuthentication(session.getRepositorySession()
- .getAuthenticationSelector()
- .getAuthentication(result));
- }
-
- if (result.getProxy() == null) {
- builder.setProxy(
- session.getRepositorySession().getProxySelector().getProxy(result));
- }
-
- result = builder.build();
- }
-
- return result;
+ protected RemoteRepository createDeploymentArtifactRepository(String id, String url) {
+ return getSession().createRemoteRepository(id, url);
}
- // I'm not sure if retries will work with deploying on client level ...
- // Most repository managers block a duplicate artifacts.
-
- // Eg, when we have an artifact list, even simple pom and jar in one request with released version,
- // next try can fail due to duplicate.
-
- protected void deploy(DeployRequest deployRequest) throws MojoExecutionException {
- int retryFailedDeploymentCounter = Math.max(1, Math.min(10, retryFailedDeploymentCount));
- DeploymentException exception = null;
- for (int count = 0; count < retryFailedDeploymentCounter; count++) {
- try {
- if (count > 0) {
- getLog().info("Retrying deployment attempt " + (count + 1) + " of " + retryFailedDeploymentCounter);
- }
+ protected Session getSession() {
+ return session;
+ }
- repositorySystem.deploy(session.getRepositorySession(), deployRequest);
- exception = null;
- break;
- } catch (DeploymentException e) {
- if (count + 1 < retryFailedDeploymentCounter) {
- getLog().warn("Encountered issue during deployment: " + e.getLocalizedMessage());
- getLog().debug(e);
- }
- if (exception == null) {
- exception = e;
- }
- }
- }
- if (exception != null) {
- throw new MojoExecutionException(exception.getMessage(), exception);
- }
+ protected Log getLog() {
+ return logger;
}
}
diff --git a/src/main/java/org/apache/maven/plugins/deploy/DeployFileMojo.java b/src/main/java/org/apache/maven/plugins/deploy/DeployFileMojo.java
index 7e6536f1..400a496b 100644
--- a/src/main/java/org/apache/maven/plugins/deploy/DeployFileMojo.java
+++ b/src/main/java/org/apache/maven/plugins/deploy/DeployFileMojo.java
@@ -22,47 +22,42 @@
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
-import java.util.Enumeration;
-import java.util.Objects;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.util.ArrayList;
+import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
-import org.apache.maven.artifact.ArtifactUtils;
-import org.apache.maven.model.Model;
-import org.apache.maven.model.Parent;
-import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
-import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
-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.codehaus.plexus.util.FileUtils;
-import org.codehaus.plexus.util.IOUtil;
-import org.codehaus.plexus.util.StringUtils;
-import org.codehaus.plexus.util.xml.ReaderFactory;
-import org.codehaus.plexus.util.xml.WriterFactory;
-import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
-import org.eclipse.aether.RepositorySystemSession;
-import org.eclipse.aether.artifact.Artifact;
-import org.eclipse.aether.artifact.ArtifactType;
-import org.eclipse.aether.artifact.DefaultArtifact;
-import org.eclipse.aether.deployment.DeployRequest;
-import org.eclipse.aether.deployment.DeploymentException;
-import org.eclipse.aether.repository.RemoteRepository;
-import org.eclipse.aether.util.artifact.SubArtifact;
+import org.apache.maven.api.Artifact;
+import org.apache.maven.api.RemoteRepository;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.plugin.annotations.Mojo;
+import org.apache.maven.api.plugin.annotations.Parameter;
+import org.apache.maven.api.services.ArtifactDeployer;
+import org.apache.maven.api.services.ArtifactDeployerException;
+import org.apache.maven.api.services.ArtifactDeployerRequest;
+import org.apache.maven.api.services.ArtifactManager;
+import org.apache.maven.api.services.xml.ModelXmlFactory;
+import org.apache.maven.api.services.xml.XmlReaderException;
/**
* Installs the artifact in the remote repository.
*
* @author Allan Ramirez
*/
-@Mojo(name = "deploy-file", requiresProject = false, threadSafe = true)
+@Mojo(name = "deploy-file", projectRequired = false)
+@SuppressWarnings("unused")
public class DeployFileMojo extends AbstractDeployMojo {
+ private static final String TAR = "tar.";
+ private static final String ILLEGAL_VERSION_CHARS = "\\/:\"<>|?*[](){},";
+
/**
* GroupId of the artifact to be deployed. Retrieved from POM file if specified.
*/
@@ -100,7 +95,7 @@ public class DeployFileMojo extends AbstractDeployMojo {
* File to be deployed.
*/
@Parameter(property = "file", required = true)
- private File file;
+ Path file;
/**
* The bundled API docs for the artifact.
@@ -108,7 +103,7 @@ public class DeployFileMojo extends AbstractDeployMojo {
* @since 2.6
*/
@Parameter(property = "javadoc")
- private File javadoc;
+ private Path javadoc;
/**
* The bundled sources for the artifact.
@@ -116,7 +111,7 @@ public class DeployFileMojo extends AbstractDeployMojo {
* @since 2.6
*/
@Parameter(property = "sources")
- private File sources;
+ private Path sources;
/**
* Server Id to map on the <id> under <server> section of settings.xml In most cases, this parameter
@@ -136,7 +131,7 @@ public class DeployFileMojo extends AbstractDeployMojo {
* Location of an existing POM file to be deployed alongside the main artifact, given by the ${file} parameter.
*/
@Parameter(property = "pomFile")
- private File pomFile;
+ private Path pomFile;
/**
* Upload a POM for this artifact. Will generate a default POM if none is supplied with the pomFile argument.
@@ -185,143 +180,159 @@ public class DeployFileMojo extends AbstractDeployMojo {
@Parameter(property = "maven.deploy.file.skip", defaultValue = "false")
private String skip = Boolean.FALSE.toString();
- void initProperties() throws MojoExecutionException {
- if (pomFile == null) {
- boolean foundPom = false;
- try (JarFile jarFile = new JarFile(file)) {
- Pattern pomEntry = Pattern.compile("META-INF/maven/.*/pom\\.xml");
- Enumeration jarEntries = jarFile.entries();
+ void initProperties() throws MojoException {
+ Path deployedPom;
+ if (pomFile != null) {
+ deployedPom = pomFile;
+ processModel(readModel(deployedPom));
+ } else {
+ deployedPom = readingPomFromJarFile();
+ if (deployedPom != null) {
+ pomFile = deployedPom;
+ }
+ }
- while (jarEntries.hasMoreElements()) {
- JarEntry entry = jarEntries.nextElement();
+ if (packaging == null && file != null) {
+ packaging = getExtension(file);
+ }
+ }
- if (pomEntry.matcher(entry.getName()).matches()) {
- getLog().debug("Using " + entry.getName() + " as pomFile");
- foundPom = true;
- String base = file.getName();
+ private Path readingPomFromJarFile() {
+ Pattern pomEntry = Pattern.compile("META-INF/maven/.*/pom\\.xml");
+ try {
+ try (JarFile jarFile = new JarFile(file.toFile())) {
+ JarEntry entry = jarFile.stream()
+ .filter(e -> pomEntry.matcher(e.getName()).matches())
+ .findFirst()
+ .orElse(null);
+ if (entry != null) {
+ getLog().debug("Using " + entry.getName() + " as pomFile");
+
+ try (InputStream pomInputStream = jarFile.getInputStream(entry)) {
+ String base = file.getFileName().toString();
if (base.indexOf('.') > 0) {
base = base.substring(0, base.lastIndexOf('.'));
}
- pomFile = new File(file.getParentFile(), base + ".pom");
-
- try (InputStream pomInputStream = jarFile.getInputStream(entry)) {
- try (OutputStream pomOutputStream = Files.newOutputStream(pomFile.toPath())) {
- IOUtil.copy(pomInputStream, pomOutputStream);
- }
- processModel(readModel(pomFile));
- break;
- }
- }
- }
+ Path pomFile = File.createTempFile(base, ".pom").toPath();
- if (!foundPom) {
- getLog().info("pom.xml not found in " + file.getName());
+ Files.copy(pomInputStream, pomFile, StandardCopyOption.REPLACE_EXISTING);
+
+ processModel(readModel(pomFile));
+
+ return pomFile;
+ }
+ } else {
+ getLog().info("pom.xml not found in " + file.getFileName());
}
- } catch (IOException e) {
- // ignore, artifact not packaged by Maven
}
- } else {
- processModel(readModel(pomFile));
- }
-
- if (packaging == null && file != null) {
- packaging = getExtension(file);
+ } catch (IOException e) {
+ // ignore, artifact not packaged by Maven
}
+ return null;
}
- public void execute() throws MojoExecutionException, MojoFailureException {
+ public void execute() throws MojoException {
if (Boolean.parseBoolean(skip)
- || ("releases".equals(skip) && !ArtifactUtils.isSnapshot(version))
- || ("snapshots".equals(skip) && ArtifactUtils.isSnapshot(version))) {
+ || ("releases".equals(skip) && !session.isVersionSnapshot(version))
+ || ("snapshots".equals(skip) && session.isVersionSnapshot(version))) {
getLog().info("Skipping artifact deployment");
return;
}
- if (!file.exists()) {
- throw new MojoExecutionException(file.getPath() + " not found.");
+ if (!Files.exists(file)) {
+ String message = "The specified file '" + file + "' does not exist";
+ getLog().error(message);
+ throw new MojoException(message);
}
initProperties();
- RemoteRepository remoteRepository = getRemoteRepository(repositoryId, url);
+ RemoteRepository deploymentRepository =
+ createDeploymentArtifactRepository(repositoryId, url.replace(File.separator, "/"));
+
+ if (deploymentRepository.getProtocol().isEmpty()) {
+ throw new MojoException("No transfer protocol found.");
+ }
- if (StringUtils.isEmpty(remoteRepository.getProtocol())) {
- throw new MojoExecutionException("No transfer protocol found.");
+ Path deployedPom;
+ if (pomFile != null) {
+ deployedPom = pomFile;
+ processModel(readModel(deployedPom));
+ } else {
+ deployedPom = readingPomFromJarFile();
}
if (groupId == null || artifactId == null || version == null || packaging == null) {
- throw new MojoExecutionException("The artifact information is incomplete: 'groupId', 'artifactId', "
+ throw new MojoException("The artifact information is incomplete: 'groupId', 'artifactId', "
+ "'version' and 'packaging' are required.");
}
if (!isValidId(groupId) || !isValidId(artifactId) || !isValidVersion(version)) {
- throw new MojoExecutionException("The artifact information is not valid: uses invalid characters.");
+ throw new MojoException("The artifact information is not valid: uses invalid characters.");
}
failIfOffline();
warnIfAffectedPackagingAndMaven(packaging);
- DeployRequest deployRequest = new DeployRequest();
- deployRequest.setRepository(remoteRepository);
+ List deployables = new ArrayList<>();
boolean isFilePom = classifier == null && "pom".equals(packaging);
- if (!isFilePom) {
- ArtifactType artifactType =
- session.getRepositorySession().getArtifactTypeRegistry().get(packaging);
- if (artifactType != null
- && (classifier == null || classifier.isEmpty())
- && !StringUtils.isEmpty(artifactType.getClassifier())) {
- classifier = artifactType.getClassifier();
- }
- }
- Artifact mainArtifact = new DefaultArtifact(
- groupId, artifactId, classifier, isFilePom ? "pom" : getExtension(file), version)
- .setFile(file);
- deployRequest.addArtifact(mainArtifact);
+ Artifact artifact = session.createArtifact(
+ groupId, artifactId, version, classifier, isFilePom ? "pom" : getExtension(file), packaging);
- File artifactLocalFile = getLocalRepositoryFile(session.getRepositorySession(), mainArtifact);
-
- if (file.equals(artifactLocalFile)) {
- throw new MojoFailureException("Cannot deploy artifact from the local repository: " + file);
+ if (file.equals(getLocalRepositoryFile(artifact))) {
+ throw new MojoException("Cannot deploy artifact from the local repository: " + file);
}
- File temporaryPom = null;
- if (!"pom".equals(packaging)) {
- if (pomFile != null) {
- deployRequest.addArtifact(new SubArtifact(mainArtifact, "", "pom", pomFile));
- } else if (generatePom) {
- temporaryPom = generatePomFile();
- getLog().debug("Deploying generated POM");
- deployRequest.addArtifact(new SubArtifact(mainArtifact, "", "pom", temporaryPom));
+ ArtifactManager artifactManager = session.getService(ArtifactManager.class);
+ artifactManager.setPath(artifact, file);
+ deployables.add(artifact);
+
+ if (!isFilePom) {
+ Artifact pomArtifact = session.createArtifact(groupId, artifactId, version, "", "pom", null);
+ if (deployedPom != null) {
+ artifactManager.setPath(pomArtifact, deployedPom);
+ deployables.add(pomArtifact);
} else {
- getLog().debug("Skipping deploying POM");
+ deployedPom = generatePomFile();
+ artifactManager.setPath(pomArtifact, deployedPom);
+ if (generatePom) {
+ getLog().debug("Deploying generated POM");
+ deployables.add(pomArtifact);
+ } else {
+ getLog().debug("Skipping deploying POM");
+ }
}
}
if (sources != null) {
- deployRequest.addArtifact(new SubArtifact(mainArtifact, "sources", "jar", sources));
+ Artifact sourcesArtifact = session.createArtifact(groupId, artifactId, version, "sources", "jar", null);
+ artifactManager.setPath(sourcesArtifact, sources);
+ deployables.add(sourcesArtifact);
}
if (javadoc != null) {
- deployRequest.addArtifact(new SubArtifact(mainArtifact, "javadoc", "jar", javadoc));
+ Artifact javadocArtifact = session.createArtifact(groupId, artifactId, version, "javadoc", "jar", null);
+ artifactManager.setPath(javadocArtifact, javadoc);
+ deployables.add(javadocArtifact);
}
if (files != null) {
if (types == null) {
- throw new MojoExecutionException("You must specify 'types' if you specify 'files'");
+ throw new MojoException("You must specify 'types' if you specify 'files'");
}
if (classifiers == null) {
- throw new MojoExecutionException("You must specify 'classifiers' if you specify 'files'");
+ throw new MojoException("You must specify 'classifiers' if you specify 'files'");
}
- int filesLength = StringUtils.countMatches(files, ",");
- int typesLength = StringUtils.countMatches(types, ",");
- int classifiersLength = StringUtils.countMatches(classifiers, ",");
+ int filesLength = countCommas(files);
+ int typesLength = countCommas(types);
+ int classifiersLength = countCommas(classifiers);
if (typesLength != filesLength) {
- throw new MojoExecutionException("You must specify the same number of entries in 'files' and "
+ throw new MojoException("You must specify the same number of entries in 'files' and "
+ "'types' (respectively " + filesLength + " and " + typesLength + " entries )");
}
if (classifiersLength != filesLength) {
- throw new MojoExecutionException("You must specify the same number of entries in 'files' and "
+ throw new MojoException("You must specify the same number of entries in 'files' and "
+ "'classifiers' (respectively " + filesLength + " and " + classifiersLength + " entries )");
}
int fi = 0;
@@ -340,24 +351,26 @@ public void execute() throws MojoExecutionException, MojoFailureException {
if (nci == -1) {
nci = classifiers.length();
}
- File file = new File(files.substring(fi, nfi));
- if (!file.isFile()) {
+ Path file = Paths.get(files.substring(fi, nfi).replace("/", File.separator));
+ if (!Files.isRegularFile(file)) {
// try relative to the project basedir just in case
- file = new File(files.substring(fi, nfi));
+ file = Paths.get(files.substring(fi, nfi));
}
- if (file.isFile()) {
+ if (Files.isRegularFile(file)) {
String extension = getExtension(file);
- ArtifactType artifactType = session.getRepositorySession()
- .getArtifactTypeRegistry()
- .get(types.substring(ti, nti).trim());
- if (artifactType != null && !Objects.equals(extension, artifactType.getExtension())) {
- extension = artifactType.getExtension();
- }
-
- deployRequest.addArtifact(new SubArtifact(
- mainArtifact, classifiers.substring(ci, nci).trim(), extension, file));
+ String type = types.substring(ti, nti).trim();
+
+ Artifact deployable = session.createArtifact(
+ artifact.getGroupId(),
+ artifact.getArtifactId(),
+ artifact.getVersion().asString(),
+ classifiers.substring(ci, nci).trim(),
+ extension,
+ type);
+ artifactManager.setPath(deployable, file);
+ deployables.add(deployable);
} else {
- throw new MojoExecutionException("Specified side artifact " + file + " does not exist");
+ throw new MojoException("Specified side artifact " + file + " does not exist");
}
fi = nfi + 1;
ti = nti + 1;
@@ -365,21 +378,33 @@ public void execute() throws MojoExecutionException, MojoFailureException {
}
} else {
if (types != null) {
- throw new MojoExecutionException("You must specify 'files' if you specify 'types'");
+ throw new MojoException("You must specify 'files' if you specify 'types'");
}
if (classifiers != null) {
- throw new MojoExecutionException("You must specify 'files' if you specify 'classifiers'");
+ throw new MojoException("You must specify 'files' if you specify 'classifiers'");
}
}
try {
- repositorySystem.deploy(session.getRepositorySession(), deployRequest);
- } catch (DeploymentException e) {
- throw new MojoExecutionException(e.getMessage(), e);
+ ArtifactDeployerRequest deployRequest = ArtifactDeployerRequest.builder()
+ .session(session)
+ .repository(deploymentRepository)
+ .artifacts(deployables)
+ .retryFailedDeploymentCount(Math.max(1, Math.min(10, getRetryFailedDeploymentCount())))
+ .build();
+
+ getLog().info("Deploying artifacts " + deployables + " to repository " + deploymentRepository);
+ ArtifactDeployer artifactDeployer = session.getService(ArtifactDeployer.class);
+ artifactDeployer.deploy(deployRequest);
+ } catch (ArtifactDeployerException e) {
+ throw new MojoException(e.getMessage(), e);
} finally {
- if (temporaryPom != null) {
- // noinspection ResultOfMethodCallIgnored
- temporaryPom.delete();
+ if (pomFile == null && deployedPom != null) {
+ try {
+ Files.deleteIfExists(deployedPom);
+ } catch (IOException e) {
+ // ignore
+ }
}
}
}
@@ -388,9 +413,8 @@ public void execute() throws MojoExecutionException, MojoFailureException {
* Gets the path of the specified artifact within the local repository. Note that the returned path need not exist
* (yet).
*/
- private File getLocalRepositoryFile(RepositorySystemSession session, Artifact artifact) {
- String path = session.getLocalRepositoryManager().getPathForLocalArtifact(artifact);
- return new File(session.getLocalRepository().getBasedir(), path);
+ private Path getLocalRepositoryFile(Artifact artifact) {
+ return session.getPathForLocalArtifact(artifact);
}
/**
@@ -426,17 +450,18 @@ private void processModel(Model model) {
*
* @param pomFile The path of the POM file to parse, must not be null
.
* @return The model from the POM file, never null
.
- * @throws MojoExecutionException If the file doesn't exist or cannot be read.
+ * @throws MojoException If the file doesn't exist of cannot be read.
*/
- Model readModel(File pomFile) throws MojoExecutionException {
- try (Reader reader = ReaderFactory.newXmlReader(pomFile)) {
- return new MavenXpp3Reader().read(reader);
+ Model readModel(Path pomFile) throws MojoException {
+ try (InputStream is = Files.newInputStream(pomFile)) {
+ ModelXmlFactory modelXmlFactory = session.getService(ModelXmlFactory.class);
+ return modelXmlFactory.read(is);
} catch (FileNotFoundException e) {
- throw new MojoExecutionException("POM not found " + pomFile, e);
+ throw new MojoException("POM not found " + pomFile, e);
} catch (IOException e) {
- throw new MojoExecutionException("Error reading POM " + pomFile, e);
- } catch (XmlPullParserException e) {
- throw new MojoExecutionException("Error parsing POM " + pomFile, e);
+ throw new MojoException("Error reading POM " + pomFile, e);
+ } catch (XmlReaderException e) {
+ throw new MojoException("Error parsing POM " + pomFile, e);
}
}
@@ -444,22 +469,19 @@ Model readModel(File pomFile) throws MojoExecutionException {
* Generates a minimal POM from the user-supplied artifact information.
*
* @return The path to the generated POM file, never null
.
- * @throws MojoExecutionException If the generation failed.
+ * @throws MojoException If the generation failed.
*/
- private File generatePomFile() throws MojoExecutionException {
+ private Path generatePomFile() throws MojoException {
Model model = generateModel();
-
try {
- File tempFile = File.createTempFile("mvndeploy", ".pom");
- tempFile.deleteOnExit();
-
- try (Writer fw = WriterFactory.newXmlWriter(tempFile)) {
- new MavenXpp3Writer().write(fw, model);
+ Path pomFile = File.createTempFile("mvndeploy", ".pom").toPath();
+ try (Writer writer = Files.newBufferedWriter(pomFile)) {
+ ModelXmlFactory modelXmlFactory = session.getService(ModelXmlFactory.class);
+ modelXmlFactory.write(model, writer);
}
-
- return tempFile;
+ return pomFile;
} catch (IOException e) {
- throw new MojoExecutionException("Error writing temporary pom file: " + e.getMessage(), e);
+ throw new MojoException("Error writing temporary POM file: " + e.getMessage(), e);
}
}
@@ -469,18 +491,14 @@ private File generatePomFile() throws MojoExecutionException {
* @return The generated model, never null
.
*/
private Model generateModel() {
- Model model = new Model();
-
- model.setModelVersion("4.0.0");
-
- model.setGroupId(groupId);
- model.setArtifactId(artifactId);
- model.setVersion(version);
- model.setPackaging(packaging);
-
- model.setDescription(description);
-
- return model;
+ return Model.newBuilder()
+ .modelVersion("4.0.0")
+ .groupId(groupId)
+ .artifactId(artifactId)
+ .version(version)
+ .packaging(packaging)
+ .description(description)
+ .build();
}
void setGroupId(String groupId) {
@@ -499,7 +517,7 @@ void setPackaging(String packaging) {
this.packaging = packaging;
}
- void setPomFile(File pomFile) {
+ void setPomFile(Path pomFile) {
this.pomFile = pomFile;
}
@@ -519,7 +537,7 @@ String getPackaging() {
return packaging;
}
- File getFile() {
+ Path getFile() {
return file;
}
@@ -533,16 +551,27 @@ void setClassifier(String classifier) {
// these below should be shared (duplicated in m-install-p, m-deploy-p)
+ private static int countCommas(String str) {
+ int count = 0;
+ int idx = 0;
+ while ((idx = str.indexOf(',', idx)) != -1) {
+ count++;
+ idx++;
+ }
+ return count;
+ }
+
/**
- * Specialization of {@link FileUtils#getExtension(String)} that honors various {@code tar.xxx} combinations.
+ * Get file extension, honoring various {@code tar.xxx} combinations.
*/
- private String getExtension(final File file) {
- String filename = file.getName();
- if (filename.contains(".tar.")) {
- return "tar." + FileUtils.getExtension(filename);
- } else {
- return FileUtils.getExtension(filename);
+ private String getExtension(final Path file) {
+ String filename = file.getFileName().toString();
+ int lastDot = filename.lastIndexOf('.');
+ if (lastDot > 0 && lastDot < filename.length() - 1) {
+ String ext = filename.substring(lastDot + 1);
+ return filename.regionMatches(lastDot + 1 - TAR.length(), TAR, 0, TAR.length()) ? TAR + ext : ext;
}
+ return "";
}
/**
@@ -566,8 +595,6 @@ private boolean isValidId(String id) {
return true;
}
- private static final String ILLEGAL_VERSION_CHARS = "\\/:\"<>|?*[](){},";
-
/**
* Returns {@code true} if passed in string is "valid Maven (simple. non range, expression, etc) version".
*/
diff --git a/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java b/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
index 79ee1d87..3b75d63d 100644
--- a/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
+++ b/src/main/java/org/apache/maven/plugins/deploy/DeployMojo.java
@@ -18,30 +18,26 @@
*/
package org.apache.maven.plugins.deploy;
-import java.io.File;
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
+import java.nio.file.Files;
+import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import org.apache.maven.RepositoryUtils;
-import org.apache.maven.artifact.ArtifactUtils;
-import org.apache.maven.model.Plugin;
-import org.apache.maven.model.PluginExecution;
-import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.plugin.MojoFailureException;
-import org.apache.maven.plugin.descriptor.PluginDescriptor;
-import org.apache.maven.plugins.annotations.LifecyclePhase;
-import org.apache.maven.plugins.annotations.Mojo;
-import org.apache.maven.plugins.annotations.Parameter;
-import org.apache.maven.project.MavenProject;
-import org.apache.maven.project.artifact.ProjectArtifact;
-import org.eclipse.aether.artifact.Artifact;
-import org.eclipse.aether.deployment.DeployRequest;
-import org.eclipse.aether.repository.RemoteRepository;
-import org.eclipse.aether.util.artifact.ArtifactIdUtils;
+import org.apache.maven.api.Artifact;
+import org.apache.maven.api.MojoExecution;
+import org.apache.maven.api.Project;
+import org.apache.maven.api.RemoteRepository;
+import org.apache.maven.api.di.Inject;
+import org.apache.maven.api.model.DistributionManagement;
+import org.apache.maven.api.model.Plugin;
+import org.apache.maven.api.model.PluginExecution;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.plugin.annotations.Mojo;
+import org.apache.maven.api.plugin.annotations.Parameter;
+import org.apache.maven.api.services.ArtifactDeployer;
+import org.apache.maven.api.services.ArtifactDeployerRequest;
+import org.apache.maven.api.services.ArtifactManager;
+import org.apache.maven.api.services.ProjectManager;
/**
* Deploys an artifact to remote repository.
@@ -49,28 +45,26 @@
* @author Emmanuel Venisse
* @author John Casey (refactoring only)
*/
-@Mojo(name = "deploy", defaultPhase = LifecyclePhase.DEPLOY, threadSafe = true)
+@Mojo(name = "deploy", defaultPhase = "deploy")
public class DeployMojo extends AbstractDeployMojo {
private static final Pattern ALT_LEGACY_REPO_SYNTAX_PATTERN = Pattern.compile("(.+?)::(.+?)::(.+)");
private static final Pattern ALT_REPO_SYNTAX_PATTERN = Pattern.compile("(.+?)::(.+)");
- @Parameter(defaultValue = "${project}", readonly = true, required = true)
- private MavenProject project;
+ @Inject
+ private Project project;
- @Parameter(defaultValue = "${reactorProjects}", required = true, readonly = true)
- private List reactorProjects;
-
- @Parameter(defaultValue = "${plugin}", required = true, readonly = true)
- private PluginDescriptor pluginDescriptor;
+ @Inject
+ private MojoExecution mojoExecution;
/**
* Whether every project should be deployed during its own deploy-phase or at the end of the multimodule build. If
* set to {@code true} and the build fails, none of the reactor projects is deployed.
+ * (experimental)
*
* @since 2.8
*/
- @Parameter(defaultValue = "false", property = "deployAtEnd")
+ @Parameter(defaultValue = "true", property = "deployAtEnd")
private boolean deployAtEnd;
/**
@@ -116,7 +110,7 @@ public class DeployMojo extends AbstractDeployMojo {
/**
* Set this to 'true' to bypass artifact deploy
- * Since since 3.0.0-M2 it's not anymore a real boolean as it can have more than 2 values:
+ * Since 3.0.0-M2 it's not anymore a real boolean as it can have more than 2 values:
*
* true
: will skip as usual
* releases
: will skip if current version of the project is a release
@@ -146,221 +140,175 @@ private enum State {
TO_BE_DEPLOYED
}
- private static final String DEPLOY_PROCESSED_MARKER = DeployMojo.class.getName() + ".processed";
-
- private static final String DEPLOY_ALT_RELEASE_DEPLOYMENT_REPOSITORY =
- DeployMojo.class.getName() + ".altReleaseDeploymentRepository";
-
- private static final String DEPLOY_ALT_SNAPSHOT_DEPLOYMENT_REPOSITORY =
- DeployMojo.class.getName() + ".altSnapshotDeploymentRepository";
-
- private static final String DEPLOY_ALT_DEPLOYMENT_REPOSITORY =
- DeployMojo.class.getName() + ".altDeploymentRepository";
+ public DeployMojo() {}
private void putState(State state) {
- getPluginContext().put(DEPLOY_PROCESSED_MARKER, state.name());
+ session.getPluginContext(project).put(State.class.getName(), state);
}
- private void putPluginContextValue(String key, String value) {
- if (value != null) {
- getPluginContext().put(key, value);
- }
+ private void putState(ArtifactDeployerRequest request) {
+ session.getPluginContext(project).put(ArtifactDeployerRequest.class.getName(), request);
}
- private String getPluginContextValue(Map pluginContext, String key) {
- return (String) pluginContext.get(key);
+ private State getState(Project project) {
+ return (State) session.getPluginContext(project).get(State.class.getName());
}
- private State getState(Map pluginContext) {
- return State.valueOf(getPluginContextValue(pluginContext, DEPLOY_PROCESSED_MARKER));
+ private boolean hasState(Project project) {
+ return session.getPluginContext(project).containsKey(State.class.getName());
}
- private boolean hasState(MavenProject project) {
- Map pluginContext = session.getPluginContext(pluginDescriptor, project);
- return pluginContext.containsKey(DEPLOY_PROCESSED_MARKER);
- }
-
- public void execute() throws MojoExecutionException, MojoFailureException {
- State state;
+ public void execute() {
if (Boolean.parseBoolean(skip)
- || ("releases".equals(skip) && !ArtifactUtils.isSnapshot(project.getVersion()))
- || ("snapshots".equals(skip) && ArtifactUtils.isSnapshot(project.getVersion()))) {
+ || ("releases".equals(skip) && !session.isVersionSnapshot(project.getVersion()))
+ || ("snapshots".equals(skip) && session.isVersionSnapshot(project.getVersion()))) {
getLog().info("Skipping artifact deployment");
- state = State.SKIPPED;
+ putState(State.SKIPPED);
} else {
failIfOffline();
- warnIfAffectedPackagingAndMaven(project.getPackaging());
+ warnIfAffectedPackagingAndMaven(project.getPackaging().id());
if (!deployAtEnd) {
-
- RemoteRepository deploymentRepository = getDeploymentRepository(
- project,
- altSnapshotDeploymentRepository,
- altReleaseDeploymentRepository,
- altDeploymentRepository);
-
- DeployRequest request = new DeployRequest();
- request.setRepository(deploymentRepository);
- processProject(project, request);
- deploy(request);
- state = State.DEPLOYED;
+ getLog().info("Deploying deploy for " + project.getGroupId() + ":" + project.getArtifactId() + ":"
+ + project.getVersion() + " at end");
+ deploy(createDeployerRequest());
+ putState(State.DEPLOYED);
} else {
- putPluginContextValue(DEPLOY_ALT_SNAPSHOT_DEPLOYMENT_REPOSITORY, altSnapshotDeploymentRepository);
- putPluginContextValue(DEPLOY_ALT_RELEASE_DEPLOYMENT_REPOSITORY, altReleaseDeploymentRepository);
- putPluginContextValue(DEPLOY_ALT_DEPLOYMENT_REPOSITORY, altDeploymentRepository);
- state = State.TO_BE_DEPLOYED;
+ // compute the request
+ putState(State.TO_BE_DEPLOYED);
+ putState(createDeployerRequest());
+ if (!allProjectsMarked()) {
+ getLog().info("Deferring deploy for " + project.getGroupId() + ":" + project.getArtifactId() + ":"
+ + project.getVersion() + " at end");
+ }
}
}
- putState(state);
-
- List allProjectsUsingPlugin = getAllProjectsUsingPlugin();
-
- if (allProjectsMarked(allProjectsUsingPlugin)) {
- deployAllAtOnce(allProjectsUsingPlugin);
- } else if (state == State.TO_BE_DEPLOYED) {
- getLog().info("Deferring deploy for " + project.getGroupId() + ":" + project.getArtifactId() + ":"
- + project.getVersion() + " at end");
+ if (allProjectsMarked()) {
+ deployAllAtOnce();
}
}
- private void deployAllAtOnce(List allProjectsUsingPlugin) throws MojoExecutionException {
- Map requests = new LinkedHashMap<>();
-
- // collect all arifacts from all modules to deploy
- // requests are grouped by used remote repository
- for (MavenProject reactorProject : allProjectsUsingPlugin) {
- Map pluginContext = session.getPluginContext(pluginDescriptor, reactorProject);
- State state = getState(pluginContext);
- if (state == State.TO_BE_DEPLOYED) {
+ private boolean allProjectsMarked() {
+ return session.getProjects().stream().allMatch(p -> hasState(p) || !hasDeployExecution(p));
+ }
- RemoteRepository deploymentRepository = getDeploymentRepository(
- reactorProject,
- getPluginContextValue(pluginContext, DEPLOY_ALT_SNAPSHOT_DEPLOYMENT_REPOSITORY),
- getPluginContextValue(pluginContext, DEPLOY_ALT_RELEASE_DEPLOYMENT_REPOSITORY),
- getPluginContextValue(pluginContext, DEPLOY_ALT_DEPLOYMENT_REPOSITORY));
-
- DeployRequest request = requests.computeIfAbsent(deploymentRepository, repo -> {
- DeployRequest newRequest = new DeployRequest();
- newRequest.setRepository(repo);
- return newRequest;
- });
- processProject(reactorProject, request);
+ private boolean hasDeployExecution(Project p) {
+ String key = mojoExecution.getPlugin().getModel().getKey();
+ Plugin plugin = p.getBuild().getPluginsAsMap().get(key);
+ if (plugin != null) {
+ for (PluginExecution execution : plugin.getExecutions()) {
+ if (!execution.getGoals().isEmpty() && !"none".equalsIgnoreCase(execution.getPhase())) {
+ return true;
+ }
}
}
- // finally execute all deployments request, lets resolver to optimize deployment
- for (DeployRequest request : requests.values()) {
- deploy(request);
- }
+ return false;
}
- private boolean allProjectsMarked(List allProjectsUsingPlugin) {
- for (MavenProject reactorProject : allProjectsUsingPlugin) {
- if (!hasState(reactorProject)) {
- return false;
+ private void deployAllAtOnce() {
+ Map>> flattenedRequests = new LinkedHashMap<>();
+ // flatten requests, grouping by remote repository and number of retries
+ for (Project reactorProject : session.getProjects()) {
+ State state = getState(reactorProject);
+ if (state == State.TO_BE_DEPLOYED) {
+ ArtifactDeployerRequest request = (ArtifactDeployerRequest)
+ session.getPluginContext(reactorProject).get(ArtifactDeployerRequest.class.getName());
+ flattenedRequests
+ .computeIfAbsent(request.getRepository(), r -> new LinkedHashMap<>())
+ .computeIfAbsent(request.getRetryFailedDeploymentCount(), i -> new ArrayList<>())
+ .addAll(request.getArtifacts());
}
}
- return true;
- }
-
- private List getAllProjectsUsingPlugin() {
- ArrayList result = new ArrayList<>();
- for (MavenProject reactorProject : reactorProjects) {
- if (hasExecution(reactorProject.getPlugin("org.apache.maven.plugins:maven-deploy-plugin"))) {
- result.add(reactorProject);
+ // Re-group all requests
+ List requests = new ArrayList<>();
+ for (Map.Entry>> entry1 : flattenedRequests.entrySet()) {
+ for (Map.Entry> entry2 : entry1.getValue().entrySet()) {
+ requests.add(ArtifactDeployerRequest.builder()
+ .session(session)
+ .repository(entry1.getKey())
+ .retryFailedDeploymentCount(entry2.getKey())
+ .artifacts(entry2.getValue())
+ .build());
}
}
- return result;
- }
-
- private boolean hasExecution(Plugin plugin) {
- if (plugin == null) {
- return false;
+ // Deploy
+ if (!requests.isEmpty()) {
+ requests.forEach(this::deploy);
+ } else {
+ getLog().info("No actual deploy requests");
}
+ }
- for (PluginExecution execution : plugin.getExecutions()) {
- if (!execution.getGoals().isEmpty() && !"none".equalsIgnoreCase(execution.getPhase())) {
- return true;
- }
+ private void deploy(ArtifactDeployerRequest request) {
+ try {
+ getLog().info("Deploying artifacts " + request.getArtifacts().toString() + " to repository "
+ + request.getRepository());
+ getArtifactDeployer().deploy(request);
+ } catch (MojoException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new MojoException(e.getMessage(), e);
}
- return false;
}
- private void processProject(final MavenProject project, DeployRequest request) throws MojoExecutionException {
- // always exists, as project exists
- Artifact pomArtifact = RepositoryUtils.toArtifact(new ProjectArtifact(project));
- // always exists, but at "init" is w/o file (packaging plugin assigns file to this when packaged)
- Artifact projectArtifact = RepositoryUtils.toArtifact(project.getArtifact());
-
- // pom project: pomArtifact and projectArtifact are SAME
- // jar project: pomArtifact and projectArtifact are DIFFERENT
- // incomplete project: is not pom project and projectArtifact has no file
-
- // we must compare coordinates ONLY (as projectArtifact may not have file, and Artifact.equals factors it in)
- // BUT if projectArtifact has file set, use that one
- if (ArtifactIdUtils.equalsId(pomArtifact, projectArtifact)) {
- if (isFile(projectArtifact.getFile())) {
- pomArtifact = projectArtifact;
- }
- projectArtifact = null;
- }
+ private ArtifactDeployerRequest createDeployerRequest() {
+ ProjectManager projectManager = getProjectManager();
+ Collection deployables = projectManager.getAllArtifacts(project);
+ Collection attachedArtifacts = projectManager.getAttachedArtifacts(project);
- if (isFile(pomArtifact.getFile())) {
- request.addArtifact(pomArtifact);
- } else {
- throw new MojoExecutionException(
- "The POM for project " + project.getArtifactId() + " could not be attached");
+ ArtifactManager artifactManager = getArtifactManager();
+ if (artifactManager.getPath(project.getPomArtifact()).isEmpty()) {
+ artifactManager.setPath(project.getPomArtifact(), project.getPomPath());
}
- // is not packaged, is "incomplete"
- boolean isIncomplete = projectArtifact != null && !isFile(projectArtifact.getFile());
- if (projectArtifact != null) {
- if (!isIncomplete) {
- request.addArtifact(projectArtifact);
- } else if (!project.getAttachedArtifacts().isEmpty()) {
- if (allowIncompleteProjects) {
- getLog().warn("");
- getLog().warn("The packaging plugin for project " + project.getArtifactId() + " did not assign");
- getLog().warn("a main file to the project but it has attachments. Change packaging to 'pom'.");
- getLog().warn("");
- getLog().warn("Incomplete projects like this will fail in future Maven versions!");
- getLog().warn("");
+ for (Artifact deployable : deployables) {
+ if (!isValidPath(deployable)) {
+ if (deployable == project.getMainArtifact().orElse(null)) {
+ if (attachedArtifacts.isEmpty()) {
+ throw new MojoException(
+ "The packaging for this project did not assign a file to the build artifact");
+ } else {
+ if (allowIncompleteProjects) {
+ getLog().warn("");
+ getLog().warn("The packaging plugin for this project did not assign");
+ getLog().warn(
+ "a main file to the project but it has attachments. Change packaging to 'pom'.");
+ getLog().warn("");
+ getLog().warn("Incomplete projects like this will fail in future Maven versions!");
+ getLog().warn("");
+ } else {
+ throw new MojoException("The packaging plugin for this project did not assign "
+ + "a main file to the project but it has attachments. Change packaging to 'pom'.");
+ }
+ }
} else {
- throw new MojoExecutionException("The packaging plugin for project " + project.getArtifactId()
- + " did not assign a main file to the project but it has attachments. Change packaging"
- + " to 'pom'.");
+ throw new MojoException("The packaging for this project did not assign "
+ + "a file to the attached artifact: " + deployable);
}
- } else {
- throw new MojoExecutionException("The packaging plugin for project " + project.getArtifactId()
- + " did not assign a file to the build artifact");
}
}
- for (org.apache.maven.artifact.Artifact attached : project.getAttachedArtifacts()) {
- getLog().debug("Attaching for deploy: " + attached.getId());
- request.addArtifact(RepositoryUtils.toArtifact(attached));
- }
- }
+ ArtifactDeployerRequest request = ArtifactDeployerRequest.builder()
+ .session(session)
+ .repository(getDeploymentRepository(session.isVersionSnapshot(project.getVersion())))
+ .artifacts(deployables)
+ .retryFailedDeploymentCount(Math.max(1, Math.min(10, getRetryFailedDeploymentCount())))
+ .build();
- private boolean isFile(File file) {
- return file != null && file.isFile();
+ return request;
}
/**
* Visible for testing.
*/
- RemoteRepository getDeploymentRepository(
- final MavenProject project,
- final String altSnapshotDeploymentRepository,
- final String altReleaseDeploymentRepository,
- final String altDeploymentRepository)
- throws MojoExecutionException {
+ RemoteRepository getDeploymentRepository(boolean isSnapshot) throws MojoException {
RemoteRepository repo = null;
String altDeploymentRepo;
- if (ArtifactUtils.isSnapshot(project.getVersion()) && altSnapshotDeploymentRepository != null) {
+ if (isSnapshot && altSnapshotDeploymentRepository != null) {
altDeploymentRepo = altSnapshotDeploymentRepository;
- } else if (!ArtifactUtils.isSnapshot(project.getVersion()) && altReleaseDeploymentRepository != null) {
+ } else if (!isSnapshot && altReleaseDeploymentRepository != null) {
altDeploymentRepo = altReleaseDeploymentRepository;
} else {
altDeploymentRepo = altDeploymentRepository;
@@ -379,9 +327,9 @@ RemoteRepository getDeploymentRepository(
if ("default".equals(layout)) {
getLog().warn("Using legacy syntax for alternative repository. " + "Use \"" + id + "::" + url
+ "\" instead.");
- repo = getRemoteRepository(id, url);
+ repo = createDeploymentArtifactRepository(id, url);
} else {
- throw new MojoExecutionException(
+ throw new MojoException(
altDeploymentRepo,
"Invalid legacy syntax and layout for repository.",
"Invalid legacy syntax and layout for alternative repository. Use \"" + id + "::" + url
@@ -391,7 +339,7 @@ RemoteRepository getDeploymentRepository(
matcher = ALT_REPO_SYNTAX_PATTERN.matcher(altDeploymentRepo);
if (!matcher.matches()) {
- throw new MojoExecutionException(
+ throw new MojoException(
altDeploymentRepo,
"Invalid syntax for repository.",
"Invalid syntax for alternative repository. Use \"id::url\".");
@@ -399,22 +347,54 @@ RemoteRepository getDeploymentRepository(
String id = matcher.group(1).trim();
String url = matcher.group(2).trim();
- repo = getRemoteRepository(id, url);
+ repo = createDeploymentArtifactRepository(id, url);
}
}
}
if (repo == null) {
- repo = RepositoryUtils.toRepo(project.getDistributionManagementArtifactRepository());
+ DistributionManagement dm = project.getModel().getDistributionManagement();
+ if (dm != null) {
+ if (isSnapshot
+ && dm.getSnapshotRepository() != null
+ && isNotEmpty(dm.getSnapshotRepository().getId())
+ && isNotEmpty(dm.getSnapshotRepository().getUrl())) {
+ repo = session.createRemoteRepository(dm.getSnapshotRepository());
+ } else if (dm.getRepository() != null
+ && isNotEmpty(dm.getRepository().getId())
+ && isNotEmpty(dm.getRepository().getUrl())) {
+ repo = session.createRemoteRepository(dm.getRepository());
+ }
+ }
}
if (repo == null) {
String msg = "Deployment failed: repository element was not specified in the POM inside"
+ " distributionManagement element or in -DaltDeploymentRepository=id::url parameter";
- throw new MojoExecutionException(msg);
+ throw new MojoException(msg);
}
return repo;
}
+
+ private boolean isValidPath(Artifact a) {
+ return getArtifactManager().getPath(a).filter(Files::isRegularFile).isPresent();
+ }
+
+ private static boolean isNotEmpty(String str) {
+ return str != null && !str.isEmpty();
+ }
+
+ private ArtifactDeployer getArtifactDeployer() {
+ return session.getService(ArtifactDeployer.class);
+ }
+
+ private ArtifactManager getArtifactManager() {
+ return session.getService(ArtifactManager.class);
+ }
+
+ private ProjectManager getProjectManager() {
+ return session.getService(ProjectManager.class);
+ }
}
diff --git a/src/test/java/org/apache/maven/plugins/deploy/DeployFileMojoTest.java b/src/test/java/org/apache/maven/plugins/deploy/DeployFileMojoTest.java
index b1083cb3..25ba9369 100644
--- a/src/test/java/org/apache/maven/plugins/deploy/DeployFileMojoTest.java
+++ b/src/test/java/org/apache/maven/plugins/deploy/DeployFileMojoTest.java
@@ -19,285 +19,237 @@
package org.apache.maven.plugins.deploy;
import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
-import java.util.Objects;
-
-import org.apache.maven.execution.MavenSession;
-import org.apache.maven.model.Model;
-import org.apache.maven.plugin.testing.AbstractMojoTestCase;
-import org.eclipse.aether.DefaultRepositorySystemSession;
-import org.eclipse.aether.internal.impl.DefaultLocalPathComposer;
-import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory;
-import org.eclipse.aether.repository.LocalRepository;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
+
+import org.apache.maven.api.Artifact;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.di.Inject;
+import org.apache.maven.api.di.Priority;
+import org.apache.maven.api.di.Provides;
+import org.apache.maven.api.di.Singleton;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.plugin.testing.InjectMojo;
+import org.apache.maven.api.plugin.testing.MojoParameter;
+import org.apache.maven.api.plugin.testing.MojoTest;
+import org.apache.maven.api.plugin.testing.stubs.ArtifactStub;
+import org.apache.maven.api.plugin.testing.stubs.SessionMock;
+import org.apache.maven.api.services.ArtifactDeployer;
+import org.apache.maven.api.services.ArtifactDeployerRequest;
+import org.apache.maven.api.services.ArtifactManager;
+import org.apache.maven.internal.impl.InternalSession;
+import org.junit.jupiter.api.Test;
+
+import static org.apache.maven.api.plugin.testing.MojoExtension.getBasedir;
+import static org.apache.maven.api.plugin.testing.MojoExtension.getVariableValueFromObject;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.when;
/**
* @author Allan Ramirez
*/
-public class DeployFileMojoTest extends AbstractMojoTestCase {
- private final String LOCAL_REPO = getBasedir() + "/target/local-repo";
-
- private List expectedFiles;
-
- private List fileList;
-
- private File remoteRepo;
-
- private AutoCloseable openMocks;
-
- @Mock
- private MavenSession session;
-
- @InjectMocks
- private DeployFileMojo mojo;
-
- public void setUp() throws Exception {
- super.setUp();
-
- remoteRepo = new File(getBasedir(), "target/remote-repo");
-
- if (!remoteRepo.exists()) {
- remoteRepo.mkdirs();
- }
- }
+@MojoTest
+public class DeployFileMojoTest {
+ private static final String LOCAL_REPO = "target/local-repo";
- @Override
- public void tearDown() throws Exception {
- super.tearDown();
- if (openMocks != null) {
- openMocks.close();
- }
- }
+ @Inject
+ @SuppressWarnings("unused")
+ private Session session;
- public void testDeployTestEnvironment() throws Exception {
- File testPom = new File(getBasedir(), "target/test-classes/unit/deploy-file-test/plugin-config.xml");
+ @Inject
+ @SuppressWarnings("unused")
+ private ArtifactDeployer artifactDeployer;
- AbstractDeployMojo mojo = (AbstractDeployMojo) lookupMojo("deploy-file", testPom);
+ @Inject
+ @SuppressWarnings("unused")
+ private ArtifactManager artifactManager;
+ @Test
+ @InjectMojo(goal = "deploy-file")
+ public void testDeployTestEnvironment(DeployFileMojo mojo) {
assertNotNull(mojo);
}
- public void testBasicDeployFile() throws Exception {
- File testPom = new File(getBasedir(), "target/test-classes/unit/deploy-file-test/plugin-config.xml");
-
- mojo = (DeployFileMojo) lookupMojo("deploy-file", testPom);
-
- openMocks = MockitoAnnotations.openMocks(this);
-
+ @Test
+ @InjectMojo(goal = "deploy-file")
+ @MojoParameter(name = "groupId", value = "org.apache.maven.test")
+ @MojoParameter(name = "artifactId", value = "maven-deploy-file-test")
+ @MojoParameter(name = "version", value = "1.0")
+ @MojoParameter(name = "packaging", value = "jar")
+ @MojoParameter(
+ name = "file",
+ value = "${session.topDirectory}/src/test/resources/unit/maven-deploy-test-1.0-SNAPSHOT.jar")
+ @MojoParameter(name = "repositoryId", value = "deploy-test")
+ @MojoParameter(name = "url", value = "file://${session.topDirectory}/target/remote-repo/deploy-file")
+ @MojoParameter(name = "description", value = "POM was created from deploy:deploy-file")
+ @MojoParameter(name = "generatePom", value = "true")
+ @MojoParameter(name = "skip", value = "snapshots")
+ public void testBasicDeployFile(DeployFileMojo mojo) throws Exception {
assertNotNull(mojo);
- DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession();
- repositorySession.setLocalRepositoryManager(
- new SimpleLocalRepositoryManagerFactory(new DefaultLocalPathComposer())
- .newInstance(repositorySession, new LocalRepository(LOCAL_REPO)));
- when(session.getRepositorySession()).thenReturn(repositorySession);
-
String groupId = (String) getVariableValueFromObject(mojo, "groupId");
-
String artifactId = (String) getVariableValueFromObject(mojo, "artifactId");
-
String version = (String) getVariableValueFromObject(mojo, "version");
-
String packaging = (String) getVariableValueFromObject(mojo, "packaging");
-
- File file = (File) getVariableValueFromObject(mojo, "file");
-
+ Path file = (Path) getVariableValueFromObject(mojo, "file");
String repositoryId = (String) getVariableValueFromObject(mojo, "repositoryId");
-
String url = (String) getVariableValueFromObject(mojo, "url");
- String skip = (String) getVariableValueFromObject(mojo, "skip");
-
assertEquals("org.apache.maven.test", groupId);
-
assertEquals("maven-deploy-file-test", artifactId);
-
assertEquals("1.0", version);
-
assertEquals("jar", packaging);
-
- assertEquals("snapshots", skip);
-
- assertTrue(file.exists());
-
+ assertTrue(Files.exists(file), file.toString());
assertEquals("deploy-test", repositoryId);
-
- assertEquals("file://" + getBasedir() + "/target/remote-repo/deploy-file-test", url);
-
- mojo.execute();
-
- // check the generated pom
- File pom = new File(
- remoteRepo,
- "deploy-file-test/" + groupId.replace('.', '/') + "/"
- + artifactId + "/" + version + "/" + artifactId + "-"
- + version + ".pom");
-
- assertTrue(pom.exists());
-
- Model model = mojo.readModel(pom);
-
- assertEquals("4.0.0", model.getModelVersion());
-
- assertEquals(groupId, model.getGroupId());
-
- assertEquals(artifactId, model.getArtifactId());
-
- assertEquals(version, model.getVersion());
-
- assertEquals(packaging, model.getPackaging());
-
- assertEquals("POM was created from deploy:deploy-file", model.getDescription());
-
- // check the remote-repo
- expectedFiles = new ArrayList<>();
- fileList = new ArrayList<>();
-
- File repo = new File(remoteRepo, "deploy-file-test");
-
- File[] files = repo.listFiles();
-
- for (File file1 : Objects.requireNonNull(files)) {
- addFileToList(file1, fileList);
- }
-
- expectedFiles.add("org");
- expectedFiles.add("apache");
- expectedFiles.add("maven");
- expectedFiles.add("test");
- expectedFiles.add("maven-deploy-file-test");
- expectedFiles.add("1.0");
- expectedFiles.add("maven-metadata.xml");
- expectedFiles.add("maven-metadata.xml.md5");
- expectedFiles.add("maven-metadata.xml.sha1");
- expectedFiles.add("maven-deploy-file-test-1.0.jar");
- expectedFiles.add("maven-deploy-file-test-1.0.jar.md5");
- expectedFiles.add("maven-deploy-file-test-1.0.jar.sha1");
- expectedFiles.add("maven-deploy-file-test-1.0.pom");
- expectedFiles.add("maven-deploy-file-test-1.0.pom.md5");
- expectedFiles.add("maven-deploy-file-test-1.0.pom.sha1");
-
- assertEquals(expectedFiles.size(), fileList.size());
-
- assertEquals(0, getSizeOfExpectedFiles(fileList, expectedFiles));
+ assertEquals("file://" + getBasedir() + "/target/remote-repo/deploy-file", url);
+
+ execute(mojo, request -> {
+ assertNotNull(request);
+ List artifacts = new ArrayList<>(request.getArtifacts());
+ assertEquals(2, artifacts.size());
+ Artifact a1 = artifacts.get(0);
+ Path p1 = artifactManager.getPath(a1).orElse(null);
+ assertEquals(file, p1);
+ Artifact a2 = artifacts.get(1);
+ Path p2 = artifactManager.getPath(a2).orElse(null);
+ assertNotNull(p2);
+ assertTrue(p2.toString().endsWith(".pom"));
+
+ assertNotNull(request.getRepository());
+ assertEquals(
+ url.replace(File.separator, "/"), request.getRepository().getUrl());
+
+ // check the generated pom
+ File pom = p2.toFile();
+ assertTrue(pom.exists());
+
+ Model model = mojo.readModel(p2);
+ assertEquals("4.0.0", model.getModelVersion());
+ assertEquals(groupId, model.getGroupId());
+ assertEquals(artifactId, model.getArtifactId());
+ assertEquals(version, model.getVersion());
+ assertEquals(packaging, model.getPackaging());
+ assertEquals("POM was created from deploy:deploy-file", model.getDescription());
+ });
}
- public void testDeployIfClassifierIsSet() throws Exception {
- File testPom = new File(getBasedir(), "target/test-classes/unit/deploy-file-classifier/plugin-config.xml");
-
- mojo = (DeployFileMojo) lookupMojo("deploy-file", testPom);
-
- openMocks = MockitoAnnotations.openMocks(this);
-
+ @Test
+ @InjectMojo(goal = "deploy-file")
+ @MojoParameter(name = "groupId", value = "org.apache.maven.test")
+ @MojoParameter(name = "artifactId", value = "maven-deploy-file-test")
+ @MojoParameter(name = "version", value = "1.0")
+ @MojoParameter(name = "packaging", value = "jar")
+ @MojoParameter(
+ name = "file",
+ value = "${session.topDirectory}/src/test/resources/unit/maven-deploy-test-1.0-SNAPSHOT.jar")
+ @MojoParameter(name = "repositoryId", value = "deploy-test")
+ @MojoParameter(name = "url", value = "file://${session.topDirectory}/target/remote-repo/deploy-file")
+ @MojoParameter(name = "classifier", value = "bin")
+ @MojoParameter(name = "generatePom", value = "true")
+ public void testDeployIfClassifierIsSet(DeployFileMojo mojo) throws Exception {
assertNotNull(mojo);
- DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession();
- repositorySession.setLocalRepositoryManager(
- new SimpleLocalRepositoryManagerFactory(new DefaultLocalPathComposer())
- .newInstance(repositorySession, new LocalRepository(LOCAL_REPO)));
- when(session.getRepositorySession()).thenReturn(repositorySession);
-
- String classifier = (String) getVariableValueFromObject(mojo, "classifier");
-
String groupId = (String) getVariableValueFromObject(mojo, "groupId");
-
String artifactId = (String) getVariableValueFromObject(mojo, "artifactId");
-
- String version = (String) getVariableValueFromObject(mojo, "version");
-
+ String classifier = (String) getVariableValueFromObject(mojo, "classifier");
assertEquals("bin", classifier);
+ String version = (String) getVariableValueFromObject(mojo, "version");
+ String url = (String) getVariableValueFromObject(mojo, "url");
- mojo.execute();
-
- File deployedArtifact = new File(
- remoteRepo,
- "deploy-file-classifier/" + groupId.replace('.', '/') + "/"
- + artifactId + "/" + version + "/" + artifactId + "-"
- + version + "-" + classifier + ".jar");
-
- assertTrue(deployedArtifact.exists());
-
- mojo.setClassifier("prod");
-
- assertEquals("prod", mojo.getClassifier());
-
- mojo.execute();
-
- File prodDeployedArtifact = new File(
- remoteRepo,
- "deploy-file-classifier/" + groupId.replace('.', '/') + "/"
- + artifactId + "/" + version + "/" + artifactId + "-"
- + version + "-" + mojo.getClassifier() + ".jar");
-
- assertTrue(prodDeployedArtifact.exists());
+ ArtifactDeployerRequest request = execute(mojo);
+
+ assertNotNull(request);
+ List artifacts = new ArrayList<>(request.getArtifacts());
+ assertEquals(2, artifacts.size());
+ // first artifact
+ Artifact a1 = artifacts.get(0);
+ assertEquals(new ArtifactStub(groupId, artifactId, "bin", version, "jar"), a1);
+ Path p1 = artifactManager.getPath(a1).orElse(null);
+ assertNotNull(p1);
+ assertTrue(p1.toString().endsWith("maven-deploy-test-1.0-SNAPSHOT.jar"));
+ // second artifact
+ Artifact a2 = artifacts.get(1);
+ assertEquals(new ArtifactStub(groupId, artifactId, "", version, "pom"), a2);
+ Path p2 = artifactManager.getPath(a2).orElse(null);
+ assertNotNull(p2);
+ assertTrue(p2.toString().endsWith(".pom"));
+ // remote repository
+ assertNotNull(request.getRepository());
+ assertEquals(url.replace(File.separator, "/"), request.getRepository().getUrl());
}
- public void testDeployIfArtifactIsNotJar() throws Exception {
- File testPom =
- new File(getBasedir(), "target/test-classes/unit/deploy-file-artifact-not-jar/plugin-config.xml");
-
- mojo = (DeployFileMojo) lookupMojo("deploy-file", testPom);
-
- openMocks = MockitoAnnotations.openMocks(this);
-
+ @Test
+ @InjectMojo(goal = "deploy-file")
+ @MojoParameter(name = "groupId", value = "org.apache.maven.test")
+ @MojoParameter(name = "artifactId", value = "maven-deploy-file-test")
+ @MojoParameter(name = "version", value = "1.0")
+ @MojoParameter(name = "file", value = "${session.topDirectory}/src/test/resources/unit/maven-deploy-test.zip")
+ @MojoParameter(name = "repositoryId", value = "deploy-test")
+ @MojoParameter(name = "url", value = "file://${session.topDirectory}/target/remote-repo/deploy-file")
+ @MojoParameter(name = "generatePom", value = "true")
+ public void testDeployIfArtifactIsNotJar(DeployFileMojo mojo) throws Exception {
assertNotNull(mojo);
- DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession();
- repositorySession.setLocalRepositoryManager(
- new SimpleLocalRepositoryManagerFactory(new DefaultLocalPathComposer())
- .newInstance(repositorySession, new LocalRepository(LOCAL_REPO)));
- when(session.getRepositorySession()).thenReturn(repositorySession);
-
String groupId = (String) getVariableValueFromObject(mojo, "groupId");
-
String artifactId = (String) getVariableValueFromObject(mojo, "artifactId");
-
String version = (String) getVariableValueFromObject(mojo, "version");
-
assertEquals("org.apache.maven.test", groupId);
-
assertEquals("maven-deploy-file-test", artifactId);
-
assertEquals("1.0", version);
- mojo.execute();
-
- File file = new File(
- remoteRepo,
- "deploy-file-artifact-not-jar/" + groupId.replace('.', '/') + "/"
- + artifactId + "/" + version + "/" + artifactId + "-"
- + version + ".zip");
-
- assertTrue(file.exists());
+ ArtifactDeployerRequest request = execute(mojo);
+
+ assertNotNull(request);
+ List artifacts = new ArrayList<>(request.getArtifacts());
+ assertEquals(2, artifacts.size());
+ Artifact a1 = artifacts.get(0);
+ Artifact a2 = artifacts.get(1);
+ Path p1 = artifactManager.getPath(a1).orElse(null);
+ Path p2 = artifactManager.getPath(a2).orElse(null);
+ assertNotNull(p1);
+ assertTrue(p1.toString().endsWith("maven-deploy-test.zip"));
+ assertNotNull(p2);
+ assertTrue(p2.toString().endsWith(".pom"));
+
+ assertNotNull(request.getRepository());
+ assertEquals(
+ "file://" + getBasedir().replace(File.separator, "/") + "/target/remote-repo/deploy-file",
+ request.getRepository().getUrl());
}
- private void addFileToList(File file, List fileList) {
- if (!file.isDirectory()) {
- fileList.add(file.getName());
- } else {
- fileList.add(file.getName());
-
- File[] files = file.listFiles();
+ private ArtifactDeployerRequest execute(DeployFileMojo mojo) {
+ AtomicReference holder = new AtomicReference<>();
+ execute(mojo, holder::set);
+ return holder.get();
+ }
- for (File file1 : Objects.requireNonNull(files)) {
- addFileToList(file1, fileList);
- }
- }
+ private void execute(DeployFileMojo mojo, Consumer consumer) {
+ doAnswer(iom -> {
+ ArtifactDeployerRequest request = iom.getArgument(0, ArtifactDeployerRequest.class);
+ consumer.accept(request);
+ return null;
+ })
+ .when(artifactDeployer)
+ .deploy(any(ArtifactDeployerRequest.class));
+ mojo.execute();
}
- private int getSizeOfExpectedFiles(List fileList, List expectedFiles) {
- for (String fileName : fileList) {
- if (expectedFiles.contains(fileName)) {
- expectedFiles.remove(fileName);
- } else {
- fail(fileName + " is not included in the expected files");
- }
- }
- return expectedFiles.size();
+ @Provides
+ @Singleton
+ @Priority(10)
+ @SuppressWarnings("unused")
+ private InternalSession createSession() {
+ InternalSession session = SessionMock.getMockSession(LOCAL_REPO);
+ when(session.getTopDirectory()).thenReturn(Paths.get(getBasedir()));
+ return session;
}
}
diff --git a/src/test/java/org/apache/maven/plugins/deploy/DeployFileMojoUnitTest.java b/src/test/java/org/apache/maven/plugins/deploy/DeployFileMojoUnitTest.java
index c368b365..d04ef9a9 100644
--- a/src/test/java/org/apache/maven/plugins/deploy/DeployFileMojoUnitTest.java
+++ b/src/test/java/org/apache/maven/plugins/deploy/DeployFileMojoUnitTest.java
@@ -18,17 +18,16 @@
*/
package org.apache.maven.plugins.deploy;
-import java.io.File;
+import java.nio.file.Path;
+import java.nio.file.Paths;
-import org.apache.maven.model.Model;
-import org.apache.maven.model.Parent;
-import org.apache.maven.plugin.MojoExecutionException;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Jerome Lacoste
@@ -37,24 +36,20 @@ public class DeployFileMojoUnitTest {
MockDeployFileMojo mojo;
Parent parent;
- @Before
+ @BeforeEach
public void setUp() {
- Model pomModel = new Model();
- pomModel.setPackaging(null);
-
- parent = new Parent();
- parent.setGroupId("parentGroup");
- parent.setArtifactId("parentArtifact");
- parent.setVersion("parentVersion");
-
+ Model pomModel = Model.newBuilder()
+ .packaging(null)
+ .parent(
+ parent = Parent.newBuilder()
+ .groupId("parentGroup")
+ .artifactId("parentArtifact")
+ .version("parentVersion")
+ .build())
+ .build();
mojo = new MockDeployFileMojo(pomModel);
}
- @After
- public void tearDown() {
- mojo = null;
- }
-
static class MockDeployFileMojo extends DeployFileMojo {
private Model model;
@@ -62,100 +57,45 @@ public MockDeployFileMojo(Model model) {
this.model = model;
}
- public void setModel(Model model) {
- this.model = model;
- }
-
- protected Model readModel(File pomFile) {
+ @Override
+ protected Model readModel(Path pomFile) throws MojoException {
return model;
}
}
@Test
- public void testProcessPomFromPomFileWithParent1() {
- mojo.setPomFile(new File("foo.bar"));
-
- setMojoModel(mojo.model, null, null, null, null, parent);
-
- try {
- mojo.initProperties();
- } catch (MojoExecutionException expected) {
- assertTrue(true); // missing artifactId and packaging
- }
-
- checkMojoProperties("parentGroup", null, "parentVersion", null);
- }
-
- @Test
- public void testProcessPomFromPomFileWithParent2() {
- mojo.setPomFile(new File("foo.bar"));
- setMojoModel(mojo.model, null, "artifact", null, null, parent);
-
- try {
- mojo.initProperties();
- } catch (MojoExecutionException expected) {
- assertTrue(true); // missing packaging
- }
-
- checkMojoProperties("parentGroup", "artifact", "parentVersion", null);
- }
-
- @Test
- public void testProcessPomFromPomFileWithParent3() {
- mojo.setPomFile(new File("foo.bar"));
- setMojoModel(mojo.model, null, "artifact", "version", null, parent);
-
- try {
- mojo.initProperties();
- } catch (MojoExecutionException expected) {
- assertTrue(true); // missing version and packaging
- }
-
- checkMojoProperties("parentGroup", "artifact", "version", null);
- }
-
- @Test
- public void testProcessPomFromPomFileWithParent4() throws MojoExecutionException {
- mojo.setPomFile(new File("foo.bar"));
- setMojoModel(mojo.model, null, "artifact", "version", "packaging", parent);
-
+ public void testProcessPomFromPomFileWithParent4() {
+ mojo.setPomFile(Paths.get("foo.bar"));
+ setMojoModel(mojo, null, "artifact", "version", "packaging", parent);
mojo.initProperties();
-
checkMojoProperties("parentGroup", "artifact", "version", "packaging");
}
@Test
- public void testProcessPomFromPomFileWithParent5() throws MojoExecutionException {
- mojo.setPomFile(new File("foo.bar"));
- setMojoModel(mojo.model, "group", "artifact", "version", "packaging", parent);
-
+ public void testProcessPomFromPomFileWithParent5() {
+ mojo.setPomFile(Paths.get("foo.bar"));
+ setMojoModel(mojo, "group", "artifact", "version", "packaging", parent);
mojo.initProperties();
-
checkMojoProperties("group", "artifact", "version", "packaging");
}
@Test
- public void testProcessPomFromPomFileWithParent6() throws MojoExecutionException {
- mojo.setPomFile(new File("foo.bar"));
- setMojoModel(mojo.model, "group", "artifact", "version", "packaging", null);
-
+ public void testProcessPomFromPomFileWithParent6() {
+ mojo.setPomFile(Paths.get("foo.bar"));
+ setMojoModel(mojo, "group", "artifact", "version", "packaging", null);
mojo.initProperties();
-
checkMojoProperties("group", "artifact", "version", "packaging");
}
@Test
- public void testProcessPomFromPomFileWithOverrides() throws MojoExecutionException {
- mojo.setPomFile(new File("foo.bar"));
- setMojoModel(mojo.model, "group", "artifact", "version", "packaging", null);
-
+ public void testProcessPomFromPomFileWithOverrides() {
+ mojo.setPomFile(Paths.get("foo.bar"));
+ setMojoModel(mojo, "group", "artifact", "version", "packaging", null);
mojo.setGroupId("groupO");
mojo.setArtifactId("artifactO");
mojo.setVersion("versionO");
mojo.setPackaging("packagingO");
-
mojo.initProperties();
-
checkMojoProperties("groupO", "artifactO", "versionO", "packagingO");
}
@@ -171,11 +111,13 @@ private void checkMojoProperties(
}
private void setMojoModel(
- Model model, String group, String artifact, String version, String packaging, Parent parent) {
- model.setGroupId(group);
- model.setArtifactId(artifact);
- model.setVersion(version);
- model.setPackaging(packaging);
- model.setParent(parent);
+ MockDeployFileMojo mojo, String group, String artifact, String version, String packaging, Parent parent) {
+ mojo.model = Model.newBuilder()
+ .groupId(group)
+ .artifactId(artifact)
+ .version(version)
+ .packaging(packaging)
+ .parent(parent)
+ .build();
}
}
diff --git a/src/test/java/org/apache/maven/plugins/deploy/DeployMojoPomPackagingTest.java b/src/test/java/org/apache/maven/plugins/deploy/DeployMojoPomPackagingTest.java
new file mode 100644
index 00000000..37c67366
--- /dev/null
+++ b/src/test/java/org/apache/maven/plugins/deploy/DeployMojoPomPackagingTest.java
@@ -0,0 +1,144 @@
+/*
+ * 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.deploy;
+
+import java.nio.file.Paths;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.apache.maven.api.Artifact;
+import org.apache.maven.api.Project;
+import org.apache.maven.api.di.Inject;
+import org.apache.maven.api.di.Priority;
+import org.apache.maven.api.di.Provides;
+import org.apache.maven.api.di.Singleton;
+import org.apache.maven.api.model.DeploymentRepository;
+import org.apache.maven.api.model.DistributionManagement;
+import org.apache.maven.api.model.Repository;
+import org.apache.maven.api.plugin.testing.InjectMojo;
+import org.apache.maven.api.plugin.testing.MojoParameter;
+import org.apache.maven.api.plugin.testing.MojoTest;
+import org.apache.maven.api.plugin.testing.stubs.ProjectStub;
+import org.apache.maven.api.plugin.testing.stubs.SessionMock;
+import org.apache.maven.api.services.ArtifactDeployer;
+import org.apache.maven.api.services.ArtifactDeployerRequest;
+import org.apache.maven.api.services.ArtifactManager;
+import org.apache.maven.api.services.ProjectManager;
+import org.apache.maven.api.services.RepositoryFactory;
+import org.apache.maven.internal.impl.InternalSession;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import static org.apache.maven.api.plugin.testing.MojoExtension.getBasedir;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.when;
+
+@MojoTest
+@ExtendWith(MockitoExtension.class)
+public class DeployMojoPomPackagingTest {
+
+ private static final String LOCAL_REPO = "/target/local-repo";
+
+ @Inject
+ @SuppressWarnings("unused")
+ private InternalSession session;
+
+ @Inject
+ @SuppressWarnings("unused")
+ private ArtifactManager artifactManager;
+
+ @Inject
+ @SuppressWarnings("unused")
+ private ProjectManager projectManager;
+
+ @Inject
+ @SuppressWarnings("unused")
+ private ArtifactDeployer artifactDeployer;
+
+ @Test
+ @InjectMojo(goal = "deploy")
+ @MojoParameter(name = "deployAtEnd", value = "false")
+ public void testBasicDeployWithPackagingAsPom(DeployMojo mojo) throws Exception {
+ assertNotNull(mojo);
+
+ ArtifactDeployerRequest request = execute(mojo);
+
+ assertNotNull(request);
+ Collection artifacts = request.getArtifacts();
+ assertEquals(
+ Collections.singletonList("org.apache.maven.test:maven-deploy-test:pom:1.0-SNAPSHOT"),
+ artifacts.stream().map(Artifact::key).collect(Collectors.toList()));
+ assertEquals(
+ Paths.get(getBasedir()).toUri().toString(),
+ request.getRepository().getUrl());
+ }
+
+ private ArtifactDeployerRequest execute(DeployMojo mojo) {
+ ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(ArtifactDeployerRequest.class);
+ doNothing().when(artifactDeployer).deploy(requestCaptor.capture());
+
+ mojo.execute();
+
+ List requests = requestCaptor.getAllValues();
+ assertNotNull(requests);
+ return requests.isEmpty() ? null : requests.get(requests.size() - 1);
+ }
+
+ @Provides
+ @Singleton
+ @Priority(10)
+ @SuppressWarnings("unused")
+ private InternalSession createSession() {
+ InternalSession session = SessionMock.getMockSession(LOCAL_REPO);
+ when(session.getArtifact(any()))
+ .thenAnswer(iom -> new org.apache.maven.internal.impl.DefaultArtifact(
+ session, iom.getArgument(0, org.eclipse.aether.artifact.Artifact.class)));
+ when(session.createRemoteRepository(any())).thenAnswer(iom -> session.getService(RepositoryFactory.class)
+ .createRemote(iom.getArgument(0, Repository.class)));
+ return session;
+ }
+
+ @Provides
+ @Singleton
+ @SuppressWarnings("unused")
+ private Project createProject() {
+ ProjectStub project = new ProjectStub();
+ project.setBasedir(Paths.get(getBasedir()));
+ project.setPomPath(Paths.get(getBasedir(), "src/test/resources/unit/pom.xml"));
+ project.setGroupId("org.apache.maven.test");
+ project.setArtifactId("maven-deploy-test");
+ project.setVersion("1.0-SNAPSHOT");
+ project.setPackaging("pom");
+ project.setModel(project.getModel()
+ .withDistributionManagement(DistributionManagement.newBuilder()
+ .repository(DeploymentRepository.newBuilder()
+ .id("remote-repo")
+ .url(Paths.get(getBasedir()).toUri().toString())
+ .build())
+ .build()));
+ return project;
+ }
+}
diff --git a/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java b/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java
index 52964cc5..a1e3e1e4 100644
--- a/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java
+++ b/src/test/java/org/apache/maven/plugins/deploy/DeployMojoTest.java
@@ -19,827 +19,299 @@
package org.apache.maven.plugins.deploy;
import java.io.File;
-import java.util.ArrayList;
-import java.util.Collections;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.Collection;
import java.util.List;
-import java.util.Objects;
-import java.util.Properties;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.maven.execution.MavenSession;
-import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.plugin.descriptor.PluginDescriptor;
-import org.apache.maven.plugin.testing.AbstractMojoTestCase;
-import org.apache.maven.plugin.testing.stubs.MavenProjectStub;
-import org.apache.maven.plugins.deploy.stubs.ArtifactRepositoryStub;
-import org.apache.maven.plugins.deploy.stubs.DeployArtifactStub;
-import org.apache.maven.project.MavenProject;
-import org.codehaus.plexus.util.FileUtils;
-import org.eclipse.aether.DefaultRepositorySystemSession;
-import org.eclipse.aether.RepositorySystem;
-import org.eclipse.aether.internal.impl.DefaultLocalPathComposer;
-import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory;
-import org.eclipse.aether.repository.LocalRepository;
-import org.eclipse.aether.repository.RemoteRepository;
-import org.junit.Ignore;
-import org.mockito.InjectMocks;
-import org.mockito.MockitoAnnotations;
-
+import java.util.stream.Collectors;
+
+import org.apache.maven.api.Artifact;
+import org.apache.maven.api.Project;
+import org.apache.maven.api.RemoteRepository;
+import org.apache.maven.api.di.Inject;
+import org.apache.maven.api.di.Priority;
+import org.apache.maven.api.di.Provides;
+import org.apache.maven.api.di.Singleton;
+import org.apache.maven.api.model.Repository;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.plugin.testing.InjectMojo;
+import org.apache.maven.api.plugin.testing.MojoParameter;
+import org.apache.maven.api.plugin.testing.MojoTest;
+import org.apache.maven.api.plugin.testing.stubs.ArtifactStub;
+import org.apache.maven.api.plugin.testing.stubs.ProjectStub;
+import org.apache.maven.api.plugin.testing.stubs.SessionMock;
+import org.apache.maven.api.services.ArtifactDeployer;
+import org.apache.maven.api.services.ArtifactDeployerRequest;
+import org.apache.maven.api.services.ArtifactManager;
+import org.apache.maven.api.services.ProjectManager;
+import org.apache.maven.api.services.RepositoryFactory;
+import org.apache.maven.internal.impl.InternalSession;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import static org.apache.maven.api.plugin.testing.MojoExtension.getBasedir;
+import static org.apache.maven.api.plugin.testing.MojoExtension.getVariableValueFromObject;
+import static org.apache.maven.api.plugin.testing.MojoExtension.setVariableValueToObject;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;
/**
* @author Allan Ramirez
*/
-public class DeployMojoTest extends AbstractMojoTestCase {
- private File remoteRepo;
-
- private File localRepo;
-
- private final String LOCAL_REPO = getBasedir() + "/target/local-repo";
-
- private final String REMOTE_REPO = getBasedir() + "/target/remote-repo";
-
- DeployArtifactStub artifact;
-
- final MavenProjectStub project = new MavenProjectStub();
-
- private AutoCloseable openMocks;
-
- private MavenSession session;
-
- @InjectMocks
- private DeployMojo mojo;
-
- public void setUp() throws Exception {
- super.setUp();
-
- session = mock(MavenSession.class);
- when(session.getPluginContext(any(PluginDescriptor.class), any(MavenProject.class)))
- .thenReturn(new ConcurrentHashMap<>());
- DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession();
- repositorySession.setLocalRepositoryManager(
- new SimpleLocalRepositoryManagerFactory(new DefaultLocalPathComposer())
- .newInstance(repositorySession, new LocalRepository(LOCAL_REPO)));
- when(session.getRepositorySession()).thenReturn(repositorySession);
-
- remoteRepo = new File(REMOTE_REPO);
-
- remoteRepo.mkdirs();
-
- localRepo = new File(LOCAL_REPO);
+@MojoTest
+@ExtendWith(MockitoExtension.class)
+public class DeployMojoTest {
- if (localRepo.exists()) {
- FileUtils.deleteDirectory(localRepo);
- }
+ private static final String LOCAL_REPO = "target/local-repo";
- if (remoteRepo.exists()) {
- FileUtils.deleteDirectory(remoteRepo);
- }
- }
-
- public void tearDown() throws Exception {
- super.tearDown();
+ @Inject
+ @SuppressWarnings("unused")
+ private InternalSession session;
- if (remoteRepo.exists()) {
- // FileUtils.deleteDirectory( remoteRepo );
- }
-
- if (openMocks != null) {
- openMocks.close();
- }
- }
+ @Inject
+ @SuppressWarnings("unused")
+ private ArtifactManager artifactManager;
- public void testDeployTestEnvironment() throws Exception {
- File testPom = new File(getBasedir(), "target/test-classes/unit/basic-deploy-test/plugin-config.xml");
+ @Inject
+ @SuppressWarnings("unused")
+ private ProjectManager projectManager;
- mojo = (DeployMojo) lookupMojo("deploy", testPom);
+ @Inject
+ @SuppressWarnings("unused")
+ private ArtifactDeployer artifactDeployer;
+ @Test
+ @InjectMojo(goal = "deploy")
+ public void testDeployTestEnvironment(DeployMojo mojo) {
assertNotNull(mojo);
}
- public void testBasicDeploy() throws Exception {
- File testPom = new File(getBasedir(), "target/test-classes/unit/basic-deploy-test/plugin-config.xml");
-
- mojo = (DeployMojo) lookupMojo("deploy", testPom);
-
- openMocks = MockitoAnnotations.openMocks(this);
-
+ @Test
+ @InjectMojo(goal = "deploy")
+ @MojoParameter(name = "deployAtEnd", value = "false")
+ public void testBasicDeploy(DeployMojo mojo) throws Exception {
assertNotNull(mojo);
+ Project project = (Project) getVariableValueFromObject(mojo, "project");
+ artifactManager.setPath(
+ project.getMainArtifact().get(),
+ Paths.get(getBasedir(), "target/test-classes/unit/maven-deploy-test-1.0-SNAPSHOT.jar"));
- DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession();
- repositorySession.setLocalRepositoryManager(
- new SimpleLocalRepositoryManagerFactory(new DefaultLocalPathComposer())
- .newInstance(repositorySession, new LocalRepository(LOCAL_REPO)));
- when(session.getRepositorySession()).thenReturn(repositorySession);
-
- File file = new File(
- getBasedir(),
- "target/test-classes/unit/basic-deploy-test/target/" + "deploy-test-file-1.0-SNAPSHOT.jar");
-
- assertTrue(file.exists());
-
- MavenProject project = (MavenProject) getVariableValueFromObject(mojo, "project");
- project.setGroupId("org.apache.maven.test");
- project.setArtifactId("maven-deploy-test");
- project.setVersion("1.0-SNAPSHOT");
+ ArtifactDeployerRequest request = execute(mojo);
- setVariableValueToObject(mojo, "pluginContext", new ConcurrentHashMap<>());
- setVariableValueToObject(mojo, "reactorProjects", Collections.singletonList(project));
-
- artifact = (DeployArtifactStub) project.getArtifact();
-
- String packaging = project.getPackaging();
-
- assertEquals("jar", packaging);
-
- artifact.setFile(file);
-
- ArtifactRepositoryStub repo = getRepoStub(mojo);
-
- assertNotNull(repo);
-
- repo.setAppendToUrl("basic-deploy-test");
-
- assertEquals("deploy-test", repo.getId());
- assertEquals("deploy-test", repo.getKey());
- assertEquals("file", repo.getProtocol());
- assertEquals("file://" + getBasedir() + "/target/remote-repo/basic-deploy-test", repo.getUrl());
-
- mojo.execute();
-
- // check the artifact in local repository
- List expectedFiles = new ArrayList<>();
- List fileList = new ArrayList<>();
-
- expectedFiles.add("org");
- expectedFiles.add("apache");
- expectedFiles.add("maven");
- expectedFiles.add("test");
- expectedFiles.add("maven-deploy-test");
- expectedFiles.add("1.0-SNAPSHOT");
- expectedFiles.add("maven-metadata-deploy-test.xml");
- // expectedFiles.add( "maven-deploy-test-1.0-SNAPSHOT.jar" );
- // expectedFiles.add( "maven-deploy-test-1.0-SNAPSHOT.pom" );
- // as we are in SNAPSHOT the file is here twice
- expectedFiles.add("maven-metadata-deploy-test.xml");
- // extra Aether files
- expectedFiles.add("resolver-status.properties");
- expectedFiles.add("resolver-status.properties");
-
- File localRepo = new File(LOCAL_REPO, "");
-
- File[] files = localRepo.listFiles();
-
- for (File file2 : Objects.requireNonNull(files)) {
- addFileToList(file2, fileList);
- }
-
- assertEquals(expectedFiles.size(), fileList.size());
-
- assertEquals(0, getSizeOfExpectedFiles(fileList, expectedFiles));
-
- // check the artifact in remote repository
- expectedFiles = new ArrayList<>();
- fileList = new ArrayList<>();
-
- expectedFiles.add("org");
- expectedFiles.add("apache");
- expectedFiles.add("maven");
- expectedFiles.add("test");
- expectedFiles.add("maven-deploy-test");
- expectedFiles.add("1.0-SNAPSHOT");
- expectedFiles.add("maven-metadata.xml");
- expectedFiles.add("maven-metadata.xml.md5");
- expectedFiles.add("maven-metadata.xml.sha1");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.jar");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.jar.md5");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.jar.sha1");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.pom");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.pom.md5");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.pom.sha1");
- // as we are in SNAPSHOT the file is here twice
- expectedFiles.add("maven-metadata.xml");
- expectedFiles.add("maven-metadata.xml.md5");
- expectedFiles.add("maven-metadata.xml.sha1");
-
- remoteRepo = new File(remoteRepo, "basic-deploy-test");
-
- files = remoteRepo.listFiles();
-
- for (File file1 : Objects.requireNonNull(files)) {
- addFileToList(file1, fileList);
- }
-
- assertEquals(expectedFiles.size(), fileList.size());
-
- assertEquals(0, getSizeOfExpectedFiles(fileList, expectedFiles));
+ assertNotNull(request);
+ Collection artifacts = request.getArtifacts();
+ assertEquals(
+ Arrays.asList(
+ "org.apache.maven.test:maven-deploy-test:pom:1.0-SNAPSHOT",
+ "org.apache.maven.test:maven-deploy-test:jar:1.0-SNAPSHOT"),
+ artifacts.stream().map(Artifact::key).collect(Collectors.toList()));
+ assertEquals(
+ Paths.get(getBasedir()).toUri().toString(),
+ request.getRepository().getUrl());
}
- public void testSkippingDeploy() throws Exception {
- File testPom = new File(getBasedir(), "target/test-classes/unit/basic-deploy-test/plugin-config.xml");
-
- mojo = (DeployMojo) lookupMojo("deploy", testPom);
-
+ @Test
+ @InjectMojo(goal = "deploy")
+ @MojoParameter(name = "deployAtEnd", value = "false")
+ public void testSkippingDeploy(DeployMojo mojo) throws Exception {
assertNotNull(mojo);
- File file = new File(
- getBasedir(),
- "target/test-classes/unit/basic-deploy-test/target/" + "deploy-test-file-1.0-SNAPSHOT.jar");
-
+ File file = new File(getBasedir(), "target/test-classes/unit/maven-deploy-test-1.0-SNAPSHOT.jar");
assertTrue(file.exists());
-
- MavenProject project = (MavenProject) getVariableValueFromObject(mojo, "project");
-
- setVariableValueToObject(mojo, "pluginDescriptor", new PluginDescriptor());
- setVariableValueToObject(mojo, "pluginContext", new ConcurrentHashMap<>());
- setVariableValueToObject(mojo, "reactorProjects", Collections.singletonList(project));
- setVariableValueToObject(mojo, "session", session);
-
- artifact = (DeployArtifactStub) project.getArtifact();
-
- String packaging = project.getPackaging();
-
+ Project project = (Project) getVariableValueFromObject(mojo, "project");
+ String packaging = project.getPackaging().id();
assertEquals("jar", packaging);
-
- artifact.setFile(file);
-
- ArtifactRepositoryStub repo = getRepoStub(mojo);
-
- assertNotNull(repo);
-
- repo.setAppendToUrl("basic-deploy-test");
-
- assertEquals("deploy-test", repo.getId());
- assertEquals("deploy-test", repo.getKey());
- assertEquals("file", repo.getProtocol());
- assertEquals("file://" + getBasedir() + "/target/remote-repo/basic-deploy-test", repo.getUrl());
+ artifactManager.setPath(project.getMainArtifact().get(), file.toPath());
setVariableValueToObject(mojo, "skip", Boolean.TRUE.toString());
- mojo.execute();
-
- File localRepo = new File(LOCAL_REPO, "");
-
- File[] files = localRepo.listFiles();
-
- assertNull(files);
-
- remoteRepo = new File(remoteRepo, "basic-deploy-test");
-
- files = remoteRepo.listFiles();
-
- assertNull(files);
- }
-
- public void testBasicDeployWithPackagingAsPom() throws Exception {
- File testPom = new File(getBasedir(), "target/test-classes/unit/basic-deploy-pom/plugin-config.xml");
-
- mojo = (DeployMojo) lookupMojo("deploy", testPom);
-
- openMocks = MockitoAnnotations.openMocks(this);
-
- assertNotNull(mojo);
-
- DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession();
- repositorySession.setLocalRepositoryManager(
- new SimpleLocalRepositoryManagerFactory(new DefaultLocalPathComposer())
- .newInstance(repositorySession, new LocalRepository(LOCAL_REPO)));
- when(session.getRepositorySession()).thenReturn(repositorySession);
-
- File pomFile = new File(
- getBasedir(),
- "target/test-classes/unit/basic-deploy-pom/target/" + "deploy-test-file-1.0-SNAPSHOT.pom");
-
- assertTrue(pomFile.exists());
-
- MavenProject project = (MavenProject) getVariableValueFromObject(mojo, "project");
- project.setGroupId("org.apache.maven.test");
- project.setArtifactId("maven-deploy-test");
- project.setVersion("1.0-SNAPSHOT");
-
- setVariableValueToObject(mojo, "pluginContext", new ConcurrentHashMap<>());
- setVariableValueToObject(mojo, "reactorProjects", Collections.singletonList(project));
-
- artifact = (DeployArtifactStub) project.getArtifact();
-
- artifact.setArtifactHandlerExtension(project.getPackaging());
-
- artifact.setFile(pomFile);
-
- ArtifactRepositoryStub repo = getRepoStub(mojo);
-
- repo.setAppendToUrl("basic-deploy-pom");
-
- mojo.execute();
-
- List expectedFiles = new ArrayList<>();
- List fileList = new ArrayList<>();
-
- expectedFiles.add("org");
- expectedFiles.add("apache");
- expectedFiles.add("maven");
- expectedFiles.add("test");
- expectedFiles.add("maven-deploy-test");
- expectedFiles.add("1.0-SNAPSHOT");
- expectedFiles.add("maven-metadata.xml");
- expectedFiles.add("maven-metadata.xml.md5");
- expectedFiles.add("maven-metadata.xml.sha1");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.pom");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.pom.md5");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.pom.sha1");
- // as we are in SNAPSHOT the file is here twice
- expectedFiles.add("maven-metadata.xml");
- expectedFiles.add("maven-metadata.xml.md5");
- expectedFiles.add("maven-metadata.xml.sha1");
- remoteRepo = new File(remoteRepo, "basic-deploy-pom");
-
- File[] files = remoteRepo.listFiles();
-
- for (File file : Objects.requireNonNull(files)) {
- addFileToList(file, fileList);
- }
-
- assertEquals(expectedFiles.size(), fileList.size());
-
- assertEquals(0, getSizeOfExpectedFiles(fileList, expectedFiles));
- }
-
- public void testBasicDeployWithPackagingAsBom() throws Exception {
- File testPom = new File(getBasedir(), "target/test-classes/unit/basic-deploy-bom/plugin-config.xml");
-
- mojo = (DeployMojo) lookupMojo("deploy", testPom);
-
- openMocks = MockitoAnnotations.openMocks(this);
-
- assertNotNull(mojo);
-
- DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession();
- repositorySession.setLocalRepositoryManager(
- new SimpleLocalRepositoryManagerFactory(new DefaultLocalPathComposer())
- .newInstance(repositorySession, new LocalRepository(LOCAL_REPO)));
- when(session.getRepositorySession()).thenReturn(repositorySession);
-
- File pomFile = new File(
- getBasedir(),
- "target/test-classes/unit/basic-deploy-bom/target/" + "deploy-test-file-1.0-SNAPSHOT.pom");
-
- assertTrue(pomFile.exists());
-
- MavenProject project = (MavenProject) getVariableValueFromObject(mojo, "project");
- project.setGroupId("org.apache.maven.test");
- project.setArtifactId("maven-deploy-test");
- project.setVersion("1.0-SNAPSHOT");
-
- setVariableValueToObject(mojo, "pluginContext", new ConcurrentHashMap<>());
- setVariableValueToObject(mojo, "reactorProjects", Collections.singletonList(project));
-
- artifact = (DeployArtifactStub) project.getArtifact();
-
- artifact.setArtifactHandlerExtension(project.getPackaging());
-
- artifact.setFile(pomFile);
-
- ArtifactRepositoryStub repo = getRepoStub(mojo);
-
- repo.setAppendToUrl("basic-deploy-bom");
-
- mojo.execute();
-
- List expectedFiles = new ArrayList<>();
- List fileList = new ArrayList<>();
-
- expectedFiles.add("org");
- expectedFiles.add("apache");
- expectedFiles.add("maven");
- expectedFiles.add("test");
- expectedFiles.add("maven-deploy-test");
- expectedFiles.add("1.0-SNAPSHOT");
- expectedFiles.add("maven-metadata.xml");
- expectedFiles.add("maven-metadata.xml.md5");
- expectedFiles.add("maven-metadata.xml.sha1");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.pom");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.pom.md5");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.pom.sha1");
- // as we are in SNAPSHOT the file is here twice
- expectedFiles.add("maven-metadata.xml");
- expectedFiles.add("maven-metadata.xml.md5");
- expectedFiles.add("maven-metadata.xml.sha1");
- remoteRepo = new File(remoteRepo, "basic-deploy-bom");
-
- File[] files = remoteRepo.listFiles();
-
- for (File file : Objects.requireNonNull(files)) {
- addFileToList(file, fileList);
- }
-
- assertEquals(expectedFiles.size(), fileList.size());
-
- assertEquals(0, getSizeOfExpectedFiles(fileList, expectedFiles));
- }
-
- public void testDeployIfArtifactFileIsNull() throws Exception {
- File testPom = new File(getBasedir(), "target/test-classes/unit/basic-deploy-test/plugin-config.xml");
-
- mojo = (DeployMojo) lookupMojo("deploy", testPom);
-
- openMocks = MockitoAnnotations.openMocks(this);
-
- setVariableValueToObject(mojo, "session", session);
-
- assertNotNull(mojo);
-
- MavenProject project = (MavenProject) getVariableValueFromObject(mojo, "project");
- project.setGroupId("org.apache.maven.test");
- project.setArtifactId("maven-deploy-test");
- project.setVersion("1.0-SNAPSHOT");
-
- setVariableValueToObject(mojo, "pluginContext", new ConcurrentHashMap<>());
- setVariableValueToObject(mojo, "reactorProjects", Collections.singletonList(project));
-
- artifact = (DeployArtifactStub) project.getArtifact();
-
- artifact.setFile(null);
-
- assertNull(artifact.getFile());
-
- try {
- mojo.execute();
- fail("Did not throw mojo execution exception");
- } catch (MojoExecutionException e) {
- // expected, message should include artifactId
- assertEquals(
- "The packaging plugin for project maven-deploy-test did not assign a file to the build artifact",
- e.getMessage());
- }
+ ArtifactDeployerRequest request = execute(mojo);
+ assertNull(request);
}
- public void testDeployIfProjectFileIsNull() throws Exception {
- File testPom = new File(getBasedir(), "target/test-classes/unit/basic-deploy-test/plugin-config.xml");
-
- mojo = (DeployMojo) lookupMojo("deploy", testPom);
-
- openMocks = MockitoAnnotations.openMocks(this);
-
- setVariableValueToObject(mojo, "session", session);
-
+ @Test
+ @InjectMojo(goal = "deploy")
+ @MojoParameter(name = "deployAtEnd", value = "false")
+ public void testDeployIfArtifactFileIsNull(DeployMojo mojo) throws Exception {
assertNotNull(mojo);
- MavenProject project = (MavenProject) getVariableValueFromObject(mojo, "project");
- project.setGroupId("org.apache.maven.test");
- project.setArtifactId("maven-deploy-test");
- project.setVersion("1.0-SNAPSHOT");
-
- project.setFile(null);
- assertNull(project.getFile());
-
- setVariableValueToObject(mojo, "pluginContext", new ConcurrentHashMap<>());
- setVariableValueToObject(mojo, "reactorProjects", Collections.singletonList(project));
+ Project project = (Project) getVariableValueFromObject(mojo, "project");
+ assertFalse(artifactManager.getPath(project.getMainArtifact().get()).isPresent());
- try {
- mojo.execute();
- fail("Did not throw mojo execution exception");
- } catch (MojoExecutionException e) {
- // expected, message should include artifactId
- assertEquals("The POM for project maven-deploy-test could not be attached", e.getMessage());
- }
+ assertThrows(MojoException.class, mojo::execute, "Did not throw mojo execution exception");
}
- public void testDeployWithAttachedArtifacts() throws Exception {
- File testPom = new File(
- getBasedir(), "target/test-classes/unit/basic-deploy-with-attached-artifacts/" + "plugin-config.xml");
-
- mojo = (DeployMojo) lookupMojo("deploy", testPom);
-
- openMocks = MockitoAnnotations.openMocks(this);
-
- assertNotNull(mojo);
-
- DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession();
- repositorySession.setLocalRepositoryManager(
- new SimpleLocalRepositoryManagerFactory(new DefaultLocalPathComposer())
- .newInstance(repositorySession, new LocalRepository(LOCAL_REPO)));
- when(session.getRepositorySession()).thenReturn(repositorySession);
-
- MavenProject project = (MavenProject) getVariableValueFromObject(mojo, "project");
- project.setGroupId("org.apache.maven.test");
- project.setArtifactId("maven-deploy-test");
- project.setVersion("1.0-SNAPSHOT");
-
- setVariableValueToObject(mojo, "pluginContext", new ConcurrentHashMap<>());
- setVariableValueToObject(mojo, "reactorProjects", Collections.singletonList(project));
-
- artifact = (DeployArtifactStub) project.getArtifact();
-
- File file = new File(
- getBasedir(),
- "target/test-classes/unit/basic-deploy-with-attached-artifacts/target/"
- + "deploy-test-file-1.0-SNAPSHOT.jar");
-
- artifact.setFile(file);
-
- ArtifactRepositoryStub repo = getRepoStub(mojo);
-
- repo.setAppendToUrl("basic-deploy-with-attached-artifacts");
-
- mojo.execute();
-
- // check the artifacts in remote repository
- List expectedFiles = new ArrayList<>();
- List fileList = new ArrayList<>();
-
- expectedFiles.add("org");
- expectedFiles.add("apache");
- expectedFiles.add("maven");
- expectedFiles.add("test");
- expectedFiles.add("maven-deploy-test");
- expectedFiles.add("1.0-SNAPSHOT");
- expectedFiles.add("maven-metadata.xml");
- expectedFiles.add("maven-metadata.xml.md5");
- expectedFiles.add("maven-metadata.xml.sha1");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.jar");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.jar.md5");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.jar.sha1");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.pom");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.pom.md5");
- expectedFiles.add("maven-deploy-test-1.0-SNAPSHOT.pom.sha1");
- // as we are in SNAPSHOT the file is here twice
- expectedFiles.add("maven-metadata.xml");
- expectedFiles.add("maven-metadata.xml.md5");
- expectedFiles.add("maven-metadata.xml.sha1");
- expectedFiles.add("attached-artifact-test-0");
- expectedFiles.add("1.0-SNAPSHOT");
- expectedFiles.add("maven-metadata.xml");
- expectedFiles.add("maven-metadata.xml.md5");
- expectedFiles.add("maven-metadata.xml.sha1");
- expectedFiles.add("attached-artifact-test-0-1.0-SNAPSHOT.jar");
- expectedFiles.add("attached-artifact-test-0-1.0-SNAPSHOT.jar.md5");
- expectedFiles.add("attached-artifact-test-0-1.0-SNAPSHOT.jar.sha1");
- // as we are in SNAPSHOT the file is here twice
- expectedFiles.add("maven-metadata.xml");
- expectedFiles.add("maven-metadata.xml.md5");
- expectedFiles.add("maven-metadata.xml.sha1");
-
- remoteRepo = new File(remoteRepo, "basic-deploy-with-attached-artifacts");
-
- File[] files = remoteRepo.listFiles();
-
- for (File file1 : Objects.requireNonNull(files)) {
- addFileToList(file1, fileList);
- }
-
- assertEquals(expectedFiles.size(), fileList.size());
-
- assertEquals(0, getSizeOfExpectedFiles(fileList, expectedFiles));
- }
-
- public void testNonPomDeployWithAttachedArtifactsOnly() throws Exception {
- File testPom = new File(
- getBasedir(), "target/test-classes/unit/basic-deploy-with-attached-artifacts/" + "plugin-config.xml");
-
- mojo = (DeployMojo) lookupMojo("deploy", testPom);
-
- openMocks = MockitoAnnotations.openMocks(this);
-
- assertNotNull(mojo);
-
- MavenProject project = (MavenProject) getVariableValueFromObject(mojo, "project");
- project.setGroupId("org.apache.maven.test");
- project.setArtifactId("maven-deploy-test");
- project.setVersion("1.0-SNAPSHOT");
-
- setVariableValueToObject(mojo, "pluginContext", new ConcurrentHashMap<>());
- setVariableValueToObject(mojo, "reactorProjects", Collections.singletonList(project));
-
- artifact = (DeployArtifactStub) project.getArtifact();
- artifact.setFile(null);
-
- try {
- mojo.execute();
- fail("Did not throw mojo execution exception");
- } catch (MojoExecutionException e) {
- // expected, message should include artifactId
- assertEquals(
- "The packaging plugin for project maven-deploy-test did not assign a main file to the project "
- + "but it has attachments. Change packaging to 'pom'.",
- e.getMessage());
- }
- }
-
- @Ignore("SCP is not part of Maven3 distribution. Aether handles transport extensions.")
- public void _testBasicDeployWithScpAsProtocol() throws Exception {
- String originalUserHome = System.getProperty("user.home");
-
- // FIX THE DAMN user.home BEFORE YOU DELETE IT!!!
- File altHome = new File(getBasedir(), "target/ssh-user-home");
- altHome.mkdirs();
-
- System.out.println("Testing user.home value for .ssh dir: " + altHome.getCanonicalPath());
-
- Properties props = System.getProperties();
- props.setProperty("user.home", altHome.getCanonicalPath());
-
- System.setProperties(props);
-
- File testPom = new File(getBasedir(), "target/test-classes/unit/basic-deploy-scp/plugin-config.xml");
-
- mojo = (DeployMojo) lookupMojo("deploy", testPom);
-
+ @Test
+ @InjectMojo(goal = "deploy")
+ @MojoParameter(name = "deployAtEnd", value = "false")
+ public void testDeployWithAttachedArtifacts(DeployMojo mojo) throws Exception {
assertNotNull(mojo);
-
- RepositorySystem repositorySystem = mock(RepositorySystem.class);
-
- setVariableValueToObject(mojo, "repositorySystem", repositorySystem);
-
- File file = new File(
- getBasedir(),
- "target/test-classes/unit/basic-deploy-scp/target/" + "deploy-test-file-1.0-SNAPSHOT.jar");
-
- assertTrue(file.exists());
-
- MavenProject project = (MavenProject) getVariableValueFromObject(mojo, "project");
-
- setVariableValueToObject(mojo, "pluginContext", new ConcurrentHashMap<>());
- setVariableValueToObject(mojo, "reactorProjects", Collections.singletonList(project));
-
- artifact = (DeployArtifactStub) project.getArtifact();
-
- artifact.setFile(file);
-
- String altUserHome = System.getProperty("user.home");
-
- if (altUserHome.equals(originalUserHome)) {
- // this is *very* bad!
- throw new IllegalStateException(
- "Setting 'user.home' system property to alternate value did NOT work. Aborting test.");
- }
-
- File sshFile = new File(altUserHome, ".ssh");
-
- System.out.println("Testing .ssh dir: " + sshFile.getCanonicalPath());
-
- // delete first the .ssh folder if existing before executing the mojo
- if (sshFile.exists()) {
- FileUtils.deleteDirectory(sshFile);
- }
-
- mojo.execute();
-
- assertTrue(sshFile.exists());
-
- FileUtils.deleteDirectory(sshFile);
+ Project project = (Project) getVariableValueFromObject(mojo, "project");
+ projectManager.attachArtifact(
+ project,
+ new ArtifactStub("org.apache.maven.test", "attached-artifact-test", "", "1.0-SNAPSHOT", "jar"),
+ Paths.get(getBasedir(), "target/test-classes/unit/attached-artifact-test-1.0-SNAPSHOT.jar"));
+ artifactManager.setPath(
+ project.getMainArtifact().get(),
+ Paths.get(getBasedir(), "target/test-classes/unit/maven-deploy-test-1.0-SNAPSHOT.jar"));
+
+ ArtifactDeployerRequest request = execute(mojo);
+
+ assertNotNull(request);
+ Collection artifacts = request.getArtifacts();
+ assertEquals(
+ Arrays.asList(
+ "org.apache.maven.test:maven-deploy-test:pom:1.0-SNAPSHOT",
+ "org.apache.maven.test:maven-deploy-test:jar:1.0-SNAPSHOT",
+ "org.apache.maven.test:attached-artifact-test:jar:1.0-SNAPSHOT"),
+ artifacts.stream().map(Artifact::key).collect(Collectors.toList()));
+ assertEquals(
+ Paths.get(getBasedir()).toUri().toString(),
+ request.getRepository().getUrl());
}
- public void testLegacyAltDeploymentRepositoryWithDefaultLayout() throws Exception {
- mojo = new DeployMojo();
-
- setVariableValueToObject(mojo, "project", project);
- setVariableValueToObject(mojo, "session", session);
+ @Test
+ @InjectMojo(goal = "deploy")
+ public void testLegacyAltDeploymentRepositoryWithDefaultLayout(DeployMojo mojo) throws IllegalAccessException {
setVariableValueToObject(mojo, "altDeploymentRepository", "altDeploymentRepository::default::http://localhost");
- project.setVersion("1.0-SNAPSHOT");
-
- assertEquals(
- new RemoteRepository.Builder("altDeploymentRepository", "default", "http://localhost").build(),
- mojo.getDeploymentRepository(
- project, null, null, "altDeploymentRepository::default::http://localhost"));
+ RemoteRepository repository = mojo.getDeploymentRepository(true);
+ assertEquals("altDeploymentRepository", repository.getId());
+ assertEquals("http://localhost", repository.getUrl());
}
- public void testLegacyAltDeploymentRepositoryWithLegacyLayout() throws Exception {
- mojo = new DeployMojo();
-
- setVariableValueToObject(mojo, "project", project);
- setVariableValueToObject(mojo, "session", session);
+ @Test
+ @InjectMojo(goal = "deploy")
+ public void testLegacyAltDeploymentRepositoryWithLegacyLayout(DeployMojo mojo) throws IllegalAccessException {
setVariableValueToObject(mojo, "altDeploymentRepository", "altDeploymentRepository::legacy::http://localhost");
- project.setVersion("1.0-SNAPSHOT");
- try {
- mojo.getDeploymentRepository(project, null, null, "altDeploymentRepository::legacy::http://localhost");
- fail("Should throw: Invalid legacy syntax and layout for repository.");
- } catch (MojoExecutionException e) {
- assertEquals(e.getMessage(), "Invalid legacy syntax and layout for repository.");
- assertEquals(
- e.getLongMessage(),
- "Invalid legacy syntax and layout for alternative repository. Use \"altDeploymentRepository::http://localhost\" instead, and only default layout is supported.");
- }
+ MojoException e = assertThrows(
+ MojoException.class,
+ () -> mojo.getDeploymentRepository(true),
+ "Should throw: Invalid legacy syntax and layout for repository.");
+ assertEquals(e.getMessage(), "Invalid legacy syntax and layout for repository.");
+ assertEquals(
+ e.getLongMessage(),
+ "Invalid legacy syntax and layout for alternative repository. Use \"altDeploymentRepository::http://localhost\" instead, and only default layout is supported.");
}
- public void testInsaneAltDeploymentRepository() throws Exception {
- mojo = new DeployMojo();
-
- setVariableValueToObject(mojo, "project", project);
- setVariableValueToObject(mojo, "session", session);
+ @Test
+ @InjectMojo(goal = "deploy")
+ public void testInsaneAltDeploymentRepository(DeployMojo mojo) throws IllegalAccessException {
setVariableValueToObject(
mojo, "altDeploymentRepository", "altDeploymentRepository::hey::wow::foo::http://localhost");
- project.setVersion("1.0-SNAPSHOT");
- try {
- mojo.getDeploymentRepository(
- project, null, null, "altDeploymentRepository::hey::wow::foo::http://localhost");
- fail("Should throw: Invalid legacy syntax and layout for repository.");
- } catch (MojoExecutionException e) {
- assertEquals(e.getMessage(), "Invalid legacy syntax and layout for repository.");
- assertEquals(
- e.getLongMessage(),
- "Invalid legacy syntax and layout for alternative repository. Use \"altDeploymentRepository::wow::foo::http://localhost\" instead, and only default layout is supported.");
- }
+ MojoException e = assertThrows(
+ MojoException.class,
+ () -> mojo.getDeploymentRepository(true),
+ "Should throw: Invalid legacy syntax and layout for repository.");
+ assertEquals(e.getMessage(), "Invalid legacy syntax and layout for repository.");
+ assertEquals(
+ e.getLongMessage(),
+ "Invalid legacy syntax and layout for alternative repository. Use \"altDeploymentRepository::wow::foo::http://localhost\" instead, and only default layout is supported.");
}
- public void testDefaultScmSvnAltDeploymentRepository() throws Exception {
- mojo = new DeployMojo();
-
- setVariableValueToObject(mojo, "project", project);
- setVariableValueToObject(mojo, "session", session);
+ @Test
+ @InjectMojo(goal = "deploy")
+ public void testDefaultScmSvnAltDeploymentRepository(DeployMojo mojo) throws IllegalAccessException {
setVariableValueToObject(
mojo, "altDeploymentRepository", "altDeploymentRepository::default::scm:svn:http://localhost");
- project.setVersion("1.0-SNAPSHOT");
-
- assertEquals(
- new RemoteRepository.Builder("altDeploymentRepository", "default", "scm:svn:http://localhost").build(),
- mojo.getDeploymentRepository(
- project, null, null, "altDeploymentRepository::default::scm:svn:http://localhost"));
+ RemoteRepository repository = mojo.getDeploymentRepository(true);
+ assertEquals("altDeploymentRepository", repository.getId());
+ assertEquals("scm:svn:http://localhost", repository.getUrl());
}
- public void testLegacyScmSvnAltDeploymentRepository() throws Exception {
- mojo = new DeployMojo();
-
- setVariableValueToObject(mojo, "project", project);
+ @Test
+ @InjectMojo(goal = "deploy")
+ public void testLegacyScmSvnAltDeploymentRepository(DeployMojo mojo) throws IllegalAccessException {
setVariableValueToObject(
mojo, "altDeploymentRepository", "altDeploymentRepository::legacy::scm:svn:http://localhost");
- project.setVersion("1.0-SNAPSHOT");
- try {
- mojo.getDeploymentRepository(
- project, null, null, "altDeploymentRepository::legacy::scm:svn:http://localhost");
- fail("Should throw: Invalid legacy syntax and layout for repository.");
- } catch (MojoExecutionException e) {
- assertEquals(e.getMessage(), "Invalid legacy syntax and layout for repository.");
- assertEquals(
- e.getLongMessage(),
- "Invalid legacy syntax and layout for alternative repository. Use \"altDeploymentRepository::scm:svn:http://localhost\" instead, and only default layout is supported.");
- }
- }
-
- public void testAltSnapshotDeploymentRepository() throws Exception {
- mojo = new DeployMojo();
-
- setVariableValueToObject(mojo, "project", project);
- setVariableValueToObject(mojo, "session", session);
- setVariableValueToObject(
- mojo, "altSnapshotDeploymentRepository", "altSnapshotDeploymentRepository::http://localhost");
-
- project.setVersion("1.0-SNAPSHOT");
-
+ MojoException e = assertThrows(
+ MojoException.class,
+ () -> mojo.getDeploymentRepository(true),
+ "Should throw: Invalid legacy syntax and layout for repository.");
+ assertEquals(e.getMessage(), "Invalid legacy syntax and layout for repository.");
assertEquals(
- new RemoteRepository.Builder("altSnapshotDeploymentRepository", "default", "http://localhost").build(),
- mojo.getDeploymentRepository(project, "altSnapshotDeploymentRepository::http://localhost", null, null));
+ e.getLongMessage(),
+ "Invalid legacy syntax and layout for alternative repository. Use \"altDeploymentRepository::scm:svn:http://localhost\" instead, and only default layout is supported.");
}
- public void testAltReleaseDeploymentRepository() throws Exception {
- mojo = new DeployMojo();
+ @Test
+ @InjectMojo(goal = "deploy")
+ public void testAltSnapshotDeploymentRepository(DeployMojo mojo) throws IllegalAccessException {
+ setVariableValueToObject(mojo, "altDeploymentRepository", "altReleaseDeploymentRepository::http://localhost");
- setVariableValueToObject(mojo, "project", project);
- setVariableValueToObject(mojo, "session", session);
- setVariableValueToObject(
- mojo, "altReleaseDeploymentRepository", "altReleaseDeploymentRepository::http://localhost");
+ RemoteRepository repository = mojo.getDeploymentRepository(true);
+ assertEquals("altReleaseDeploymentRepository", repository.getId());
+ assertEquals("http://localhost", repository.getUrl());
+ }
- project.setVersion("1.0");
+ @Test
+ @InjectMojo(goal = "deploy")
+ public void testAltReleaseDeploymentRepository(DeployMojo mojo) throws IllegalAccessException {
+ setVariableValueToObject(mojo, "altDeploymentRepository", "altReleaseDeploymentRepository::http://localhost");
- assertEquals(
- new RemoteRepository.Builder("altReleaseDeploymentRepository", "default", "http://localhost").build(),
- mojo.getDeploymentRepository(project, null, "altReleaseDeploymentRepository::http://localhost", null));
+ RemoteRepository repository = mojo.getDeploymentRepository(false);
+ assertEquals("altReleaseDeploymentRepository", repository.getId());
+ assertEquals("http://localhost", repository.getUrl());
}
- private void addFileToList(File file, List fileList) {
- if (!file.isDirectory()) {
- fileList.add(file.getName());
- } else {
- fileList.add(file.getName());
+ private ArtifactDeployerRequest execute(DeployMojo mojo) {
+ ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(ArtifactDeployerRequest.class);
+ doNothing().when(artifactDeployer).deploy(requestCaptor.capture());
- File[] files = file.listFiles();
+ mojo.execute();
- for (File file1 : Objects.requireNonNull(files)) {
- addFileToList(file1, fileList);
- }
- }
+ List requests = requestCaptor.getAllValues();
+ assertNotNull(requests);
+ return requests.isEmpty() ? null : requests.get(requests.size() - 1);
}
- private int getSizeOfExpectedFiles(List fileList, List expectedFiles) {
- for (String fileName : fileList) {
- // translate uniqueVersion to -SNAPSHOT
- fileName = fileName.replaceFirst("-\\d{8}\\.\\d{6}-\\d+", "-SNAPSHOT");
-
- if (!expectedFiles.remove(fileName)) {
- fail(fileName + " is not included in the expected files");
- }
- }
- return expectedFiles.size();
+ @Provides
+ @Singleton
+ @Priority(10)
+ @SuppressWarnings("unused")
+ private InternalSession createSession() {
+ InternalSession session = SessionMock.getMockSession(LOCAL_REPO);
+ when(session.getArtifact(any()))
+ .thenAnswer(iom -> new org.apache.maven.internal.impl.DefaultArtifact(
+ session, iom.getArgument(0, org.eclipse.aether.artifact.Artifact.class)));
+ when(session.createRemoteRepository(any())).thenAnswer(iom -> session.getService(RepositoryFactory.class)
+ .createRemote(iom.getArgument(0, Repository.class)));
+ return session;
}
- private ArtifactRepositoryStub getRepoStub(Object mojo) throws Exception {
- MavenProject project = (MavenProject) getVariableValueFromObject(mojo, "project");
- return (ArtifactRepositoryStub) project.getDistributionManagementArtifactRepository();
+ @Provides
+ @Singleton
+ @SuppressWarnings("unused")
+ private Project createProject() {
+ ProjectStub project = new ProjectStub();
+ project.setBasedir(Paths.get(getBasedir()));
+ project.setPomPath(Paths.get(getBasedir(), "src/test/resources/unit/pom.xml"));
+ project.setGroupId("org.apache.maven.test");
+ project.setArtifactId("maven-deploy-test");
+ project.setVersion("1.0-SNAPSHOT");
+ project.setPackaging("jar");
+ project.setModel(project.getModel()
+ .withDistributionManagement(org.apache.maven.api.model.DistributionManagement.newBuilder()
+ .repository(org.apache.maven.api.model.DeploymentRepository.newBuilder()
+ .id("remote-repo")
+ .url(Paths.get(getBasedir()).toUri().toString())
+ .build())
+ .build()));
+ ArtifactStub jar = new ArtifactStub("org.apache.maven.test", "maven-deploy-test", "", "1.0-SNAPSHOT", "jar");
+ project.setMainArtifact(jar);
+ return project;
}
}
diff --git a/src/test/java/org/apache/maven/plugins/deploy/stubs/ArtifactRepositoryStub.java b/src/test/java/org/apache/maven/plugins/deploy/stubs/ArtifactRepositoryStub.java
deleted file mode 100644
index 9dd95400..00000000
--- a/src/test/java/org/apache/maven/plugins/deploy/stubs/ArtifactRepositoryStub.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * 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.deploy.stubs;
-
-import org.apache.maven.artifact.Artifact;
-import org.apache.maven.artifact.metadata.ArtifactMetadata;
-import org.apache.maven.artifact.repository.ArtifactRepository;
-import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
-import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
-import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
-import org.apache.maven.plugin.testing.stubs.StubArtifactRepository;
-
-public class ArtifactRepositoryStub extends StubArtifactRepository {
- private boolean blacklisted;
-
- private ArtifactRepositoryLayout layout;
-
- private String url;
-
- private final String basedir = System.getProperty("basedir");
-
- public ArtifactRepositoryStub() {
- super(null);
- }
-
- public ArtifactRepositoryStub(String dir) {
- super(dir);
- }
-
- public String pathOf(Artifact artifact) {
- return getLayout().pathOf(artifact);
- }
-
- public String pathOfRemoteRepositoryMetadata(ArtifactMetadata artifactMetadata) {
- return getLayout().pathOfRemoteRepositoryMetadata(artifactMetadata);
- }
-
- public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) {
- return getLayout().pathOfLocalRepositoryMetadata(metadata, repository);
- }
-
- public String getUrl() {
- return url;
- }
-
- public void setAppendToUrl(String dir) {
- this.url = "file://" + basedir + "/target/remote-repo/" + dir;
- }
-
- public String getBasedir() {
- return basedir;
- }
-
- public String getProtocol() {
- return "file";
- }
-
- public String getId() {
- return "deploy-test";
- }
-
- public ArtifactRepositoryPolicy getSnapshots() {
- return new ArtifactRepositoryPolicy(
- true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE);
- }
-
- public ArtifactRepositoryPolicy getReleases() {
- return new ArtifactRepositoryPolicy(
- true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE);
- }
-
- public ArtifactRepositoryLayout getLayout() {
- if (layout != null) {
- return layout;
- } else {
- return new DefaultRepositoryLayout();
- }
- }
-
- public String getKey() {
- return getId();
- }
-
- public boolean isUniqueVersion() {
- return false;
- }
-
- public void setBlacklisted(boolean blackListed) {
- this.blacklisted = blackListed;
- }
-
- public boolean isBlacklisted() {
- return blacklisted;
- }
-
- // @Override
- public boolean isBlocked() {
- return false;
- }
-
- // @Override
- public void setBlocked(boolean b) {}
-}
diff --git a/src/test/java/org/apache/maven/plugins/deploy/stubs/ArtifactRepositoryStub2.java b/src/test/java/org/apache/maven/plugins/deploy/stubs/ArtifactRepositoryStub2.java
deleted file mode 100644
index 96d43bb9..00000000
--- a/src/test/java/org/apache/maven/plugins/deploy/stubs/ArtifactRepositoryStub2.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * 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.deploy.stubs;
-
-public class ArtifactRepositoryStub2 extends ArtifactRepositoryStub {
- private String protocol;
-
- public ArtifactRepositoryStub2() {
- super();
- }
-
- public ArtifactRepositoryStub2(String dir) {
- super(dir);
- }
-
- public String getUrl() {
- return "file://" + System.getProperty("basedir") + "/target/remote-repo/basic-deploy-scp";
- }
-
- public String getBasedir() {
- return System.getProperty("basedir");
- }
-
- public String getProtocol() {
- if (this.protocol == null || this.protocol.equals("")) {
- this.protocol = "scp";
- }
- return this.protocol;
- }
-
- public void setProtocol(String protocol) {
- this.protocol = protocol;
- }
-}
diff --git a/src/test/java/org/apache/maven/plugins/deploy/stubs/AttachedArtifactStub.java b/src/test/java/org/apache/maven/plugins/deploy/stubs/AttachedArtifactStub.java
deleted file mode 100644
index 9226bdcf..00000000
--- a/src/test/java/org/apache/maven/plugins/deploy/stubs/AttachedArtifactStub.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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.deploy.stubs;
-
-import java.io.File;
-
-public class AttachedArtifactStub extends DeployArtifactStub {
- public String getArtifactId() {
- return "attached-artifact-test-0";
- }
-
- public File getFile() {
- return new File(
- System.getProperty("basedir"),
- "target/test-classes/unit/basic-deploy-with-attached-artifacts/"
- + "target/deploy-test-file-1.0-SNAPSHOT.jar");
- }
-}
diff --git a/src/test/java/org/apache/maven/plugins/deploy/stubs/DeployArtifactStub.java b/src/test/java/org/apache/maven/plugins/deploy/stubs/DeployArtifactStub.java
deleted file mode 100644
index 7218fdf7..00000000
--- a/src/test/java/org/apache/maven/plugins/deploy/stubs/DeployArtifactStub.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * 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.deploy.stubs;
-
-import java.io.File;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.maven.artifact.handler.ArtifactHandler;
-import org.apache.maven.artifact.handler.DefaultArtifactHandler;
-import org.apache.maven.artifact.metadata.ArtifactMetadata;
-import org.apache.maven.plugin.testing.stubs.ArtifactStub;
-
-public class DeployArtifactStub extends ArtifactStub {
- private Map