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