View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.plugins.deploy;
20  
21  import java.io.File;
22  import java.util.ArrayList;
23  import java.util.LinkedHashMap;
24  import java.util.List;
25  import java.util.Map;
26  import java.util.regex.Matcher;
27  import java.util.regex.Pattern;
28  
29  import org.apache.maven.RepositoryUtils;
30  import org.apache.maven.artifact.ArtifactUtils;
31  import org.apache.maven.model.Plugin;
32  import org.apache.maven.model.PluginExecution;
33  import org.apache.maven.plugin.MojoExecutionException;
34  import org.apache.maven.plugin.MojoFailureException;
35  import org.apache.maven.plugin.descriptor.PluginDescriptor;
36  import org.apache.maven.plugins.annotations.LifecyclePhase;
37  import org.apache.maven.plugins.annotations.Mojo;
38  import org.apache.maven.plugins.annotations.Parameter;
39  import org.apache.maven.project.MavenProject;
40  import org.apache.maven.project.artifact.ProjectArtifact;
41  import org.eclipse.aether.artifact.Artifact;
42  import org.eclipse.aether.deployment.DeployRequest;
43  import org.eclipse.aether.repository.RemoteRepository;
44  import org.eclipse.aether.util.artifact.ArtifactIdUtils;
45  
46  /**
47   * Deploys an artifact to remote repository.
48   *
49   * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a>
50   * @author <a href="mailto:jdcasey@apache.org">John Casey (refactoring only)</a>
51   */
52  @Mojo(name = "deploy", defaultPhase = LifecyclePhase.DEPLOY, threadSafe = true)
53  public class DeployMojo extends AbstractDeployMojo {
54      private static final Pattern ALT_LEGACY_REPO_SYNTAX_PATTERN = Pattern.compile("(.+?)::(.+?)::(.+)");
55  
56      private static final Pattern ALT_REPO_SYNTAX_PATTERN = Pattern.compile("(.+?)::(.+)");
57  
58      @Parameter(defaultValue = "${project}", readonly = true, required = true)
59      private MavenProject project;
60  
61      @Parameter(defaultValue = "${reactorProjects}", required = true, readonly = true)
62      private List<MavenProject> reactorProjects;
63  
64      @Parameter(defaultValue = "${plugin}", required = true, readonly = true)
65      private PluginDescriptor pluginDescriptor;
66  
67      /**
68       * Whether every project should be deployed during its own deploy-phase or at the end of the multimodule build. If
69       * set to {@code true} and the build fails, none of the reactor projects is deployed.
70       *
71       * @since 2.8
72       */
73      @Parameter(defaultValue = "false", property = "deployAtEnd")
74      private boolean deployAtEnd;
75  
76      /**
77       * Specifies an alternative repository to which the project artifacts should be deployed (other than those specified
78       * in &lt;distributionManagement&gt;). <br/>
79       * Format: <code>id::url</code>
80       * <dl>
81       * <dt>id</dt>
82       * <dd>The id can be used to pick up the correct credentials from the settings.xml</dd>
83       * <dt>url</dt>
84       * <dd>The location of the repository</dd>
85       * </dl>
86       * <b>Note:</b> In version 2.x, the format was <code>id::<i>layout</i>::url</code> where <code><i>layout</i></code>
87       * could be <code>default</code> (ie. Maven 2) or <code>legacy</code> (ie. Maven 1), but since 3.0.0 the layout part
88       * has been removed because Maven 3 only supports Maven 2 repository layout.
89       */
90      @Parameter(property = "altDeploymentRepository")
91      private String altDeploymentRepository;
92  
93      /**
94       * The alternative repository to use when the project has a snapshot version.
95       *
96       * <b>Note:</b> In version 2.x, the format was <code>id::<i>layout</i>::url</code> where <code><i>layout</i></code>
97       * could be <code>default</code> (ie. Maven 2) or <code>legacy</code> (ie. Maven 1), but since 3.0.0 the layout part
98       * has been removed because Maven 3 only supports Maven 2 repository layout.
99       * @since 2.8
100      * @see DeployMojo#altDeploymentRepository
101      */
102     @Parameter(property = "altSnapshotDeploymentRepository")
103     private String altSnapshotDeploymentRepository;
104 
105     /**
106      * The alternative repository to use when the project has a final version.
107      *
108      * <b>Note:</b> In version 2.x, the format was <code>id::<i>layout</i>::url</code> where <code><i>layout</i></code>
109      * could be <code>default</code> (ie. Maven 2) or <code>legacy</code> (ie. Maven 1), but since 3.0.0 the layout part
110      * has been removed because Maven 3 only supports Maven 2 repository layout.
111      * @since 2.8
112      * @see DeployMojo#altDeploymentRepository
113      */
114     @Parameter(property = "altReleaseDeploymentRepository")
115     private String altReleaseDeploymentRepository;
116 
117     /**
118      * Set this to 'true' to bypass artifact deploy
119      * Since since 3.0.0-M2 it's not anymore a real boolean as it can have more than 2 values:
120      * <ul>
121      *     <li><code>true</code>: will skip as usual</li>
122      *     <li><code>releases</code>: will skip if current version of the project is a release</li>
123      *     <li><code>snapshots</code>: will skip if current version of the project is a snapshot</li>
124      *     <li>any other values will be considered as <code>false</code></li>
125      * </ul>
126      * @since 2.4
127      */
128     @Parameter(property = "maven.deploy.skip", defaultValue = "false")
129     private String skip = Boolean.FALSE.toString();
130 
131     /**
132      * Set this to <code>true</code> to allow incomplete project processing. By default, such projects are forbidden
133      * and Mojo will fail to process them. Incomplete project is a Maven Project that has any other packaging than
134      * "pom" and has no main artifact packaged. In the majority of cases, what user really wants here is a project
135      * with "pom" packaging and some classified artifact attached (typical example is some assembly being packaged
136      * and attached with classifier).
137      *
138      * @since 3.1.1
139      */
140     @Parameter(defaultValue = "false", property = "allowIncompleteProjects")
141     private boolean allowIncompleteProjects;
142 
143     private enum State {
144         SKIPPED,
145         DEPLOYED,
146         TO_BE_DEPLOYED
147     }
148 
149     private static final String DEPLOY_PROCESSED_MARKER = DeployMojo.class.getName() + ".processed";
150 
151     private static final String DEPLOY_ALT_RELEASE_DEPLOYMENT_REPOSITORY =
152             DeployMojo.class.getName() + ".altReleaseDeploymentRepository";
153 
154     private static final String DEPLOY_ALT_SNAPSHOT_DEPLOYMENT_REPOSITORY =
155             DeployMojo.class.getName() + ".altSnapshotDeploymentRepository";
156 
157     private static final String DEPLOY_ALT_DEPLOYMENT_REPOSITORY =
158             DeployMojo.class.getName() + ".altDeploymentRepository";
159 
160     private void putState(State state) {
161         getPluginContext().put(DEPLOY_PROCESSED_MARKER, state.name());
162     }
163 
164     private void putPluginContextValue(String key, String value) {
165         if (value != null) {
166             getPluginContext().put(key, value);
167         }
168     }
169 
170     private String getPluginContextValue(Map<String, Object> pluginContext, String key) {
171         return (String) pluginContext.get(key);
172     }
173 
174     private State getState(Map<String, Object> pluginContext) {
175         return State.valueOf(getPluginContextValue(pluginContext, DEPLOY_PROCESSED_MARKER));
176     }
177 
178     private boolean hasState(MavenProject project) {
179         Map<String, Object> pluginContext = session.getPluginContext(pluginDescriptor, project);
180         return pluginContext.containsKey(DEPLOY_PROCESSED_MARKER);
181     }
182 
183     @Override
184     public void execute() throws MojoExecutionException, MojoFailureException {
185         State state;
186         if (Boolean.parseBoolean(skip)
187                 || ("releases".equals(skip) && !ArtifactUtils.isSnapshot(project.getVersion()))
188                 || ("snapshots".equals(skip) && ArtifactUtils.isSnapshot(project.getVersion()))) {
189             getLog().info("Skipping artifact deployment");
190             state = State.SKIPPED;
191         } else {
192             failIfOffline();
193             warnIfAffectedPackagingAndMaven(project.getPackaging());
194 
195             if (!deployAtEnd) {
196 
197                 RemoteRepository deploymentRepository = getDeploymentRepository(
198                         project,
199                         altSnapshotDeploymentRepository,
200                         altReleaseDeploymentRepository,
201                         altDeploymentRepository);
202 
203                 DeployRequest request = new DeployRequest();
204                 request.setRepository(deploymentRepository);
205                 processProject(project, request);
206                 deploy(request);
207                 state = State.DEPLOYED;
208             } else {
209                 putPluginContextValue(DEPLOY_ALT_SNAPSHOT_DEPLOYMENT_REPOSITORY, altSnapshotDeploymentRepository);
210                 putPluginContextValue(DEPLOY_ALT_RELEASE_DEPLOYMENT_REPOSITORY, altReleaseDeploymentRepository);
211                 putPluginContextValue(DEPLOY_ALT_DEPLOYMENT_REPOSITORY, altDeploymentRepository);
212                 state = State.TO_BE_DEPLOYED;
213             }
214         }
215 
216         putState(state);
217 
218         List<MavenProject> allProjectsUsingPlugin = getAllProjectsUsingPlugin();
219 
220         if (allProjectsMarked(allProjectsUsingPlugin)) {
221             deployAllAtOnce(allProjectsUsingPlugin);
222         } else if (state == State.TO_BE_DEPLOYED) {
223             getLog().info("Deferring deploy for " + project.getGroupId() + ":" + project.getArtifactId() + ":"
224                     + project.getVersion() + " at end");
225         }
226     }
227 
228     private void deployAllAtOnce(List<MavenProject> allProjectsUsingPlugin) throws MojoExecutionException {
229         Map<RemoteRepository, DeployRequest> requests = new LinkedHashMap<>();
230 
231         // collect all arifacts from all modules to deploy
232         // requests are grouped by used remote repository
233         for (MavenProject reactorProject : allProjectsUsingPlugin) {
234             Map<String, Object> pluginContext = session.getPluginContext(pluginDescriptor, reactorProject);
235             State state = getState(pluginContext);
236             if (state == State.TO_BE_DEPLOYED) {
237 
238                 RemoteRepository deploymentRepository = getDeploymentRepository(
239                         reactorProject,
240                         getPluginContextValue(pluginContext, DEPLOY_ALT_SNAPSHOT_DEPLOYMENT_REPOSITORY),
241                         getPluginContextValue(pluginContext, DEPLOY_ALT_RELEASE_DEPLOYMENT_REPOSITORY),
242                         getPluginContextValue(pluginContext, DEPLOY_ALT_DEPLOYMENT_REPOSITORY));
243 
244                 DeployRequest request = requests.computeIfAbsent(deploymentRepository, repo -> {
245                     DeployRequest newRequest = new DeployRequest();
246                     newRequest.setRepository(repo);
247                     return newRequest;
248                 });
249                 processProject(reactorProject, request);
250             }
251         }
252         // finally execute all deployments request, lets resolver to optimize deployment
253         for (DeployRequest request : requests.values()) {
254             deploy(request);
255         }
256     }
257 
258     private boolean allProjectsMarked(List<MavenProject> allProjectsUsingPlugin) {
259         for (MavenProject reactorProject : allProjectsUsingPlugin) {
260             if (!hasState(reactorProject)) {
261                 return false;
262             }
263         }
264         return true;
265     }
266 
267     private List<MavenProject> getAllProjectsUsingPlugin() {
268         ArrayList<MavenProject> result = new ArrayList<>();
269         for (MavenProject reactorProject : reactorProjects) {
270             if (hasExecution(reactorProject.getPlugin("org.apache.maven.plugins:maven-deploy-plugin"))) {
271                 result.add(reactorProject);
272             }
273         }
274         return result;
275     }
276 
277     private boolean hasExecution(Plugin plugin) {
278         if (plugin == null) {
279             return false;
280         }
281 
282         for (PluginExecution execution : plugin.getExecutions()) {
283             if (!execution.getGoals().isEmpty() && !"none".equalsIgnoreCase(execution.getPhase())) {
284                 return true;
285             }
286         }
287         return false;
288     }
289 
290     private void processProject(final MavenProject project, DeployRequest request) throws MojoExecutionException {
291         // always exists, as project exists
292         Artifact pomArtifact = RepositoryUtils.toArtifact(new ProjectArtifact(project));
293         // always exists, but at "init" is w/o file (packaging plugin assigns file to this when packaged)
294         Artifact projectArtifact = RepositoryUtils.toArtifact(project.getArtifact());
295 
296         // pom project: pomArtifact and projectArtifact are SAME
297         // jar project: pomArtifact and projectArtifact are DIFFERENT
298         // incomplete project: is not pom project and projectArtifact has no file
299 
300         // we must compare coordinates ONLY (as projectArtifact may not have file, and Artifact.equals factors it in)
301         // BUT if projectArtifact has file set, use that one
302         if (ArtifactIdUtils.equalsId(pomArtifact, projectArtifact)) {
303             if (isFile(projectArtifact.getFile())) {
304                 pomArtifact = projectArtifact;
305             }
306             projectArtifact = null;
307         }
308 
309         if (isFile(pomArtifact.getFile())) {
310             request.addArtifact(pomArtifact);
311         } else {
312             throw new MojoExecutionException(
313                     "The POM for project " + project.getArtifactId() + " could not be attached");
314         }
315 
316         // is not packaged, is "incomplete"
317         boolean isIncomplete = projectArtifact != null && !isFile(projectArtifact.getFile());
318         if (projectArtifact != null) {
319             if (!isIncomplete) {
320                 request.addArtifact(projectArtifact);
321             } else if (!project.getAttachedArtifacts().isEmpty()) {
322                 if (allowIncompleteProjects) {
323                     getLog().warn("");
324                     getLog().warn("The packaging plugin for project " + project.getArtifactId() + " did not assign");
325                     getLog().warn("a main file to the project but it has attachments. Change packaging to 'pom'.");
326                     getLog().warn("");
327                     getLog().warn("Incomplete projects like this will fail in future Maven versions!");
328                     getLog().warn("");
329                 } else {
330                     throw new MojoExecutionException("The packaging plugin for project " + project.getArtifactId()
331                             + " did not assign a main file to the project but it has attachments. Change packaging"
332                             + " to 'pom'.");
333                 }
334             } else {
335                 throw new MojoExecutionException("The packaging plugin for project " + project.getArtifactId()
336                         + " did not assign a file to the build artifact");
337             }
338         }
339 
340         for (org.apache.maven.artifact.Artifact attached : project.getAttachedArtifacts()) {
341             getLog().debug("Attaching for deploy: " + attached.getId());
342             request.addArtifact(RepositoryUtils.toArtifact(attached));
343         }
344     }
345 
346     private boolean isFile(File file) {
347         return file != null && file.isFile();
348     }
349 
350     /**
351      * Visible for testing.
352      */
353     RemoteRepository getDeploymentRepository(
354             final MavenProject project,
355             final String altSnapshotDeploymentRepository,
356             final String altReleaseDeploymentRepository,
357             final String altDeploymentRepository)
358             throws MojoExecutionException {
359         RemoteRepository repo = null;
360 
361         String altDeploymentRepo;
362         if (ArtifactUtils.isSnapshot(project.getVersion()) && altSnapshotDeploymentRepository != null) {
363             altDeploymentRepo = altSnapshotDeploymentRepository;
364         } else if (!ArtifactUtils.isSnapshot(project.getVersion()) && altReleaseDeploymentRepository != null) {
365             altDeploymentRepo = altReleaseDeploymentRepository;
366         } else {
367             altDeploymentRepo = altDeploymentRepository;
368         }
369 
370         if (altDeploymentRepo != null) {
371             getLog().info("Using alternate deployment repository " + altDeploymentRepo);
372 
373             Matcher matcher = ALT_LEGACY_REPO_SYNTAX_PATTERN.matcher(altDeploymentRepo);
374 
375             if (matcher.matches()) {
376                 String id = matcher.group(1).trim();
377                 String layout = matcher.group(2).trim();
378                 String url = matcher.group(3).trim();
379 
380                 if ("default".equals(layout)) {
381                     getLog().warn("Using legacy syntax for alternative repository. " + "Use \"" + id + "::" + url
382                             + "\" instead.");
383                     repo = getRemoteRepository(id, url);
384                 } else {
385                     throw new MojoExecutionException("Invalid legacy syntax and layout for alternative repository: \""
386                             + altDeploymentRepo + "\". Use \"" + id + "::" + url
387                             + "\" instead, and only default layout is supported.");
388                 }
389             } else {
390                 matcher = ALT_REPO_SYNTAX_PATTERN.matcher(altDeploymentRepo);
391 
392                 if (!matcher.matches()) {
393                     throw new MojoExecutionException("Invalid syntax for alternative repository: \"" + altDeploymentRepo
394                             + "\". Use \"id::url\".");
395                 } else {
396                     String id = matcher.group(1).trim();
397                     String url = matcher.group(2).trim();
398 
399                     repo = getRemoteRepository(id, url);
400                 }
401             }
402         }
403 
404         if (repo == null) {
405             repo = RepositoryUtils.toRepo(project.getDistributionManagementArtifactRepository());
406         }
407 
408         if (repo == null) {
409             String msg = "Deployment failed: repository element was not specified in the POM inside"
410                     + " distributionManagement element or in -DaltDeploymentRepository=id::url parameter";
411 
412             throw new MojoExecutionException(msg);
413         }
414 
415         return repo;
416     }
417 }