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