以编程方式解析插件外部的 Maven 依赖项 - 获取 RepositorySystemSession 和 RepositorySystem

2022-09-03 14:08:06

也许这将是一个比我原先想象的更大的任务,但无论如何,我正在尝试从文件中加载一个,然后解决其依赖关系。我已经获得了两个位的代码,但是我缺少一些我需要的对象引用;具体来说,我需要获取 和 的实例。有什么提示吗?MavenProjectRepositorySystemSessionRepositorySystem

注意:我已经用标记了这个问题,但这不是Maven插件。我很高兴强制要求Maven 3(认为我已经有了..)

以下是我到目前为止的代码:

构建 MavenProject

public static MavenProject loadProject(File pomFile) throws Exception
{
    MavenProject ret = null;
    MavenXpp3Reader mavenReader = new MavenXpp3Reader();

    if (pomFile != null && pomFile.exists())
    {
        FileReader reader = null;

        try
            {
            reader = new FileReader(pomFile);
            Model model = mavenReader.read(reader);
            model.setPomFile(pomFile);

            ret = new MavenProject(model);
        }
        finally
        {
            // Close reader
        }
    }

    return ret;
}

解析依赖关系:

public static List<Dependency> getArtifactsDependencies(MavenProject project, String dependencyType, String scope) throws Exception
{    
    DefaultArtifact pomArtifact = new DefaultArtifact(project.getId());

    RepositorySystemSession repoSession = null; // TODO
    RepositorySystem repoSystem = null; // TODO

    List<RemoteRepository> remoteRepos = project.getRemoteProjectRepositories();
    List<Dependency> ret = new ArrayList<Dependency>();

    Dependency dependency = new Dependency(pomArtifact, scope);

    CollectRequest collectRequest = new CollectRequest();
    collectRequest.setRoot(dependency);
    collectRequest.setRepositories(remoteRepos);

    DependencyNode node = repoSystem.collectDependencies(repoSession, collectRequest).getRoot();
    DependencyRequest projectDependencyRequest = new DependencyRequest(node, null);

    repoSystem.resolveDependencies(repoSession, projectDependencyRequest);

    PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
    node.accept(nlg);

    ret.addAll(nlg.getDependencies(true));

    return ret;
}

我意识到这可能是一个不寻常的请求,也许我应该放弃我试图做的事情,并将其包装为插件......但我只是想完成我现在开始的事情!提前致谢。


答案 1

试试jcabi-aether,它是来自Sonatype的Apache Aether的包装器:

final File repo = this.session.getLocalRepository().getBasedir();
final Collection<Artifact> deps = new Aether(this.getProject(), repo).resolve(
  new DefaultArtifact("junit", "junit-dep", "", "jar", "4.10"),
  JavaScopes.RUNTIME
);

如果您在 Maven 插件之外:

final File repo = new File(System.getProperty("java.io.tmpdir"), "my-repo");
final MavenProject project = new MavenProject();
project.setRemoteArtifactRepositories(
  Arrays.asList(
    new RemoteRepository(
      "maven-central",
      "default",
      "http://repo1.maven.org/maven2/"
    )
  )
);
final Collection<Artifact> deps = new Aether(project, repo).resolve(
  new DefaultArtifact("junit", "junit-dep", "", "jar", "4.10"),
  JavaScopes.RUNTIME
);

答案 2

我建议阅读有关以太lib的信息,这恰恰是出于这种目的。

注意:Aether之前是在Sonatype开发的,但后来转移到Eclipse


推荐