Skip to content

Instantly share code, notes, and snippets.

@romain-grecourt
Created February 27, 2020 20:34
Show Gist options
  • Save romain-grecourt/90cf3ea75a114c4c2dbb2b13a261b91f to your computer and use it in GitHub Desktop.
Save romain-grecourt/90cf3ea75a114c4c2dbb2b13a261b91f to your computer and use it in GitHub Desktop.
embedded maven from a plugin with no fork
package io.helidon.build.maven;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
/**
* Dev.
* see http://maven.apache.org/shared/maven-verifier/xref/org/apache/maven/it/Embedded3xLauncher.html
*/
@Mojo(name = "dev")
public class DevMojo extends AbstractMojo {
/**
* The Maven Project Object.
*/
@Parameter(defaultValue = "${project}", readonly = true, required = true)
private MavenProject project;
@Override
public void execute() throws MojoFailureException {
Method doMain;
Object mavenCli;
try {
ClassLoader coreLoader = Thread.currentThread().getContextClassLoader();
Class<?> cliClass = coreLoader.loadClass("org.apache.maven.cli.MavenCli");
mavenCli = cliClass.getDeclaredConstructor().newInstance();
Class<?>[] parameterTypes = {String[].class, String.class, PrintStream.class, PrintStream.class};
doMain = cliClass.getMethod("doMain", parameterTypes);
} catch (ClassNotFoundException
| InstantiationException
| IllegalAccessException
| NoSuchMethodException
| SecurityException
| IllegalArgumentException
| InvocationTargetException ex) {
throw new MojoFailureException(ex.getMessage(), ex);
}
String[] cliArgs = new String[]{"clean", "install"};
String workingDirectory = project.getBasedir().getAbsolutePath();
try {
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(mavenCli.getClass().getClassLoader());
try {
Object result = doMain.invoke(mavenCli, new Object[]{cliArgs, workingDirectory, System.out, System.err});
int exitValue = ((Number) result).intValue();
if (exitValue != 0) {
getLog().error("Error, embedded maven build failed");
}
} finally {
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
} catch (IllegalAccessException | InvocationTargetException e) {
throw new MojoFailureException("Failed to run Maven: " + e.getMessage(), e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment