I\'m writing a Maven 3 plugin that needs to know the transitive dependencies of a given org.apache.maven.model.Dependency
. How can I do that?
In Maven 3, you access all dependencies in a tree-based form by relying on the maven-dependency-tree shared component:
A tree-based API for resolution of Maven project dependencies.
This component introduces the DependencyGraphBuilder
that can build the dependency tree for a given Maven project. You can also filter artifacts with a ArtifactFilter
, that has a couple of built-in implementations to filter by groupId, artifactId (IncludesArtifactFilter
and ExcludesArtifactFilter
), scope (ScopeArtifactFilter
), etc. If the fiter is null
, all dependencies are kept.
In your case, since you target a specific artifact, you could add a IncludesArtifactFilter
with the pattern groupId:artifactId
of your artifact. A sample code would be:
@Mojo(name = "foo")
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(hint = "default")
private DependencyGraphBuilder dependencyGraphBuilder;
public void execute() throws MojoExecutionException, MojoFailureException {
ArtifactFilter artifactFilter = new IncludesArtifactFilter(Arrays.asList("groupId:artifactId"));
ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
buildingRequest.setProject(project);
try {
DependencyNode rootNode = dependencyGraphBuilder.buildDependencyGraph(buildingRequest, artifactFilter);
CollectingDependencyNodeVisitor visitor = new CollectingDependencyNodeVisitor();
rootNode.accept(visitor);
for (DependencyNode node : visitor.getNodes()) {
System.out.println(node.toNodeString());
}
} catch (DependencyGraphBuilderException e) {
throw new MojoExecutionException("Couldn't build dependency graph", e);
}
}
}
This gives access to the root node of the dependency tree, which is the current project. From that node, you can access all chidren by calling the getChildren()
method. So if you want to list all dependencies, you can traverse that graph recursively. This component does provide a facility for doing that with the CollectingDependencyNodeVisitor
. It will collect all dependencies into a List
to easily loop through it.
For the Maven plugin, the following dependency is therefore necessary:
org.apache.maven.shared
maven-dependency-tree
3.0