Hellblazer
Hellblazer

Reputation: 819

Determining Maven execution phase within a plugin

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...

Upvotes: 16

Views: 3167

Answers (3)

iirekm
iirekm

Reputation: 9406

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>

Upvotes: 2

Brett Porter
Brett Porter

Reputation: 5867

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.

Upvotes: 2

Pascal Thivent
Pascal Thivent

Reputation: 570285

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).

Upvotes: 9

Related Questions