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.dependency.analyze;
20  
21  import javax.inject.Inject;
22  
23  import java.io.IOException;
24  import java.io.Reader;
25  import java.util.Collections;
26  import java.util.HashSet;
27  import java.util.Iterator;
28  import java.util.LinkedHashSet;
29  import java.util.List;
30  import java.util.Set;
31  import java.util.stream.Collectors;
32  
33  import org.apache.maven.model.Dependency;
34  import org.apache.maven.model.Model;
35  import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
36  import org.apache.maven.plugin.AbstractMojo;
37  import org.apache.maven.plugin.MojoExecutionException;
38  import org.apache.maven.plugin.MojoFailureException;
39  import org.apache.maven.plugins.annotations.Mojo;
40  import org.apache.maven.plugins.annotations.Parameter;
41  import org.apache.maven.project.MavenProject;
42  import org.codehaus.plexus.util.xml.XmlStreamReader;
43  import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
44  
45  /**
46   * Analyzes the <code>&lt;dependencies/&gt;</code> and <code>&lt;dependencyManagement/&gt;</code> tags in the
47   * <code>pom.xml</code> and determines the duplicate declared dependencies.
48   *
49   * @author <a href="mailto:vincent.siveton@gmail.com">Vincent Siveton</a>
50   */
51  @Mojo(name = "analyze-duplicate", aggregator = false, threadSafe = true)
52  public class AnalyzeDuplicateMojo extends AbstractMojo {
53      public static final String MESSAGE_DUPLICATE_DEP_IN_DEPENDENCIES =
54              "List of duplicate dependencies defined in <dependencies/> in your pom.xml:\n";
55  
56      public static final String MESSAGE_DUPLICATE_DEP_IN_DEPMGMT =
57              "List of duplicate dependencies defined in <dependencyManagement/> in your pom.xml:\n";
58  
59      /**
60       * Skip plugin execution completely.
61       *
62       * @since 2.7
63       */
64      @Parameter(property = "mdep.analyze.skip", defaultValue = "false")
65      private boolean skip;
66  
67      /**
68       * The Maven project to analyze.
69       */
70      private MavenProject project;
71  
72      @Inject
73      public AnalyzeDuplicateMojo(MavenProject project) {
74          this.project = project;
75      }
76  
77      /**
78       * {@inheritDoc}
79       */
80      @Override
81      public void execute() throws MojoExecutionException, MojoFailureException {
82          if (skip) {
83              getLog().info("Skipping plugin execution");
84              return;
85          }
86  
87          MavenXpp3Reader pomReader = new MavenXpp3Reader();
88          Model model;
89          try (Reader reader = new XmlStreamReader(project.getFile())) {
90              model = pomReader.read(reader);
91          } catch (IOException | XmlPullParserException e) {
92              throw new MojoExecutionException("Exception: " + e.getMessage(), e);
93          }
94  
95          Set<String> duplicateDependencies = Collections.emptySet();
96          if (model.getDependencies() != null) {
97              duplicateDependencies = findDuplicateDependencies(model.getDependencies());
98          }
99  
100         Set<String> duplicateDependenciesManagement = Collections.emptySet();
101         if (model.getDependencyManagement() != null
102                 && model.getDependencyManagement().getDependencies() != null) {
103             duplicateDependenciesManagement =
104                     findDuplicateDependencies(model.getDependencyManagement().getDependencies());
105         }
106 
107         if (getLog().isInfoEnabled()) {
108             StringBuilder sb = new StringBuilder();
109 
110             createMessage(duplicateDependencies, sb, MESSAGE_DUPLICATE_DEP_IN_DEPENDENCIES);
111             createMessage(duplicateDependenciesManagement, sb, MESSAGE_DUPLICATE_DEP_IN_DEPMGMT);
112 
113             if (sb.length() > 0) {
114                 getLog().info(sb.toString());
115             } else {
116                 getLog().info("No duplicate dependencies found in <dependencies/> or in <dependencyManagement/>");
117             }
118         }
119     }
120 
121     private void createMessage(
122             Set<String> duplicateDependencies, StringBuilder sb, String messageDuplicateDepInDependencies) {
123         if (!duplicateDependencies.isEmpty()) {
124             if (sb.length() > 0) {
125                 sb.append(System.lineSeparator());
126             }
127             sb.append(messageDuplicateDepInDependencies);
128             for (Iterator<String> it = duplicateDependencies.iterator(); it.hasNext(); ) {
129                 String dup = it.next();
130 
131                 sb.append("\to ").append(dup);
132                 if (it.hasNext()) {
133                     sb.append(System.lineSeparator());
134                 }
135             }
136         }
137     }
138 
139     private Set<String> findDuplicateDependencies(List<Dependency> modelDependencies) {
140         List<String> modelDependencies2 =
141                 modelDependencies.stream().map(Dependency::getManagementKey).collect(Collectors.toList());
142         // remove one instance of each element from the list
143         modelDependencies2.removeIf(new HashSet<>(modelDependencies2)::remove);
144         // keep a single instance of each duplicate
145         return new LinkedHashSet<>(modelDependencies2);
146     }
147 }