自定义配置和仅解析编译依赖

Custom configuration and resolving only compile dependencies

我目前正在编写一个小插件,但是当我想获取所有使用的依赖项的列表时,我遇到了困难。

我在做什么 在插件中我创建了一个新配置

def config = project.configurations.create(sourceSet.getTaskName('foo', 'bar'))

在使用插件的 build.gradle 中,我向此配置添加了一些依赖项

dependencies {
  fooTestBar(project(':module'))
}

module/build.gradle我有

plugins {
  id 'java-library'
}
dependencies {
  implementation('org.apache.commons:commons-collections4:4.4')
  api('org.springframework:spring-context:5.2.11.RELEASE')
}

当我现在在插件中执行以下操作时

List<ResolvedArtifact> = config.resolvedConfiguration.firstLevelModuleDependencies.allModuleArtifacts.flatten()

我从 :module 中的两个声明中得到了工件,但我感兴趣的只是 api 依赖项,意味着在编译项目时也使用的那个

看起来整个配置都被视为 runtime 配置,所以我拥有所有工件,包括来自两个声明的传递性工件,而不是只有 api 工件,包括来自api

直到现在我都找不到任何方法来查看已解决的依赖项/工件是否属于 api 类型,我不想在结果列表中包含它

我必须为用法添加属性

config.attributes {
    attribute( Usage.USAGE_ATTRIBUTE, objects.named( Usage, Usage.JAVA_API ) )
}

https://docs.gradle.org/current/userguide/variant_model.html https://docs.gradle.org/current/userguide/variant_attributes.html

感谢 Chris Doré https://discuss.gradle.org/t/custom-configuration-and-resolving-only-compile-dependencies/38891