用兼容的替换替换依赖模块

Substituting a dependency module with a compatible replacement

在Gradle Groovy DSL中你可以轻松substitute a dependency module with a compatible replacement as explained in the Gradle user manual。你如何在 Gradle Kotlin DSL 中做同样的事情?

TLDR

来自 Gradle docs 的示例 Gradle Kotlin DSL

configurations.forEach({c: Configuration ->
    println("Inside 'configurations.forEach'")

    val replaceGroovyAll: DependencyResolveDetails.() -> Unit = {
        println("Inside 'replaceGroovyAll'")
        if (requested.name == "groovy-all") {
            val targetUsed = "${requested.group}:groovy:${requested.version}"
            println("Replacing 'groovy-all' with $targetUsed")
            useTarget(targetUsed)
            because("prefer 'groovy' over 'groovy-all'")
        }
        if (requested.name == "log4j") {
            val targetUsed = "org.slf4j:log4j-over-slf4j:1.7.10"
            println("replacing 'log4j' with $targetUsed")
            useTarget(targetUsed)
            because("prefer 'log4j-over-slf4j' 1.7.10 over any version of 'log4j'")
        }
    }
    c.resolutionStrategy.eachDependency(replaceGroovyAll)
})

详情

Gradle 的 ResolutionStrategy.eachDependency 接受类型 Action<? super DependencyResolveDetails> 的参数。 Since version 0.8.0 Kotlin Gradle DSL transforms Action to a Function literal with receiver。因此,每当您需要在 Groovy Gradle 脚本中传递 Action<T> 时,您可以在 Kotlin 中将其定义为

val funcLit: T.() -> Unit = {
    // fields and methods of T are in scope here
}

然后你可以将此 funcLit 作为参数传递到任何需要 Action<T> 的地方。

我也开了一个issue at the project's github, which was answered by Github user eskatos。我编码并执行了他的答案,发现它也有效。这是他的代码。

configurations.all {
    resolutionStrategy.eachDependency {
        if (requested.name == "groovy-all") {
            useTarget("${requested.group}:groovy:${requested.version}")
            because("prefer 'groovy' over 'groovy-all'")
        }
        if (requested.name == "log4j") {
            useTarget("org.slf4j:log4j-over-slf4j:1.7.10")
            because("prefer 'log4j-over-slf4j' 1.7.10 over any version of 'log4j'")
        }
    }
}