プラグイン内でMavenの依存関係階層にアクセスする方法
-
18-09-2019 - |
質問
私のプラグインでは、依存関係の階層を処理し、各依存関係に関する情報(GroupID、ArtifactID、バージョンなど)を取得する必要があります。これを行うための最良の方法は何ですか?
解決
依存関係プラグインには 木の目標 それはこの作業のほとんどを行います。処理します MavenProject
を使用して DependencyTreeBuilder
, 、これはaを返します DependencyNode
解決された依存関係(およびそれらの推移的依存関係)に関する階層情報を使用します。
Treemojoからコードの多くを直接コピーできます。それはを使用します CollectingDependencyNodeVisitor
ツリーを横断して生成するには List
すべてのノードの。
アクセスできます 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() (後の1つは、推移的依存関係も返します)。
/**
* 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();
...
}
}
私は完全には確かではありませんが、両方の方法がのコレクションを返すと思います アーティファクト GroupID、artifactid、バージョンなどのゲッターを公開する実装。
以下は、すべての依存関係(Transitiveを含む)を取得する方法に関する最新の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.
}
}
}
モジョのパラメーターを変更することは、私が欠けていた非常に重要な作品です。それがなければ、次のような行:
@Parameter(defaultValue = "${project.compileClasspathElements}", readonly = true, required = true)
private List<String> compilePath;
クラスディレクトリのみを返し、期待するパスではありません。
必要性の依存のコレクションを変更し、異なる値に依存する必要解像度を必要とすることで、つかむものの範囲を変更できます。 Mavenドキュメント 詳細を提供できます。
使用してみてください Aether
ユーティリティクラスから jcabi-aether アーティファクトのすべての依存関係のリストを取得するには:
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();
}