Yes, this is possible.
We can build a project in-memory with the ProjectBuilder
API:
Builds in-memory descriptions of projects.
By invoking the build(projectArtifact, request)
method with the artifact we're interested in and a ProjectBuildingRequest
(that holds various parameters like location of the remote / local repositories, etc.), this will build a MavenProject
in-memory.
Consider the following MOJO that will print the name of all the dependencies:
@Mojo(name = "foo", requiresDependencyResolution = ResolutionScope.RUNTIME)
public class MyMojo extends AbstractMojo {
@Parameter(defaultValue = "${project}", readonly = true, required = true)
private MavenProject project;
@Parameter(defaultValue = "${session}", readonly = true, required = true)
private MavenSession session;
@Component
private ProjectBuilder projectBuilder;
public void execute() throws MojoExecutionException, MojoFailureException {
ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
try {
for (Artifact artifact : project.getArtifacts()) {
buildingRequest.setProject(null);
MavenProject mavenProject = projectBuilder.build(artifact, buildingRequest).getProject();
System.out.println(mavenProject.getName());
}
} catch (ProjectBuildingException e) {
throw new MojoExecutionException("Error while building project", e);
}
}
}
There are a couple of main ingredients here:
- The
requiresDependencyResolution
tells Maven that we require the dependencies to be resolved before execution. In this case, I specified it to RUNTIME
so that all compile and runtime dependencies are resolved. You can of course set that to the ResolutionScope
. you want.
- The project builder is injected with the
@Component
annotation.
- A default building request is build with the parameter of the current Maven session. We just need to override the current project by explicitly setting it to
null
, otherwise nothing will happen.
When you have access to the MavenProject
, you can then print all the information you want about it, like developers, etc.
If you want to print the dependencies (direct and transitive), you will also need to invoke setResolveDependencies(true)
on the building request, otherwise, they won't be populated in the built project.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…