Finding the size of Gradle dependencies with Gradle's Kotlin DSL

Originally posted on 2021-02-26

I've seen a bunch of posts about how to find the size of dependencies when using Gradle's Groovy DSL but until today I hadn't found one on how to do the same thing with the Kotlin DSL.

There's a nice gist that tracks the evolution of the Gradle depsize task that medvedev created. On Nov 10th, 2020 phi1ipp posted the Kotlin DSL translation which I've posted below (I'm never sure what happens to gists over time).

tasks.register("depsize") {
    description = "Prints dependencies for \"default\" configuration"
    doLast {
        listConfigurationDependencies(configurations["default"])
    }
}

tasks.register("depsize-all-configurations") {
    description = "Prints dependencies for all available configurations"
    doLast {
        configurations
            .filter { it.isCanBeResolved }
            .forEach { listConfigurationDependencies(it) }
    }
}

fun listConfigurationDependencies(configuration: Configuration) {
    val formatStr = "%,10.2f"

    val size = configuration.map { it.length() / (1024.0 * 1024.0) }.sum()

    val out = StringBuffer()
    out.append("\nConfiguration name: \"${configuration.name}\"\n")
    if (size > 0) {
        out.append("Total dependencies size:".padEnd(65))
        out.append("${String.format(formatStr, size)} Mb\n\n")

        configuration.sortedBy { -it.length() }
            .forEach {
                out.append(it.name.padEnd(65))
                out.append("${String.format(formatStr, (it.length() / 1024.0))} kb\n")
            }
    } else {
        out.append("No dependencies found")
    }
    println(out)
}