在我的插件中,我需要处理依赖层次结构并获取有关每个依赖项以及是否被排除的信息(groupId、artifactId、版本等)。做这个的最好方式是什么?
7 回答
依赖插件具有完成大部分工作的树目标。它MavenProject
使用处理 a DependencyTreeBuilder
,这将返回 aDependencyNode
以及有关已解析依赖项(及其传递依赖项)的分层信息。
您可以直接从 TreeMojo 复制大部分代码。它使用CollectingDependencyNodeVisitor
遍历树并生成List
所有节点的 a。
您可以Artifact
通过调用 访问节点的getArtifact()
,然后根据需要获取工件信息。要获取排除原因,DependencyNode
有一个getState()
方法返回一个 int 指示是否已包含依赖项,或者如果不是,则省略它的原因是什么(DependencyNode 类中有常量可以检查返回值)
//All components need this annotation, omitted for brevity
/**
* @component
* @required
* @readonly
*/
private ArtifactFactory artifactFactory;
private ArtifactMetadataSource artifactMetadataSource;
private ArtifactCollector artifactCollector;
private DependencyTreeBuilder treeBuilder;
private ArtifactRepository localRepository;
private MavenProject project;
public void execute() throws MojoExecutionException, MojoFailureException {
try {
ArtifactFilter artifactFilter = new ScopeArtifactFilter(null);
DependencyNode rootNode = treeBuilder.buildDependencyTree(project,
localRepository, artifactFactory, artifactMetadataSource,
artifactFilter, artifactCollector);
CollectingDependencyNodeVisitor visitor =
new CollectingDependencyNodeVisitor();
rootNode.accept(visitor);
List<DependencyNode> nodes = visitor.getNodes();
for (DependencyNode dependencyNode : nodes) {
int state = dependencyNode.getState();
Artifact artifact = dependencyNode.getArtifact();
if(state == DependencyNode.INCLUDED) {
//...
}
}
} catch (DependencyTreeBuilderException e) {
// TODO handle exception
e.printStackTrace();
}
}
您可以使用MavenProject#getDependencyArtifacts()或MavenProject#getDependencies()(后者也返回传递依赖项)。
/**
* Test Mojo
*
* @goal test
* @requiresDependencyResolution compile
*/
public class TestMojo extends AbstractMojo {
/**
* The Maven Project.
*
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject project = null;
/**
* Execute Mojo.
*
* @throws MojoExecutionException If an error occurs.
* @throws MojoFailureException If an error occurs.
*/
public void execute() throws MojoExecutionException,
MojoFailureException {
...
Set dependencies = project.getDependencies();
...
}
}
我不完全确定,但我认为这两种方法都会返回一个Artifact实现的集合,这些实现公开了 groupId、artifactId、version 等的 getter。
这是一个最新的 Maven3 示例,介绍如何获取所有依赖项(包括传递性)以及访问文件本身(例如,如果您需要将路径添加到类路径)。
// Default phase is not necessarily important.
// Both requiresDependencyCollection and requiresDependencyResolution are extremely important however!
@Mojo(name = "simple", defaultPhase = LifecyclePhase.PROCESS_RESOURCES, requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME)
public class SimpleMojo extends AbstractMojo {
@Parameter(defaultValue = "${project}", readonly = true)
private MavenProject mavenProject;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
for (final Artifact artifact : mavenProject.getArtifacts()) {
// Do whatever you need here.
// If having the actual file (artifact.getFile()) is not important, you do not need requiresDependencyResolution.
}
}
}
更改 Mojo 中的参数是我缺少的一个非常重要的部分。没有它,如下所示的行:
@Parameter(defaultValue = "${project.compileClasspathElements}", readonly = true, required = true)
private List<String> compilePath;
只会返回类目录,而不是您期望的路径。
将 requiresDependencyCollection 和 requiresDependencyResolution 更改为不同的值将允许您更改要获取的范围。maven 文档可以提供更多细节。
尝试使用jcabi-aetherAether
中的实用程序类来获取任何工件的所有依赖项的列表:
File repo = this.session.getLocalRepository().getBasedir();
Collection<Artifact> deps = new Aether(this.getProject(), repo).resolve(
new DefaultArtifact("junit", "junit-dep", "", "jar", "4.10"),
JavaScopes.RUNTIME
);
为什么不直接取回所有依赖项(包括直接依赖项和传递依赖项)并检查排除项?
@Parameter(property = "project", required = true, readonly = true)
private MavenProject project;
public void execute() throws MojoExecutionException
{
for (Artifact a : project.getArtifacts()) {
if( a.getScope().equals(Artifact.SCOPE_TEST) ) { ... }
if( a.getScope().equals(Artifact.SCOPE_PROVIDED) ) { ... }
if( a.getScope().equals(Artifact.SCOPE_RUNTIME) ) { ... }
}
}
Maven 3 使用以太,这里有示例: https ://docs.sonatype.org/display/AETHER/Home
对于 Maven 3,您可以使用 DependencyGraphBuilder。它的作用与 DependencyTreeBuilder 几乎相同。
这是示例
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.artifact.resolver.filter.IncludesArtifactFilter;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder;
import org.apache.maven.shared.dependency.graph.DependencyNode;
import org.apache.maven.shared.dependency.graph.traversal.CollectingDependencyNodeVisitor;
public class AnanlyzeTransitiveDependencyMojo extends AbstractMojo{
@Parameter(defaultValue = "${project}", readonly = true, required = true)
private MavenProject project;
@Parameter(defaultValue = "${session}", readonly = true, required = true)
private MavenSession session;
@Component(hint="maven3")
private DependencyGraphBuilder dependencyGraphBuilder;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
// If you want to filter out certain dependencies.
ArtifactFilter artifactFilter = new IncludesArtifactFilter("groupId:artifactId:version");
ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
buildingRequest.setProject(project);
try{
DependencyNode depenGraphRootNode = dependencyGraphBuilder.buildDependencyGraph(buildingRequest, artifactFilter);
CollectingDependencyNodeVisitor visitor = new CollectingDependencyNodeVisitor();
depenGraphRootNode.accept(visitor);
List<DependencyNode> children = visitor.getNodes();
getLog().info("CHILDREN ARE :");
for(DependencyNode node : children) {
Artifact atf = node.getArtifact();
}
}catch(Exception e) {
e.printStackTrace();
}