使用gradle git属性插件在Kotlin DSL中进行GString懒惰评估



我使用Gradle6.2.2和这个插件:com.gorylenko.gradle-git-properties(版本2.2.2(。我正在尝试将以下片段"翻译"为Kotlin DSL:

gitProperties {
extProperty = "gitProps" // git properties will be put in a map at project.ext.gitProps
}
shadowJar {
manifest {
attributes(
"Build-Revision": "${ -> project.ext.gitProps["git.commit.id"]}"  // Uses GString lazy evaluation to delay until git properties are populated
)
}
}

但到目前为止,我已经想出了这个:

gitProperties {
extProperty = "gitProps"
keys = listOf("git.branch", "git.build.host", "git.build.version", "git.commit.id", "git.commit.id.abbrev",
"git.commit.time", "git.remote.origin.url", "git.tags", "git.total.commit.count")
}
tasks {
withType<ShadowJar> {
manifest.attributes.apply {
put("Build-Revision", "${project.ext.properties["git.commit.id"]}")
}
}
}

我不知道如何让"GString懒惰评估"部分在Kotlin DSL中工作,也不知道gitProps映射如何适合这里;最终,这种方法(我知道这是部分错误的(返回null。有什么想法吗?

以下Kotlin语法对我有效:

put("Build-Revision", object {
override fun toString():String = (project.extra["gitProps"] as Map<String, String>)["git.commit.id"]!!
})

我认为您对数据存储的位置和方式有一些困惑,尤其是数据何时可用。

我刚刚掌握了这个插件并看了一眼:它提供了一个项目扩展,您正在配置它来指定为什么要填充extra属性,以及一个任务:"generateGitProperties"。这个任务是作为"类"任务的依赖项添加的,所以一旦你到达"shadowJar",它就已经运行了

问题是,只有在执行该任务时,才能计算git属性并填充额外的属性,因此当配置构建后,这些属性就不可用了,因此懒惰的GString恶作剧需要将懒惰值传递到shadowJar配置中,只有在shadowJars执行后才会对其进行评估。

你可以获得这样的额外属性:

tasks.register("example") {
dependsOn("generateGitProperties")
doFirst {
val gitProps: Map<String, String> by project.ext
for ((name, value) in gitProps) {
println("GIT: $name -> $value")
}
}
}

这之所以有效,是因为它在"doFirst"块中,所以它发生在任务执行时,而不是配置时。因此,从本质上讲,你可以模仿"懒惰的GString"的东西。类似这样的东西:

withType<Jar>().configureEach {
val lazyCommitId = object {
override fun toString(): String {
val gitProps: Map<String, String> by project.ext
return gitProps["git.commit.id"] ?: ""
}
}
manifest {
attributes["Git-Commit-Id"] = lazyCommitId
}
}

我这样做只是为了"jar",但无论如何,"shadowJar"只是jar任务的一个子类型。

最新更新