尝试在自定义 gradle 任务中获取我的 build.gradle 依赖项的组名和版本

Trying to get the group name and version of my build.gradle dependencies in a custom gradle task

我正在尝试做一些我认为应该相对简单的事情,但互联网上的任何内容似乎都无法满足我的需求。

基本上,我想从我的 build.gradle 中获取 compile/testCompile 依赖项(我不想要任何子依赖项 - 就像它们在文件中一样),并且对于每一个我都想用组名、名称和版本做一些事情。假设我想打印它们。

这是我的 build.gradle:

dependencies {
    compile 'org.spring.framework.cloud:spring-cloud-example:1.0.6'
    compile 'org.spring.framework.cloud:spring-cloud-other-example:1.1.6'
    testCompile 'org.spring.framework.cloud:spring-cloud-example-test:3.1.2'
}

task printDependencies {
    //some code in here to get results such as...
    // org.spring.framework.cloud  spring-cloud-other-example  1.1.6
}

谢谢大家。

要迭代所有依赖项,您可以遍历所有配置和所有配置依赖项。像这样:

task printDependencies {
    project.configurations.each { conf ->
        conf.dependencies.each { dep ->
            println "${dep.group}:${dep.name}:${dep.version}"
        }
    }
}

如果你需要确切的配置依赖,你可以单独获取它们:

task printDependencies {
    project.configurations.getByName('compile') { conf ->
        conf.dependencies.each { dep ->
            println "${dep.group}:${dep.name}:${dep.version}"
        }
    }

    project.configurations.getByName('testCompile') { conf ->
        conf.dependencies.each { dep ->
            println "${dep.group}:${dep.name}:${dep.version}"
        }
    }
}

或者修改第一个例子,加入条件检查conf.name