代码之家  ›  专栏  ›  技术社区  ›  Rahul Khimasia

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

  •  1
  • Rahul Khimasia  · 技术社区  · 8 年前

    在Gradle groovy DSL中,您可以轻松地 substitute a dependency module with a compatible replacement 如中所述 Gradle user manual 。在Gradle Kotlin DSL中,您是如何做到这一点的?

    2 回复  |  直到 8 年前
        1
  •  2
  •   sa1nt    8 年前

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

    细节

    格雷德尔的 ResolutionStrategy.eachDependency 接受类型为的参数 Action<? super DependencyResolveDetails> . Since version 0.8.0 Kotlin Gradle DSL转换 Action 到A Function literal with receiver . 所以每当你需要通过 Action<T> 在groovy Gradle脚本中,可以在kotlin中将其定义为

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

    然后你可以通过这个 funcLit 作为一个论点 行动<t> 应为。

        2
  •  0
  •   Rahul Khimasia    8 年前

    我还打开了一个 issue 在项目的Github上,由Github用户回答 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'")
            }
        }
    }