View Javadoc
1   package org.apache.maven.plugin.plugin;
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 org.apache.maven.artifact.Artifact;
23  import org.apache.maven.artifact.repository.ArtifactRepository;
24  import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
25  import org.apache.maven.artifact.resolver.filter.IncludesArtifactFilter;
26  import org.apache.maven.plugin.AbstractMojo;
27  import org.apache.maven.plugin.MojoExecutionException;
28  import org.apache.maven.plugin.descriptor.InvalidPluginDescriptorException;
29  import org.apache.maven.plugin.descriptor.PluginDescriptor;
30  import org.apache.maven.plugins.annotations.Component;
31  import org.apache.maven.plugins.annotations.Parameter;
32  import org.apache.maven.project.MavenProject;
33  import org.apache.maven.tools.plugin.DefaultPluginToolsRequest;
34  import org.apache.maven.tools.plugin.PluginToolsRequest;
35  import org.apache.maven.tools.plugin.extractor.ExtractionException;
36  import org.apache.maven.tools.plugin.generator.Generator;
37  import org.apache.maven.tools.plugin.generator.GeneratorException;
38  import org.apache.maven.tools.plugin.generator.GeneratorUtils;
39  import org.apache.maven.tools.plugin.scanner.MojoScanner;
40  import org.codehaus.plexus.component.repository.ComponentDependency;
41  import org.codehaus.plexus.util.ReaderFactory;
42  
43  import java.io.File;
44  import java.util.Arrays;
45  import java.util.LinkedHashSet;
46  import java.util.List;
47  import java.util.Set;
48  
49  /**
50   * Abstract class for this Plugin.
51   *
52   * @author <a href="mailto:jason@maven.org">Jason van Zyl</a>
53   *
54   */
55  public abstract class AbstractGeneratorMojo
56      extends AbstractMojo
57  {
58      /**
59       * The project currently being built.
60       */
61      @Parameter( defaultValue = "${project}", readonly = true )
62      protected MavenProject project;
63  
64      /**
65       * The component used for scanning the source tree for mojos.
66       */
67      @Component
68      protected MojoScanner mojoScanner;
69  
70      /**
71       * The file encoding of the source files.
72       *
73       * @since 2.5
74       */
75      @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" )
76      protected String encoding;
77  
78      /**
79       * The goal prefix that will appear before the ":".
80       */
81      @Parameter
82      protected String goalPrefix;
83  
84      /**
85       * By default an exception is throw if no mojo descriptor is found. As the maven-plugin is defined in core, the
86       * descriptor generator mojo is bound to generate-resources phase.
87       * But for annotations, the compiled classes are needed, so skip error
88       *
89       * @since 3.0
90       */
91      @Parameter( property = "maven.plugin.skipErrorNoDescriptorsFound", defaultValue = "false" )
92      protected boolean skipErrorNoDescriptorsFound;
93  
94      /**
95       * <p>
96       * The role names of mojo extractors to use.
97       * </p>
98       * <p>
99       * If not set, all mojo extractors will be used. If set to an empty extractor name, no mojo extractors
100      * will be used.
101      * </p>
102      * Example:
103      * <pre>
104      *  &lt;!-- Use all mojo extractors --&gt;
105      *  &lt;extractors/&gt;
106      *
107      *  &lt;!-- Use no mojo extractors --&gt;
108      *  &lt;extractors&gt;
109      *      &lt;extractor/&gt;
110      *  &lt;/extractors&gt;
111      *
112      *  &lt;!-- Use only bsh mojo extractor --&gt;
113      *  &lt;extractors&gt;
114      *      &lt;extractor&gt;bsh&lt;/extractor&gt;
115      *  &lt;/extractors&gt;
116      * </pre>
117      */
118     @Parameter
119     protected Set<String> extractors;
120 
121     /**
122      * Set this to "true" to skip invoking any goals or reports of the plugin.
123      *
124      * @since 2.8
125      */
126     @Parameter( defaultValue = "false", property = "maven.plugin.skip" )
127     protected boolean skip;
128 
129     /**
130      * The set of dependencies for the current project
131      *
132      * @since 3.0
133      */
134     @Parameter( defaultValue = "${project.artifacts}", required = true, readonly = true )
135     protected Set<Artifact> dependencies;
136     
137     /**
138      * Specify the dependencies as {@code groupId:artifactId} containing (abstract) Mojos, to filter
139      * dependencies scanned at runtime and focus on dependencies that are really useful to Mojo analysis.
140      * By default, the value is {@code null} and all dependencies are scanned (as before this parameter was added).
141      * If specified in the configuration with no children, no dependencies are scanned.
142      * 
143      * @since 3.5
144      */
145     @Parameter
146     private List<String> mojoDependencies;
147 
148     /**
149      * List of Remote Repositories used by the resolver
150      *
151      * @since 3.0
152      */
153     @Parameter( defaultValue = "${project.remoteArtifactRepositories}", required = true, readonly = true )
154     protected List<ArtifactRepository> remoteRepos;
155 
156     /**
157      * Location of the local repository.
158      *
159      * @since 3.0
160      */
161     @Parameter( defaultValue = "${localRepository}", required = true, readonly = true )
162     protected ArtifactRepository local;
163 
164     /**
165      * Maven plugin packaging types. Default is single "maven-plugin".
166      * 
167      * @since 3.3
168      */
169     @Parameter
170     protected List<String> packagingTypes = Arrays.asList( "maven-plugin" );
171 
172     /**
173      * @return the output directory where files will be generated.
174      */
175     protected abstract File getOutputDirectory();
176 
177     /**
178      * @return the wanted <code>Generator</code> implementation.
179      */
180     protected abstract Generator createGenerator();
181 
182     /**
183      * {@inheritDoc}
184      */
185     public void execute()
186         throws MojoExecutionException
187     {
188         if ( !packagingTypes.contains( project.getPackaging() ) )
189         {
190             getLog().warn( "Unsupported packaging type " + project.getPackaging() + ", execution skipped" );
191             return;
192         }
193         if ( skip )
194         {
195             getLog().warn( "Execution skipped" );
196             return;
197         }
198 
199         if ( project.getArtifactId().toLowerCase().startsWith( "maven-" )
200             && project.getArtifactId().toLowerCase().endsWith( "-plugin" ) && !"org.apache.maven.plugins".equals(
201             project.getGroupId() ) )
202         {
203             getLog().error( "\n\nArtifact Ids of the format maven-___-plugin are reserved for \n"
204                                 + "plugins in the Group Id org.apache.maven.plugins\n"
205                                 + "Please change your artifactId to the format ___-maven-plugin\n"
206                                 + "In the future this error will break the build.\n\n" );
207         }
208 
209         String defaultGoalPrefix = PluginDescriptor.getGoalPrefixFromArtifactId( project.getArtifactId() );
210         if ( goalPrefix == null )
211         {
212             goalPrefix = defaultGoalPrefix;
213         }
214         else if ( !goalPrefix.equals( defaultGoalPrefix ) )
215         {
216             getLog().warn(
217                 "\n\nGoal prefix is specified as: '" + goalPrefix + "'. " + "Maven currently expects it to be '"
218                     + defaultGoalPrefix + "'.\n" );
219         }
220 
221         mojoScanner.setActiveExtractors( extractors );
222 
223         // TODO: could use this more, eg in the writing of the plugin descriptor!
224         PluginDescriptor pluginDescriptor = new PluginDescriptor();
225 
226         pluginDescriptor.setGroupId( project.getGroupId() );
227 
228         pluginDescriptor.setArtifactId( project.getArtifactId() );
229 
230         pluginDescriptor.setVersion( project.getVersion() );
231 
232         pluginDescriptor.setGoalPrefix( goalPrefix );
233 
234         pluginDescriptor.setName( project.getName() );
235 
236         pluginDescriptor.setDescription( project.getDescription() );
237 
238         if ( encoding == null || encoding.length() < 1 )
239         {
240             getLog().warn( "Using platform encoding (" + ReaderFactory.FILE_ENCODING
241                                + " actually) to read mojo source files, i.e. build is platform dependent!" );
242         }
243         else
244         {
245             getLog().info( "Using '" + encoding + "' encoding to read mojo source files." );
246         }
247 
248         try
249         {
250             List<ComponentDependency> deps = GeneratorUtils.toComponentDependencies( project.getRuntimeDependencies() );
251             pluginDescriptor.setDependencies( deps );
252 
253             PluginToolsRequest request = new DefaultPluginToolsRequest( project, pluginDescriptor );
254             request.setEncoding( encoding );
255             request.setSkipErrorNoDescriptorsFound( skipErrorNoDescriptorsFound );
256             request.setDependencies( filterMojoDependencies() );
257             request.setLocal( this.local );
258             request.setRemoteRepos( this.remoteRepos );
259 
260             mojoScanner.populatePluginDescriptor( request );
261 
262             getOutputDirectory().mkdirs();
263 
264             createGenerator().execute( getOutputDirectory(), request );
265         }
266         catch ( GeneratorException e )
267         {
268             throw new MojoExecutionException( "Error writing plugin descriptor", e );
269         }
270         catch ( InvalidPluginDescriptorException e )
271         {
272             throw new MojoExecutionException( "Error extracting plugin descriptor: \'" + e.getLocalizedMessage() + "\'",
273                                               e );
274         }
275         catch ( ExtractionException e )
276         {
277             throw new MojoExecutionException( "Error extracting plugin descriptor: \'" + e.getLocalizedMessage() + "\'",
278                                               e );
279         }
280         catch ( LinkageError e )
281         {
282             throw new MojoExecutionException( "The API of the mojo scanner is not compatible with this plugin version."
283                 + " Please check the plugin dependencies configured in the POM and ensure the versions match.", e );
284         }
285     }
286 
287     /**
288      * Get dependencies filtered with mojoDependencies configuration.
289      * 
290      * @return eventually filtered dependencies, or even <code>null</code> if configured with empty mojoDependencies
291      * list
292      * @see #mojoDependencies
293      */
294     private Set<Artifact> filterMojoDependencies()
295     {
296         Set<Artifact> filteredDependencies;
297         if ( mojoDependencies == null )
298         {
299             filteredDependencies = dependencies;
300         }
301         else if ( mojoDependencies.size() == 0 )
302         {
303             filteredDependencies = null;
304         }
305         else
306         {
307             filteredDependencies = new LinkedHashSet<>();
308             
309             ArtifactFilter filter = new IncludesArtifactFilter( mojoDependencies );
310 
311             for ( Artifact artifact : dependencies )
312             {
313                 if ( filter.include( artifact ) )
314                 {
315                     filteredDependencies.add( artifact );
316                 }
317             }
318         }
319 
320         return filteredDependencies;
321     }
322 }