View Javadoc

1   package org.apache.maven.plugins.enforcer;
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.util.ArrayList;
23  import java.util.Collections;
24  import java.util.List;
25  
26  import org.apache.maven.artifact.Artifact;
27  import org.apache.maven.artifact.factory.ArtifactFactory;
28  import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
29  import org.apache.maven.artifact.repository.ArtifactRepository;
30  import org.apache.maven.artifact.resolver.ArtifactCollector;
31  import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
32  import org.apache.maven.enforcer.rule.api.EnforcerRule;
33  import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
34  import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
35  import org.apache.maven.plugin.logging.Log;
36  import org.apache.maven.plugins.enforcer.utils.DependencyVersionMap;
37  import org.apache.maven.project.MavenProject;
38  import org.apache.maven.shared.dependency.tree.DependencyNode;
39  import org.apache.maven.shared.dependency.tree.DependencyTreeBuilder;
40  import org.apache.maven.shared.dependency.tree.DependencyTreeBuilderException;
41  import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
42  import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
43  import org.codehaus.plexus.i18n.I18N;
44  
45  /**
46   * @author <a href="mailto:rex@e-hoffman.org">Rex Hoffman</a>
47   */
48  public class DependencyConvergence
49      implements EnforcerRule
50  {
51  
52      private static Log log;
53  
54      private static I18N i18n;
55      
56      private boolean uniqueVersions; 
57  
58      public void setUniqueVersions( boolean uniqueVersions )
59      {
60          this.uniqueVersions = uniqueVersions;
61      }
62      
63      /**
64       * Uses the {@link EnforcerRuleHelper} to populate the values of the
65       * {@link DependencyTreeBuilder#buildDependencyTree(MavenProject, ArtifactRepository, ArtifactFactory, ArtifactMetadataSource, ArtifactFilter, ArtifactCollector)}
66       * factory method. <br/>
67       * This method simply exists to hide all the ugly lookup that the {@link EnforcerRuleHelper} has to do.
68       * 
69       * @param helper
70       * @return a Dependency Node which is the root of the project's dependency tree
71       * @throws EnforcerRuleException
72       */
73      private DependencyNode getNode( EnforcerRuleHelper helper )
74          throws EnforcerRuleException
75      {
76          try
77          {
78              MavenProject project = (MavenProject) helper.evaluate( "${project}" );
79              DependencyTreeBuilder dependencyTreeBuilder =
80                  (DependencyTreeBuilder) helper.getComponent( DependencyTreeBuilder.class );
81              ArtifactRepository repository = (ArtifactRepository) helper.evaluate( "${localRepository}" );
82              ArtifactFactory factory = (ArtifactFactory) helper.getComponent( ArtifactFactory.class );
83              ArtifactMetadataSource metadataSource =
84                  (ArtifactMetadataSource) helper.getComponent( ArtifactMetadataSource.class );
85              ArtifactCollector collector = (ArtifactCollector) helper.getComponent( ArtifactCollector.class );
86              ArtifactFilter filter = null; // we need to evaluate all scopes
87              DependencyNode node =
88                  dependencyTreeBuilder.buildDependencyTree( project, repository, factory, metadataSource, filter,
89                                                             collector );
90              return node;
91          }
92          catch ( ExpressionEvaluationException e )
93          {
94              throw new EnforcerRuleException( "Unable to lookup an expression " + e.getLocalizedMessage(), e );
95          }
96          catch ( ComponentLookupException e )
97          {
98              throw new EnforcerRuleException( "Unable to lookup a component " + e.getLocalizedMessage(), e );
99          }
100         catch ( DependencyTreeBuilderException e )
101         {
102             throw new EnforcerRuleException( "Could not build dependency tree " + e.getLocalizedMessage(), e );
103         }
104     }
105 
106     public void execute( EnforcerRuleHelper helper )
107         throws EnforcerRuleException
108     {
109         if ( log == null )
110         {
111             log = helper.getLog();
112         }
113         try
114         {
115             if ( i18n == null )
116             {
117                 i18n = (I18N) helper.getComponent( I18N.class );
118             }
119             DependencyNode node = getNode( helper );
120             DependencyVersionMap visitor = new DependencyVersionMap( log );
121             visitor.setUniqueVersions( uniqueVersions );
122             node.accept( visitor );
123             List<CharSequence> errorMsgs = new ArrayList<CharSequence>();
124             errorMsgs.addAll( getConvergenceErrorMsgs( visitor.getConflictedVersionNumbers() ) );
125             for ( CharSequence errorMsg : errorMsgs )
126             {
127                 log.warn( errorMsg );
128             }
129             if ( errorMsgs.size() > 0 )
130             {
131                 throw new EnforcerRuleException( "Failed while enforcing releasability the error(s) are " + errorMsgs );
132             }
133         }
134         catch ( ComponentLookupException e )
135         {
136             throw new EnforcerRuleException( "Unable to lookup a component " + e.getLocalizedMessage(), e );
137         }
138         catch ( Exception e )
139         {
140             throw new EnforcerRuleException( e.getLocalizedMessage(), e );
141         }
142     }
143 
144     private String getFullArtifactName( Artifact artifact )
145     {
146         return artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion();
147     }
148 
149     private StringBuilder buildTreeString( DependencyNode node )
150     {
151         List<String> loc = new ArrayList<String>();
152         DependencyNode currentNode = node;
153         while ( currentNode != null )
154         {
155             loc.add( getFullArtifactName( currentNode.getArtifact() ) );
156             currentNode = currentNode.getParent();
157         }
158         Collections.reverse( loc );
159         StringBuilder builder = new StringBuilder();
160         for ( int i = 0; i < loc.size(); i++ )
161         {
162             for ( int j = 0; j < i; j++ )
163             {
164                 builder.append( "  " );
165             }
166             builder.append( "+-" + loc.get( i ) );
167             builder.append( "\n" );
168         }
169         return builder;
170     }
171 
172     private List<String> getConvergenceErrorMsgs( List<List<DependencyNode>> errors )
173     {
174         List<String> errorMsgs = new ArrayList<String>();
175         for ( List<DependencyNode> nodeList : errors )
176         {
177             errorMsgs.add( buildConvergenceErrorMsg( nodeList ) );
178         }
179         return errorMsgs;
180     }
181 
182     private String buildConvergenceErrorMsg( List<DependencyNode> nodeList )
183     {
184         StringBuilder builder = new StringBuilder();
185         builder.append( "\nDependency convergence error for " + getFullArtifactName( nodeList.get( 0 ).getArtifact() )
186             + " paths to dependency are:\n" );
187         if ( nodeList.size() > 0 )
188         {
189             builder.append( buildTreeString( nodeList.get( 0 ) ) );
190         }
191         for ( DependencyNode node : nodeList.subList( 1, nodeList.size() ) )
192         {
193             builder.append( "and\n" );
194             builder.append( buildTreeString( node ) );
195         }
196         return builder.toString();
197     }
198 
199     /**
200      * If your rule is cacheable, you must return a unique id when parameters or conditions change that would cause the
201      * result to be different. Multiple cached results are stored based on their id. The easiest way to do this is to
202      * return a hash computed from the values of your parameters. If your rule is not cacheable, then the result here is
203      * not important, you may return anything.
204      */
205     public String getCacheId()
206     {
207         return "";
208     }
209 
210     /**
211      * This tells the system if the results are cacheable at all. Keep in mind that during forked builds and other
212      * things, a given rule may be executed more than once for the same project. This means that even things that change
213      * from project to project may still be cacheable in certain instances.
214      */
215     public boolean isCacheable()
216     {
217         return false;
218     }
219 
220     /**
221      * If the rule is cacheable and the same id is found in the cache, the stored results are passed to this method to
222      * allow double checking of the results. Most of the time this can be done by generating unique ids, but sometimes
223      * the results of objects returned by the helper need to be queried. You may for example, store certain objects in
224      * your rule and then query them later.
225      * 
226      * @param rule
227      */
228     public boolean isResultValid( EnforcerRule rule )
229     {
230         return false;
231     }
232 }