gpt4 book ai didi

gradle - 如何在 Gradle Kotlin DSL 中有效地填充额外的属性?

转载 作者:行者123 更新时间:2023-12-01 03:10:52 24 4
gpt4 key购买 nike

我正在将 Gradle 构建脚本从 Groovy 迁移到 Kotlin DSL,其中没有真正记录的一件事是如何填充 extra properties .

在 Groovy 中,我可以这样写:

ext {
comp = 'node_exporter'
compVersion = '0.16.0'
compProject = 'prometheus'
arch = 'linux-amd64'
tarball = "v${compVersion}/${comp}-${compVersion}.${arch}.tar.gz"
downloadSrc = "https://github.com/${compProject}/${comp}/releases/download/${tarball}"
unzipDir = "${comp}-${compVersion}.${arch}"
}

我发现在 Kotlin DSL 中,我可以通过以下方式实现相同的功能:
val comp by extra { "filebeat" }
val compVersion by extra { "6.4.0" }
val arch by extra { "linux-x86_64" }
val tarball by extra { "${comp}-${compVersion}-${arch}.tar.gz" }
val downloadSrc by extra { "https://artifacts.elastic.co/downloads/beats/${comp}/${tarball}" }
val unzipDir by extra { "${comp}-${compVersion}-${arch}" }

这看起来很重复。

ExtraPropertiesExtension的实现在 Kotlin 中有点复杂,但最后,它只是简单的旧 Map<String, Object> .

所以,我的问题: 是否可以填充 extra具有多个属性的对象更容易,而不仅仅是重复 val myProp by extra { "myValue"} ?

最佳答案

根据当前( 5.2.1 )文档:

All enhanced objects in Gradle’s domain model can hold extra user-defined properties. This includes, but is not limited to, projects, tasks, and source sets.

Extra properties can be added, read and set via the owning object’s extra property. Alternatively, they can be addressed via Kotlin delegated properties using by extra.


这是在 Project 上使用额外属性的示例和 Task对象:
val kotlinVersion by extra { "1.3.21" }
val kotlinDslVersion by extra("1.1.3")
extra["isKotlinDsl"] = true

tasks.register("printExtProps") {
extra["kotlinPositive"] = true

doLast {
// Extra properties defined on the Project object
println("Kotlin version: $kotlinVersion")
println("Kotlin DSL version: $kotlinDslVersion")
println("Is Kotlin DSL: ${project.extra["isKotlinDsl"]}")
// Extra properties defined on the Task object
// this means the current Task
println("Kotlin positive: ${this.extra["kotlinPositive"]}")
}
}

关于gradle - 如何在 Gradle Kotlin DSL 中有效地填充额外的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52401740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com