View Javadoc
1   package org.apache.maven.plugins.dependency.tree;
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.IOException;
24  import java.io.StringWriter;
25  import java.io.Writer;
26  import java.util.ArrayList;
27  import java.util.Arrays;
28  import java.util.List;
29  
30  import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
31  import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter;
32  import org.apache.maven.artifact.versioning.ArtifactVersion;
33  import org.apache.maven.artifact.versioning.Restriction;
34  import org.apache.maven.artifact.versioning.VersionRange;
35  import org.apache.maven.execution.MavenSession;
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.dependency.utils.DependencyUtil;
40  import org.apache.maven.plugins.annotations.Component;
41  import org.apache.maven.plugins.annotations.Mojo;
42  import org.apache.maven.plugins.annotations.Parameter;
43  import org.apache.maven.plugins.annotations.ResolutionScope;
44  import org.apache.maven.project.DefaultProjectBuildingRequest;
45  import org.apache.maven.project.MavenProject;
46  import org.apache.maven.project.ProjectBuildingRequest;
47  import org.apache.maven.shared.artifact.filter.StrictPatternExcludesArtifactFilter;
48  import org.apache.maven.shared.artifact.filter.StrictPatternIncludesArtifactFilter;
49  import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder;
50  import org.apache.maven.shared.dependency.graph.DependencyGraphBuilderException;
51  import org.apache.maven.shared.dependency.graph.DependencyNode;
52  import org.apache.maven.shared.dependency.graph.filter.AncestorOrSelfDependencyNodeFilter;
53  import org.apache.maven.shared.dependency.graph.filter.AndDependencyNodeFilter;
54  import org.apache.maven.shared.dependency.graph.filter.ArtifactDependencyNodeFilter;
55  import org.apache.maven.shared.dependency.graph.filter.DependencyNodeFilter;
56  import org.apache.maven.shared.dependency.graph.traversal.BuildingDependencyNodeVisitor;
57  import org.apache.maven.shared.dependency.graph.traversal.CollectingDependencyNodeVisitor;
58  import org.apache.maven.shared.dependency.graph.traversal.DependencyNodeVisitor;
59  import org.apache.maven.shared.dependency.graph.traversal.FilteringDependencyNodeVisitor;
60  import org.apache.maven.shared.dependency.graph.traversal.SerializingDependencyNodeVisitor;
61  import org.apache.maven.shared.dependency.graph.traversal.SerializingDependencyNodeVisitor.GraphTokens;
62  
63  /**
64   * Displays the dependency tree for this project.
65   *
66   * @author <a href="mailto:markhobson@gmail.com">Mark Hobson</a>
67   * @since 2.0-alpha-5
68   */
69  @Mojo( name = "tree", requiresDependencyCollection = ResolutionScope.TEST, threadSafe = true )
70  public class TreeMojo
71      extends AbstractMojo
72  {
73      // fields -----------------------------------------------------------------
74  
75      /**
76       * The Maven project.
77       */
78      @Parameter( defaultValue = "${project}", readonly = true, required = true )
79      private MavenProject project;
80  
81      @Parameter( defaultValue = "${session}", readonly = true, required = true )
82      private MavenSession session;
83  
84      /**
85       * Contains the full list of projects in the reactor.
86       */
87      @Parameter( defaultValue = "${reactorProjects}", readonly = true, required = true )
88      private List<MavenProject> reactorProjects;
89  
90      /**
91       * The dependency tree builder to use.
92       */
93      @Component( hint = "default" )
94      private DependencyGraphBuilder dependencyGraphBuilder;
95  
96      /**
97       * If specified, this parameter will cause the dependency tree to be written to the path specified, instead of
98       * writing to the console.
99       *
100      * @since 2.0-alpha-5
101      */
102     @Parameter( property = "outputFile" )
103     private File outputFile;
104 
105     /**
106      * If specified, this parameter will cause the dependency tree to be written using the specified format. Currently
107      * supported format are: <code>text</code>, <code>dot</code>, <code>graphml</code> and <code>tgf</code>.
108      * <p/>
109      * These formats can be plotted to image files. An example of how to plot a dot file using pygraphviz can be found
110      * <a href="http://networkx.lanl.gov/pygraphviz/tutorial.html#layout-and-drawing">here</a>.
111      *
112      * @since 2.2
113      */
114     @Parameter( property = "outputType", defaultValue = "text" )
115     private String outputType;
116 
117     /**
118      * The scope to filter by when resolving the dependency tree, or <code>null</code> to include dependencies from all
119      * scopes. Note that this feature does not currently work due to MSHARED-4
120      *
121      * @see <a href="https://issues.apache.org/jira/browse/MSHARED-4">MSHARED-4</a>
122      * @since 2.0-alpha-5
123      */
124     @Parameter( property = "scope" )
125     private String scope;
126 
127     /**
128      * Whether to include omitted nodes in the serialized dependency tree. Notice this feature actually uses Maven 2
129      * algorithm and <a href="http://maven.apache.org/shared/maven-dependency-tree/">may give wrong results when used
130      * with Maven 3</a>.
131      *
132      * @since 2.0-alpha-6
133      */
134     @Parameter( property = "verbose", defaultValue = "false" )
135     private boolean verbose;
136 
137     /**
138      * The token set name to use when outputting the dependency tree. Possible values are <code>whitespace</code>,
139      * <code>standard</code> or <code>extended</code>, which use whitespace, standard (ie ASCII) or extended character
140      * sets respectively.
141      *
142      * @since 2.0-alpha-6
143      */
144     @Parameter( property = "tokens", defaultValue = "standard" )
145     private String tokens;
146 
147     /**
148      * A comma-separated list of artifacts to filter the serialized dependency tree by, or <code>null</code> not to
149      * filter the dependency tree. The filter syntax is:
150      * 
151      * <pre>
152      * [groupId]:[artifactId]:[type]:[version]
153      * </pre>
154      * 
155      * where each pattern segment is optional and supports full and partial <code>*</code> wildcards. An empty pattern
156      * segment is treated as an implicit wildcard.
157      * <p>
158      * For example, <code>org.apache.*</code> will match all artifacts whose group id starts with
159      * <code>org.apache.</code>, and <code>:::*-SNAPSHOT</code> will match all snapshot artifacts.
160      * </p>
161      * 
162      * @see StrictPatternIncludesArtifactFilter
163      * @since 2.0-alpha-6
164      */
165     @Parameter( property = "includes" )
166     private String includes;
167 
168     /**
169      * A comma-separated list of artifacts to filter from the serialized dependency tree, or <code>null</code> not to
170      * filter any artifacts from the dependency tree. The filter syntax is:
171      * 
172      * <pre>
173      * [groupId]:[artifactId]:[type]:[version]
174      * </pre>
175      * 
176      * where each pattern segment is optional and supports full and partial <code>*</code> wildcards. An empty pattern
177      * segment is treated as an implicit wildcard.
178      * <p>
179      * For example, <code>org.apache.*</code> will match all artifacts whose group id starts with
180      * <code>org.apache.</code>, and <code>:::*-SNAPSHOT</code> will match all snapshot artifacts.
181      * </p>
182      *
183      * @see StrictPatternExcludesArtifactFilter
184      * @since 2.0-alpha-6
185      */
186     @Parameter( property = "excludes" )
187     private String excludes;
188 
189     /**
190      * The computed dependency tree root node of the Maven project.
191      */
192     private DependencyNode rootNode;
193 
194     /**
195      * Whether to append outputs into the output file or overwrite it.
196      *
197      * @since 2.2
198      */
199     @Parameter( property = "appendOutput", defaultValue = "false" )
200     private boolean appendOutput;
201 
202     /**
203      * Skip plugin execution completely.
204      *
205      * @since 2.7
206      */
207     @Parameter( property = "skip", defaultValue = "false" )
208     private boolean skip;
209 
210     // Mojo methods -----------------------------------------------------------
211 
212     /*
213      * @see org.apache.maven.plugin.Mojo#execute()
214      */
215     @Override
216     public void execute()
217         throws MojoExecutionException, MojoFailureException
218     {
219         if ( isSkip() )
220         {
221             getLog().info( "Skipping plugin execution" );
222             return;
223         }
224 
225         try
226         {
227             String dependencyTreeString;
228 
229             // TODO: note that filter does not get applied due to MSHARED-4
230             ArtifactFilter artifactFilter = createResolvingArtifactFilter();
231 
232             if ( verbose )
233             {
234                 // To fix we probably need a different DependencyCollector in Aether, which doesn't remove nodes which
235                 // have already been resolved.
236                 getLog().info( "Verbose not supported since maven-dependency-plugin 3.0" );
237             }
238 
239             ProjectBuildingRequest buildingRequest =
240                 new DefaultProjectBuildingRequest( session.getProjectBuildingRequest() );
241 
242             buildingRequest.setProject( project );
243 
244             // non-verbose mode use dependency graph component, which gives consistent results with Maven version
245             // running
246             rootNode = dependencyGraphBuilder.buildDependencyGraph( buildingRequest, artifactFilter, reactorProjects );
247 
248             dependencyTreeString = serializeDependencyTree( rootNode );
249 
250             if ( outputFile != null )
251             {
252                 DependencyUtil.write( dependencyTreeString, outputFile, this.appendOutput, getLog() );
253 
254                 getLog().info( "Wrote dependency tree to: " + outputFile );
255             }
256             else
257             {
258                 DependencyUtil.log( dependencyTreeString, getLog() );
259             }
260         }
261         catch ( DependencyGraphBuilderException exception )
262         {
263             throw new MojoExecutionException( "Cannot build project dependency graph", exception );
264         }
265         catch ( IOException exception )
266         {
267             throw new MojoExecutionException( "Cannot serialise project dependency graph", exception );
268         }
269     }
270 
271     // public methods ---------------------------------------------------------
272 
273     /**
274      * Gets the Maven project used by this mojo.
275      *
276      * @return the Maven project
277      */
278     public MavenProject getProject()
279     {
280         return project;
281     }
282 
283     /**
284      * Gets the computed dependency graph root node for the Maven project.
285      *
286      * @return the dependency tree root node
287      */
288     public DependencyNode getDependencyGraph()
289     {
290         return rootNode;
291     }
292 
293     /**
294      * @return {@link #skip}
295      */
296     public boolean isSkip()
297     {
298         return skip;
299     }
300 
301     /**
302      * @param skip {@link #skip}
303      */
304     public void setSkip( boolean skip )
305     {
306         this.skip = skip;
307     }
308 
309     // private methods --------------------------------------------------------
310 
311     /**
312      * Gets the artifact filter to use when resolving the dependency tree.
313      *
314      * @return the artifact filter
315      */
316     private ArtifactFilter createResolvingArtifactFilter()
317     {
318         ArtifactFilter filter;
319 
320         // filter scope
321         if ( scope != null )
322         {
323             getLog().debug( "+ Resolving dependency tree for scope '" + scope + "'" );
324 
325             filter = new ScopeArtifactFilter( scope );
326         }
327         else
328         {
329             filter = null;
330         }
331 
332         return filter;
333     }
334 
335     /**
336      * Serializes the specified dependency tree to a string.
337      *
338      * @param theRootNode the dependency tree root node to serialize
339      * @return the serialized dependency tree
340      */
341     private String serializeDependencyTree( DependencyNode theRootNode )
342     {
343         StringWriter writer = new StringWriter();
344 
345         DependencyNodeVisitor visitor = getSerializingDependencyNodeVisitor( writer );
346 
347         // TODO: remove the need for this when the serializer can calculate last nodes from visitor calls only
348         visitor = new BuildingDependencyNodeVisitor( visitor );
349 
350         DependencyNodeFilter filter = createDependencyNodeFilter();
351 
352         if ( filter != null )
353         {
354             CollectingDependencyNodeVisitor collectingVisitor = new CollectingDependencyNodeVisitor();
355             DependencyNodeVisitor firstPassVisitor = new FilteringDependencyNodeVisitor( collectingVisitor, filter );
356             theRootNode.accept( firstPassVisitor );
357 
358             DependencyNodeFilter secondPassFilter =
359                 new AncestorOrSelfDependencyNodeFilter( collectingVisitor.getNodes() );
360             visitor = new FilteringDependencyNodeVisitor( visitor, secondPassFilter );
361         }
362 
363         theRootNode.accept( visitor );
364 
365         return writer.toString();
366     }
367 
368     /**
369      * @param writer {@link Writer}
370      * @return {@link DependencyNodeVisitor}
371      */
372     public DependencyNodeVisitor getSerializingDependencyNodeVisitor( Writer writer )
373     {
374         if ( "graphml".equals( outputType ) )
375         {
376             return new GraphmlDependencyNodeVisitor( writer );
377         }
378         else if ( "tgf".equals( outputType ) )
379         {
380             return new TGFDependencyNodeVisitor( writer );
381         }
382         else if ( "dot".equals( outputType ) )
383         {
384             return new DOTDependencyNodeVisitor( writer );
385         }
386         else
387         {
388             return new SerializingDependencyNodeVisitor( writer, toGraphTokens( tokens ) );
389         }
390     }
391 
392     /**
393      * Gets the graph tokens instance for the specified name.
394      *
395      * @param theTokens the graph tokens name
396      * @return the <code>GraphTokens</code> instance
397      */
398     private GraphTokens toGraphTokens( String theTokens )
399     {
400         GraphTokens graphTokens;
401 
402         if ( "whitespace".equals( theTokens ) )
403         {
404             getLog().debug( "+ Using whitespace tree tokens" );
405 
406             graphTokens = SerializingDependencyNodeVisitor.WHITESPACE_TOKENS;
407         }
408         else if ( "extended".equals( theTokens ) )
409         {
410             getLog().debug( "+ Using extended tree tokens" );
411 
412             graphTokens = SerializingDependencyNodeVisitor.EXTENDED_TOKENS;
413         }
414         else
415         {
416             graphTokens = SerializingDependencyNodeVisitor.STANDARD_TOKENS;
417         }
418 
419         return graphTokens;
420     }
421 
422     /**
423      * Gets the dependency node filter to use when serializing the dependency graph.
424      *
425      * @return the dependency node filter, or <code>null</code> if none required
426      */
427     private DependencyNodeFilter createDependencyNodeFilter()
428     {
429         List<DependencyNodeFilter> filters = new ArrayList<DependencyNodeFilter>();
430 
431         // filter includes
432         if ( includes != null )
433         {
434             List<String> patterns = Arrays.asList( includes.split( "," ) );
435 
436             getLog().debug( "+ Filtering dependency tree by artifact include patterns: " + patterns );
437 
438             ArtifactFilter artifactFilter = new StrictPatternIncludesArtifactFilter( patterns );
439             filters.add( new ArtifactDependencyNodeFilter( artifactFilter ) );
440         }
441 
442         // filter excludes
443         if ( excludes != null )
444         {
445             List<String> patterns = Arrays.asList( excludes.split( "," ) );
446 
447             getLog().debug( "+ Filtering dependency tree by artifact exclude patterns: " + patterns );
448 
449             ArtifactFilter artifactFilter = new StrictPatternExcludesArtifactFilter( patterns );
450             filters.add( new ArtifactDependencyNodeFilter( artifactFilter ) );
451         }
452 
453         return filters.isEmpty() ? null : new AndDependencyNodeFilter( filters );
454     }
455 
456     // following is required because the version handling in maven code
457     // doesn't work properly. I ripped it out of the enforcer rules.
458 
459     /**
460      * Copied from Artifact.VersionRange. This is tweaked to handle singular ranges properly. Currently the default
461      * containsVersion method assumes a singular version means allow everything. This method assumes that "2.0.4" ==
462      * "[2.0.4,)"
463      *
464      * @param allowedRange range of allowed versions.
465      * @param theVersion the version to be checked.
466      * @return true if the version is contained by the range.
467      */
468     public static boolean containsVersion( VersionRange allowedRange, ArtifactVersion theVersion )
469     {
470         ArtifactVersion recommendedVersion = allowedRange.getRecommendedVersion();
471         if ( recommendedVersion == null )
472         {
473             List<Restriction> restrictions = allowedRange.getRestrictions();
474             for ( Restriction restriction : restrictions )
475             {
476                 if ( restriction.containsVersion( theVersion ) )
477                 {
478                     return true;
479                 }
480             }
481         }
482 
483         // only singular versions ever have a recommendedVersion
484         return recommendedVersion.compareTo( theVersion ) <= 0;
485     }
486 }