View Javadoc
1   package org.apache.maven.plugins.dependency.analyze;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.io.File;
23  import java.io.StringWriter;
24  import java.util.ArrayList;
25  import java.util.Arrays;
26  import java.util.Iterator;
27  import java.util.LinkedHashSet;
28  import java.util.List;
29  import java.util.Set;
30  
31  import org.apache.commons.lang.StringUtils;
32  import org.apache.maven.artifact.Artifact;
33  import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
34  import org.apache.maven.plugin.AbstractMojo;
35  import org.apache.maven.plugin.MojoExecutionException;
36  import org.apache.maven.plugin.MojoFailureException;
37  import org.apache.maven.plugins.annotations.Parameter;
38  import org.apache.maven.project.MavenProject;
39  import org.apache.maven.shared.artifact.filter.StrictPatternExcludesArtifactFilter;
40  import org.apache.maven.shared.dependency.analyzer.ProjectDependencyAnalysis;
41  import org.apache.maven.shared.dependency.analyzer.ProjectDependencyAnalyzer;
42  import org.apache.maven.shared.dependency.analyzer.ProjectDependencyAnalyzerException;
43  import org.codehaus.plexus.PlexusConstants;
44  import org.codehaus.plexus.PlexusContainer;
45  import org.codehaus.plexus.context.Context;
46  import org.codehaus.plexus.context.ContextException;
47  import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable;
48  import org.codehaus.plexus.util.xml.PrettyPrintXMLWriter;
49  
50  /**
51   * Analyzes the dependencies of this project and determines which are: used and declared; used and undeclared; unused
52   * and declared.
53   *
54   * @author <a href="mailto:markhobson@gmail.com">Mark Hobson</a>
55   * @since 2.0-alpha-5
56   */
57  public abstract class AbstractAnalyzeMojo
58      extends AbstractMojo
59      implements Contextualizable
60  {
61      // fields -----------------------------------------------------------------
62  
63      /**
64       * The plexus context to look-up the right {@link ProjectDependencyAnalyzer} implementation depending on the mojo
65       * configuration.
66       */
67      private Context context;
68  
69      /**
70       * The Maven project to analyze.
71       */
72      @Parameter( defaultValue = "${project}", readonly = true, required = true )
73      private MavenProject project;
74  
75      /**
76       * Specify the project dependency analyzer to use (plexus component role-hint). By default,
77       * <a href="/shared/maven-dependency-analyzer/">maven-dependency-analyzer</a> is used. To use this, you must declare
78       * a dependency for this plugin that contains the code for the analyzer. The analyzer must have a declared Plexus
79       * role name, and you specify the role name here.
80       *
81       * @since 2.2
82       */
83      @Parameter( property = "analyzer", defaultValue = "default" )
84      private String analyzer;
85  
86      /**
87       * Whether to fail the build if a dependency warning is found.
88       */
89      @Parameter( property = "failOnWarning", defaultValue = "false" )
90      private boolean failOnWarning;
91  
92      /**
93       * Output used dependencies.
94       */
95      @Parameter( property = "verbose", defaultValue = "false" )
96      private boolean verbose;
97  
98      /**
99       * Ignore Runtime/Provided/Test/System scopes for unused dependency analysis.
100      */
101     @Parameter( property = "ignoreNonCompile", defaultValue = "false" )
102     private boolean ignoreNonCompile;
103 
104     /**
105      * Output the xml for the missing dependencies (used but not declared).
106      *
107      * @since 2.0-alpha-5
108      */
109     @Parameter( property = "outputXML", defaultValue = "false" )
110     private boolean outputXML;
111 
112     /**
113      * Output scriptable values for the missing dependencies (used but not declared).
114      *
115      * @since 2.0-alpha-5
116      */
117     @Parameter( property = "scriptableOutput", defaultValue = "false" )
118     private boolean scriptableOutput;
119 
120     /**
121      * Flag to use for scriptable output.
122      *
123      * @since 2.0-alpha-5
124      */
125     @Parameter( property = "scriptableFlag", defaultValue = "$$$%%%" )
126     private String scriptableFlag;
127 
128     /**
129      * Flag to use for scriptable output
130      *
131      * @since 2.0-alpha-5
132      */
133     @Parameter( defaultValue = "${basedir}", readonly = true )
134     private File baseDir;
135 
136     /**
137      * Target folder
138      *
139      * @since 2.0-alpha-5
140      */
141     @Parameter( defaultValue = "${project.build.directory}", readonly = true )
142     private File outputDirectory;
143 
144     /**
145      * Force dependencies as used, to override incomplete result caused by bytecode-level analysis. Dependency format is
146      * <code>groupId:artifactId</code>.
147      *
148      * @since 2.6
149      */
150     @Parameter
151     private String[] usedDependencies;
152 
153     /**
154      * Skip plugin execution completely.
155      *
156      * @since 2.7
157      */
158     @Parameter( property = "mdep.analyze.skip", defaultValue = "false" )
159     private boolean skip;
160 
161     /**
162      * List of dependencies that will be ignored. Any dependency on this list will be excluded from the "declared but
163      * unused" and the "used but undeclared" list. The filter syntax is:
164      *
165      * <pre>
166      * [groupId]:[artifactId]:[type]:[version]
167      * </pre>
168      *
169      * where each pattern segment is optional and supports full and partial <code>*</code> wildcards. An empty pattern
170      * segment is treated as an implicit wildcard. *
171      * <p>
172      * For example, <code>org.apache.*</code> will match all artifacts whose group id starts with
173      * <code>org.apache.</code>, and <code>:::*-SNAPSHOT</code> will match all snapshot artifacts.
174      * </p>
175      *
176      * @since 2.10
177      * @see StrictPatternIncludesArtifactFilter
178      */
179     @Parameter
180     private String[] ignoredDependencies = new String[0];
181 
182     /**
183      * List of dependencies that will be ignored if they are used but undeclared. The filter syntax is:
184      *
185      * <pre>
186      * [groupId]:[artifactId]:[type]:[version]
187      * </pre>
188      *
189      * where each pattern segment is optional and supports full and partial <code>*</code> wildcards. An empty pattern
190      * segment is treated as an implicit wildcard. *
191      * <p>
192      * For example, <code>org.apache.*</code> will match all artifacts whose group id starts with
193      * <code>org.apache.</code>, and <code>:::*-SNAPSHOT</code> will match all snapshot artifacts.
194      * </p>
195      *
196      * @since 2.10
197      * @see StrictPatternIncludesArtifactFilter
198      */
199     @Parameter
200     private String[] ignoredUsedUndeclaredDependencies = new String[0];
201 
202     /**
203      * List of dependencies that will be ignored if they are declared but unused. The filter syntax is:
204      *
205      * <pre>
206      * [groupId]:[artifactId]:[type]:[version]
207      * </pre>
208      *
209      * where each pattern segment is optional and supports full and partial <code>*</code> wildcards. An empty pattern
210      * segment is treated as an implicit wildcard. *
211      * <p>
212      * For example, <code>org.apache.*</code> will match all artifacts whose group id starts with
213      * <code>org.apache.</code>, and <code>:::*-SNAPSHOT</code> will match all snapshot artifacts.
214      * </p>
215      *
216      * @since 2.10
217      * @see StrictPatternIncludesArtifactFilter
218      */
219     @Parameter
220     private String[] ignoredUnusedDeclaredDependencies = new String[0];
221 
222     // Mojo methods -----------------------------------------------------------
223 
224     /*
225      * @see org.apache.maven.plugin.Mojo#execute()
226      */
227     @Override
228     public void execute()
229         throws MojoExecutionException, MojoFailureException
230     {
231         if ( isSkip() )
232         {
233             getLog().info( "Skipping plugin execution" );
234             return;
235         }
236 
237         if ( "pom".equals( project.getPackaging() ) )
238         {
239             getLog().info( "Skipping pom project" );
240             return;
241         }
242 
243         if ( outputDirectory == null || !outputDirectory.exists() )
244         {
245             getLog().info( "Skipping project with no build directory" );
246             return;
247         }
248 
249         boolean warning = checkDependencies();
250 
251         if ( warning && failOnWarning )
252         {
253             throw new MojoExecutionException( "Dependency problems found" );
254         }
255     }
256 
257     /**
258      * @return {@link ProjectDependencyAnalyzer}
259      * @throws MojoExecutionException in case of an error.
260      */
261     protected ProjectDependencyAnalyzer createProjectDependencyAnalyzer()
262         throws MojoExecutionException
263     {
264 
265         final String role = ProjectDependencyAnalyzer.ROLE;
266         final String roleHint = analyzer;
267 
268         try
269         {
270             final PlexusContainer container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY );
271 
272             return (ProjectDependencyAnalyzer) container.lookup( role, roleHint );
273         }
274         catch ( Exception exception )
275         {
276             throw new MojoExecutionException( "Failed to instantiate ProjectDependencyAnalyser with role " + role
277                 + " / role-hint " + roleHint, exception );
278         }
279     }
280 
281     @Override
282     public void contextualize( Context theContext )
283         throws ContextException
284     {
285         this.context = theContext;
286     }
287 
288     /**
289      * @return {@link #skip}
290      */
291     protected final boolean isSkip()
292     {
293         return skip;
294     }
295 
296     // private methods --------------------------------------------------------
297 
298     private boolean checkDependencies()
299         throws MojoExecutionException
300     {
301         ProjectDependencyAnalysis analysis;
302         try
303         {
304             analysis = createProjectDependencyAnalyzer().analyze( project );
305 
306             if ( usedDependencies != null )
307             {
308                 analysis = analysis.forceDeclaredDependenciesUsage( usedDependencies );
309             }
310         }
311         catch ( ProjectDependencyAnalyzerException exception )
312         {
313             throw new MojoExecutionException( "Cannot analyze dependencies", exception );
314         }
315 
316         if ( ignoreNonCompile )
317         {
318             analysis = analysis.ignoreNonCompile();
319         }
320 
321         Set<Artifact> usedDeclared = new LinkedHashSet<Artifact>( analysis.getUsedDeclaredArtifacts() );
322         Set<Artifact> usedUndeclared = new LinkedHashSet<Artifact>( analysis.getUsedUndeclaredArtifacts() );
323         Set<Artifact> unusedDeclared = new LinkedHashSet<Artifact>( analysis.getUnusedDeclaredArtifacts() );
324 
325         Set<Artifact> ignoredUsedUndeclared = new LinkedHashSet<Artifact>();
326         Set<Artifact> ignoredUnusedDeclared = new LinkedHashSet<Artifact>();
327 
328         ignoredUsedUndeclared.addAll( filterDependencies( usedUndeclared, ignoredDependencies ) );
329         ignoredUsedUndeclared.addAll( filterDependencies( usedUndeclared, ignoredUsedUndeclaredDependencies ) );
330 
331         ignoredUnusedDeclared.addAll( filterDependencies( unusedDeclared, ignoredDependencies ) );
332         ignoredUnusedDeclared.addAll( filterDependencies( unusedDeclared, ignoredUnusedDeclaredDependencies ) );
333 
334         boolean reported = false;
335         boolean warning = false;
336 
337         if ( verbose && !usedDeclared.isEmpty() )
338         {
339             getLog().info( "Used declared dependencies found:" );
340 
341             logArtifacts( analysis.getUsedDeclaredArtifacts(), false );
342             reported = true;
343         }
344 
345         if ( !usedUndeclared.isEmpty() )
346         {
347             getLog().warn( "Used undeclared dependencies found:" );
348 
349             logArtifacts( usedUndeclared, true );
350             reported = true;
351             warning = true;
352         }
353 
354         if ( !unusedDeclared.isEmpty() )
355         {
356             getLog().warn( "Unused declared dependencies found:" );
357 
358             logArtifacts( unusedDeclared, true );
359             reported = true;
360             warning = true;
361         }
362 
363         if ( verbose && !ignoredUsedUndeclared.isEmpty() )
364         {
365             getLog().info( "Ignored used undeclared dependencies:" );
366 
367             logArtifacts( ignoredUsedUndeclared, false );
368             reported = true;
369         }
370 
371         if ( verbose && !ignoredUnusedDeclared.isEmpty() )
372         {
373             getLog().info( "Ignored unused declared dependencies:" );
374 
375             logArtifacts( ignoredUnusedDeclared, false );
376             reported = true;
377         }
378 
379         if ( outputXML )
380         {
381             writeDependencyXML( usedUndeclared );
382         }
383 
384         if ( scriptableOutput )
385         {
386             writeScriptableOutput( usedUndeclared );
387         }
388 
389         if ( !reported )
390         {
391             getLog().info( "No dependency problems found" );
392         }
393 
394         return warning;
395     }
396 
397     private void logArtifacts( Set<Artifact> artifacts, boolean warn )
398     {
399         if ( artifacts.isEmpty() )
400         {
401             getLog().info( "   None" );
402         }
403         else
404         {
405             for ( Artifact artifact : artifacts )
406             {
407                 // called because artifact will set the version to -SNAPSHOT only if I do this. MNG-2961
408                 artifact.isSnapshot();
409 
410                 if ( warn )
411                 {
412                     getLog().warn( "   " + artifact );
413                 }
414                 else
415                 {
416                     getLog().info( "   " + artifact );
417                 }
418 
419             }
420         }
421     }
422 
423     private void writeDependencyXML( Set<Artifact> artifacts )
424     {
425         if ( !artifacts.isEmpty() )
426         {
427             getLog().info( "Add the following to your pom to correct the missing dependencies: " );
428 
429             StringWriter out = new StringWriter();
430             PrettyPrintXMLWriter writer = new PrettyPrintXMLWriter( out );
431 
432             for ( Artifact artifact : artifacts )
433             {
434                 // called because artifact will set the version to -SNAPSHOT only if I do this. MNG-2961
435                 artifact.isSnapshot();
436 
437                 writer.startElement( "dependency" );
438                 writer.startElement( "groupId" );
439                 writer.writeText( artifact.getGroupId() );
440                 writer.endElement();
441                 writer.startElement( "artifactId" );
442                 writer.writeText( artifact.getArtifactId() );
443                 writer.endElement();
444                 writer.startElement( "version" );
445                 writer.writeText( artifact.getBaseVersion() );
446                 if ( !StringUtils.isBlank( artifact.getClassifier() ) )
447                 {
448                     writer.startElement( "classifier" );
449                     writer.writeText( artifact.getClassifier() );
450                     writer.endElement();
451                 }
452                 writer.endElement();
453 
454                 if ( !Artifact.SCOPE_COMPILE.equals( artifact.getScope() ) )
455                 {
456                     writer.startElement( "scope" );
457                     writer.writeText( artifact.getScope() );
458                     writer.endElement();
459                 }
460                 writer.endElement();
461             }
462 
463             getLog().info( "\n" + out.getBuffer() );
464         }
465     }
466 
467     private void writeScriptableOutput( Set<Artifact> artifacts )
468     {
469         if ( !artifacts.isEmpty() )
470         {
471             getLog().info( "Missing dependencies: " );
472             String pomFile = baseDir.getAbsolutePath() + File.separatorChar + "pom.xml";
473             StringBuilder buf = new StringBuilder();
474 
475             for ( Artifact artifact : artifacts )
476             {
477                 // called because artifact will set the version to -SNAPSHOT only if I do this. MNG-2961
478                 artifact.isSnapshot();
479 
480                 //CHECKSTYLE_OFF: LineLength
481                 buf.append( scriptableFlag )
482                    .append( ":" )
483                    .append( pomFile )
484                    .append( ":" )
485                    .append( artifact.getDependencyConflictId() )
486                    .append( ":" )
487                    .append( artifact.getClassifier() )
488                    .append( ":" )
489                    .append( artifact.getBaseVersion() )
490                    .append( ":" )
491                    .append( artifact.getScope() )
492                    .append( "\n" );
493                 //CHECKSTYLE_ON: LineLength
494             }
495             getLog().info( "\n" + buf );
496         }
497     }
498 
499     private List<Artifact> filterDependencies( Set<Artifact> artifacts, String[] excludes )
500         throws MojoExecutionException
501     {
502         ArtifactFilter filter = new StrictPatternExcludesArtifactFilter( Arrays.asList( excludes ) );
503         List<Artifact> result = new ArrayList<Artifact>();
504 
505         for ( Iterator<Artifact> it = artifacts.iterator(); it.hasNext(); )
506         {
507             Artifact artifact = it.next();
508             if ( !filter.include( artifact ) )
509             {
510                 it.remove();
511                 result.add( artifact );
512             }
513         }
514 
515         return result;
516     }
517 }