I am currently trying to implement logic where maven is used to compile java source code. For that I don't want to use the maven cli but rather some sort of api, like the gradle tooling api for gradle. Since documentation regarding these use cases is hard to find I am at a loss here. I found the maven-core library, and using that tried to execute a project build like this:
ClassWorld world = new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader();
ClassRealm coreRealm = world.getClassRealm("plexus.core");
ContainerConfiguration configuration = new DefaultContainerConfiguration()
.setClassWorld(world)
.setRealm(coreRealm)
.setClassPathScanning(PlexusConstants.SCANNING_INDEX)
.setAutoWiring(true)
.setJSR250Lifecycle(true)
.setName("maven");
CoreExports exports = new CoreExports(coreRealm, new HashSet<>(), new HashSet<>());
DefaultPlexusContainer container = new DefaultPlexusContainer(configuration, new AbstractModule()
{
@Override
protected void configure()
{
bind(CoreExports.class).toInstance(exports);
}
});
container.setLookupRealm(null);
Maven maven = container.lookup(Maven.class);
MavenExecutionRequestPopulator populator = container.lookup(MavenExecutionRequestPopulator.class);
MavenExecutionRequest request = new DefaultMavenExecutionRequest();
request.setInteractiveMode(false);
request.setPom(new File("some/path/to/pom.xml"));
request.setBaseDirectory(new File("some/path/to"));
request.setGoals(Arrays.asList("clean", "install"));
request = populator.populateDefaults(request);
MavenExecutionResult result = maven.execute(request);
// handle result
Executing this code with a valid maven pom in the base directory results in the error message Execution default-clean of goal org.apache.maven.plugins:maven-clean-plugin:2.5:clean failed: Unable to load the mojo 'clean' (or one of its required components) from the plugin 'org.apache.maven.plugins:maven-clean-plugin:2.5'
. Simply adding this as a dependency for my project does not work so I expect I have to register this somehow somewhere unknown to me (and then do the same for the build plugin).
This code is also heavily "inspired" by the maven CLI implementation since there's no findable documentation for me anywhere on how to invoke maven builds without implementing my code as a maven plugin, which I simply cannot and will not do.
So far I'm really surprised that the maven "api" is this poorly documented and is the exact opposite of lightweight with plexus seemingly being required. So if there's any way to build maven projects with a (preferrably light weight) api then I'd be very happy to find out that I'm incapable of finding the answer myself. If there is simply no way just let me know and I'm dropping maven from my requirements. Thank you in advance
CodePudding user response:
You can examine code of Embedded3xLauncher in maven-verifier project.
Or simply use maven-verifier.
You can also ask on Maven dev list.