Determining Maven execution phase within a plugin

2019-06-15 10:42发布

I have a plugin which transforms the compiled classes. This transformation needs to be done for both the module's classes and the module's test classes. Thus, I bind the plugin to both the process-classes and process-test-classes phases. The problem I have is that I need to determine which phase the plugin is currently executing in, as I do not (cannot, actually) transform the same set of classes twice.

Thus, within the plugin, I would need to know if I'm executing process-classes - in which case I transform the module's classes. Or if I'm executing process-test-classes - in which I case I do not transform the module's classes and transform only the module's test classes.

I could, of course, create two plugins for this, but this kind of solution deeply offends my sensibilities and is probably against the law in several states.

It seems like something I could reach from my module should be able to tell me what the current phase is. I just can't for the life of me find out what that something is.

Thanks...

3条回答
2楼-- · 2019-06-15 11:32

Java plugin code snippets:

import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugins.annotations.Component;

...

@Component
private MojoExecution execution;
...
execution.getLifecyclePhase()

Use Maven dependencies (your versions may vary):

<dependency>
  <groupId>org.apache.maven</groupId>
  <artifactId>maven-plugin-api</artifactId>
  <version>3.3.1</version>
</dependency>
<dependency>
  <groupId>org.apache.maven.plugin-tools</groupId>
  <artifactId>maven-plugin-annotations</artifactId>
  <version>3.4</version>
  <scope>provided</scope>
</dependency>
<dependency>
  <groupId>org.apache.maven</groupId>
  <artifactId>maven-core</artifactId>
  <version>3.3.1</version>
</dependency>
查看更多
放我归山
3楼-- · 2019-06-15 11:37

Thus, within the plugin, I would need to know if I'm executing process-classes (...) or if I'm executing process-test-classes

AFAIK, this is not really possible.

I could, of course, create two plugins for this, but this kind of solution deeply offends my sensibilities and is probably against the law in several states.

I don't see anything wrong with having two Mojos sharing code but bound to different phases. Something like the Maven Compiler Plugin (and its compiler:compile and compiler:testCompile goals).

查看更多
三岁会撩人
4楼-- · 2019-06-15 11:40

you can't get the phase, but you can get the execution ID which you have as separate. In the plugin:

/** 
 * @parameter expression="${mojoExecution}" 
 */
private org.apache.maven.plugin.MojoExecution execution;

...

public void execute() throws MojoExecutionException
{
    ...
    System.out.println( "executionId is: " + execution.getExecutionId() );
}

I'm not sure if this is portable to Maven 3 yet.

查看更多
登录 后发表回答