Search code examples
gradledependency-managementgradle-task

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


I'm trying to do something which I feel should be relatively straightforward but nothing on the internet seems to be giving me what I'm after.

Basically, I want to take the compile/testCompile dependencies from my build.gradle (I don't want any of the sub-dependencies - just literally as they are in the file), and for each one I want to do something with the group name, name and version. Let's just say I want to print them.

So here is my 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
}

Thanks all.


Solution

  • To iterate over all you dependencies, you can itareate over all the configurations and the over all configuration dependencies. Like so:

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

    If you need exactly configuration dependencies, you can get them separately:

    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}"
            }
        }
    }
    

    Or modify the first example, by adding condition to check conf.name