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   * @version $Id: TreeMojo.java 1807877 2017-09-09 10:35:59Z khmarbaise $
68   * @since 2.0-alpha-5
69   */
70  @Mojo( name = "tree", requiresDependencyCollection = ResolutionScope.TEST, threadSafe = true )
71  public class TreeMojo
72      extends AbstractMojo
73  {
74      // fields -----------------------------------------------------------------
75  
76      /**
77       * The Maven project.
78       */
79      @Parameter( defaultValue = "${project}", readonly = true, required = true )
80      private MavenProject project;
81  
82      @Parameter( defaultValue = "${session}", readonly = true, required = true )
83      private MavenSession session;
84  
85      /**
86       * Contains the full list of projects in the reactor.
87       */
88      @Parameter( defaultValue = "${reactorProjects}", readonly = true, required = true )
89      private List<MavenProject> reactorProjects;
90  
91      /**
92       * The dependency tree builder to use.
93       */
94      @Component( hint = "default" )
95      private DependencyGraphBuilder dependencyGraphBuilder;
96  
97      /**
98       * If specified, this parameter will cause the dependency tree to be written to the path specified, instead of
99       * writing to the console.
100      *
101      * @since 2.0-alpha-5
102      */
103     @Parameter( property = "outputFile" )
104     private File outputFile;
105 
106     /**
107      * If specified, this parameter will cause the dependency tree to be written using the specified format. Currently
108      * supported format are: <code>text</code>, <code>dot</code>, <code>graphml</code> and <code>tgf</code>.
109      * <p/>
110      * These formats can be plotted to image files. An example of how to plot a dot file using pygraphviz can be found
111      * <a href="http://networkx.lanl.gov/pygraphviz/tutorial.html#layout-and-drawing">here</a>.
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="http://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     public boolean isSkip()
295     {
296         return skip;
297     }
298 
299     public void setSkip( boolean skip )
300     {
301         this.skip = skip;
302     }
303 
304     // private methods --------------------------------------------------------
305 
306     /**
307      * Gets the artifact filter to use when resolving the dependency tree.
308      *
309      * @return the artifact filter
310      */
311     private ArtifactFilter createResolvingArtifactFilter()
312     {
313         ArtifactFilter filter;
314 
315         // filter scope
316         if ( scope != null )
317         {
318             getLog().debug( "+ Resolving dependency tree for scope '" + scope + "'" );
319 
320             filter = new ScopeArtifactFilter( scope );
321         }
322         else
323         {
324             filter = null;
325         }
326 
327         return filter;
328     }
329 
330     /**
331      * Serializes the specified dependency tree to a string.
332      *
333      * @param rootNode the dependency tree root node to serialize
334      * @return the serialized dependency tree
335      */
336     private String serializeDependencyTree( DependencyNode rootNode )
337     {
338         StringWriter writer = new StringWriter();
339 
340         DependencyNodeVisitor visitor = getSerializingDependencyNodeVisitor( writer );
341 
342         // TODO: remove the need for this when the serializer can calculate last nodes from visitor calls only
343         visitor = new BuildingDependencyNodeVisitor( visitor );
344 
345         DependencyNodeFilter filter = createDependencyNodeFilter();
346 
347         if ( filter != null )
348         {
349             CollectingDependencyNodeVisitor collectingVisitor = new CollectingDependencyNodeVisitor();
350             DependencyNodeVisitor firstPassVisitor = new FilteringDependencyNodeVisitor( collectingVisitor, filter );
351             rootNode.accept( firstPassVisitor );
352 
353             DependencyNodeFilter secondPassFilter =
354                 new AncestorOrSelfDependencyNodeFilter( collectingVisitor.getNodes() );
355             visitor = new FilteringDependencyNodeVisitor( visitor, secondPassFilter );
356         }
357 
358         rootNode.accept( visitor );
359 
360         return writer.toString();
361     }
362 
363     public DependencyNodeVisitor getSerializingDependencyNodeVisitor( Writer writer )
364     {
365         if ( "graphml".equals( outputType ) )
366         {
367             return new GraphmlDependencyNodeVisitor( writer );
368         }
369         else if ( "tgf".equals( outputType ) )
370         {
371             return new TGFDependencyNodeVisitor( writer );
372         }
373         else if ( "dot".equals( outputType ) )
374         {
375             return new DOTDependencyNodeVisitor( writer );
376         }
377         else
378         {
379             return new SerializingDependencyNodeVisitor( writer, toGraphTokens( tokens ) );
380         }
381     }
382 
383     /**
384      * Gets the graph tokens instance for the specified name.
385      *
386      * @param tokens the graph tokens name
387      * @return the <code>GraphTokens</code> instance
388      */
389     private GraphTokens toGraphTokens( String tokens )
390     {
391         GraphTokens graphTokens;
392 
393         if ( "whitespace".equals( tokens ) )
394         {
395             getLog().debug( "+ Using whitespace tree tokens" );
396 
397             graphTokens = SerializingDependencyNodeVisitor.WHITESPACE_TOKENS;
398         }
399         else if ( "extended".equals( tokens ) )
400         {
401             getLog().debug( "+ Using extended tree tokens" );
402 
403             graphTokens = SerializingDependencyNodeVisitor.EXTENDED_TOKENS;
404         }
405         else
406         {
407             graphTokens = SerializingDependencyNodeVisitor.STANDARD_TOKENS;
408         }
409 
410         return graphTokens;
411     }
412 
413     /**
414      * Gets the dependency node filter to use when serializing the dependency graph.
415      *
416      * @return the dependency node filter, or <code>null</code> if none required
417      */
418     private DependencyNodeFilter createDependencyNodeFilter()
419     {
420         List<DependencyNodeFilter> filters = new ArrayList<DependencyNodeFilter>();
421 
422         // filter includes
423         if ( includes != null )
424         {
425             List<String> patterns = Arrays.asList( includes.split( "," ) );
426 
427             getLog().debug( "+ Filtering dependency tree by artifact include patterns: " + patterns );
428 
429             ArtifactFilter artifactFilter = new StrictPatternIncludesArtifactFilter( patterns );
430             filters.add( new ArtifactDependencyNodeFilter( artifactFilter ) );
431         }
432 
433         // filter excludes
434         if ( excludes != null )
435         {
436             List<String> patterns = Arrays.asList( excludes.split( "," ) );
437 
438             getLog().debug( "+ Filtering dependency tree by artifact exclude patterns: " + patterns );
439 
440             ArtifactFilter artifactFilter = new StrictPatternExcludesArtifactFilter( patterns );
441             filters.add( new ArtifactDependencyNodeFilter( artifactFilter ) );
442         }
443 
444         return filters.isEmpty() ? null : new AndDependencyNodeFilter( filters );
445     }
446 
447     // following is required because the version handling in maven code
448     // doesn't work properly. I ripped it out of the enforcer rules.
449 
450     /**
451      * Copied from Artifact.VersionRange. This is tweaked to handle singular ranges properly. Currently the default
452      * containsVersion method assumes a singular version means allow everything. This method assumes that "2.0.4" ==
453      * "[2.0.4,)"
454      *
455      * @param allowedRange range of allowed versions.
456      * @param theVersion the version to be checked.
457      * @return true if the version is contained by the range.
458      */
459     public static boolean containsVersion( VersionRange allowedRange, ArtifactVersion theVersion )
460     {
461         ArtifactVersion recommendedVersion = allowedRange.getRecommendedVersion();
462         if ( recommendedVersion == null )
463         {
464             List<Restriction> restrictions = allowedRange.getRestrictions();
465             for ( Restriction restriction : restrictions )
466             {
467                 if ( restriction.containsVersion( theVersion ) )
468                 {
469                     return true;
470                 }
471             }
472         }
473 
474         // only singular versions ever have a recommendedVersion
475         return recommendedVersion.compareTo( theVersion ) <= 0;
476     }
477 }