以编程方式解析插件外部的 Maven 依赖项 - 获取 RepositorySystemSession 和 RepositorySystem
2022-09-03 14:08:06
也许这将是一个比我原先想象的更大的任务,但无论如何,我正在尝试从文件中加载一个,然后解决其依赖关系。我已经获得了两个位的代码,但是我缺少一些我需要的对象引用;具体来说,我需要获取 和 的实例。有什么提示吗?MavenProject
RepositorySystemSession
RepositorySystem
注意:我已经用maven插件标记了这个问题,但这不是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;
}
我意识到这可能是一个不寻常的请求,也许我应该放弃我试图做的事情,并将其包装为插件......但我只是想完成我现在开始的事情!提前致谢。