Gradle 以编程方式下载插件依赖

Gradle plugin download dependency programmatically

目前我正在编写一个 gradle 插件,我需要在给定任务中以编程方式添加和下载 Maven 依赖项。

我评估了 DependencyHandlerArtifactResolutionQuery 但我不知道在哪里以及如何添加依赖项并在 mavenCentral 存储库中解决它

maven 的类似编码看起来相当简单

  Artifact artifact = artifactFactory.createArtifactWithClassifier(groupId, artifactId, version, type, classifier);

  artifactResolver.resolve(artifact, remoteRepositories, localRepository); 

所以我 guess/hope 在 gradle 中有一个类似的简单方法,我只是没有看到它

问候 马蒂亚斯

更新 1:

所以这是我尝试过的一些东西,从不同的尝试中疯狂地 c&p。值得一提的是,我要下载的依赖有分类器ZIP,所以正常在我的build.gradle我写

compile 'group:artifact:version@zip

获取文件

        ComponentIdentifier componentIdentifier = new DefaultModuleComponentIdentifier("com.sap.cloud",
                "neo-java-web-sdk", "3.39.10");

        System.out.println("CompIdentifier = " + componentIdentifier.getDisplayName());
        //getProject().getDependencies().add("compile", componentIdentifier.getDisplayName());



        Configuration configuration = getProject().getConfigurations().getByName("compile");
        org.gradle.api.artifacts.Dependency dep2 = new DefaultExternalModuleDependency("com.sap.cloud",
                "neo-java-web-sdk", "3.39.10");

        boolean depList = configuration.getDependencies().add(dep2);
//        
        configuration.forEach(file -> {
            getProject().getLogger().lifecycle("Found project dependency @ " + file.getAbsolutePath());
        });
        Set<File> files =  configuration.resolve();
        for (File file2 : files) {
            System.out.println("Files: " + file2.getName());
        }

        DependencyHandler dep =  getProject().getDependencies();
        ComponentModuleMetadataHandler modules = dep.getModules();

        ArtifactResolutionQuery a = getProject().getDependencies().createArtifactResolutionQuery()
                .forComponents(componentIdentifier).withArtifacts(MavenModule.class, SourcesArtifact.class);
        ArtifactResolutionResult r = a.execute();
        Set<ComponentArtifactsResult> set = r.getResolvedComponents();
        Set<ComponentResult> c = r.getComponents();

我认为在 Gradle 插件中以编程方式下载依赖项的最简单方法与在构建脚本中执行相同。只需创建一个新配置,添加您的依赖项并解析配置。观看下面的示例,这是如何在 Java(Gradle 插件的首选语言)中工作的:

Configuration config = project.getConfigurations().create("download");
config.setTransitive(false); // if required
project.getDependencies().add(config.getName(), "com.sap.cloud:neo-java-web-sdk:3.39.10@zip");
File file = config.getSingleFile();

对于此示例,配置的名称 ("download") 可以是 任何尚未用作配置名称的字符串(如 compileruntime).由于配置将在之后解析,因此每次重复使用此代码段(或多次调用)时都必须使用其他名称。