使用 gradle-git-properties 插件在 Kotlin DSL 中进行 GString 惰性求值

GString lazy evaluation in Kotlin DSL using gradle-git-properties plugin

我将 Gradle 6.2.2 与此插件一起使用:com.gorylenko.gradle-git-properties(版本 2.2.2)。我正在尝试 "translate" 将以下代码片段放入 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 lazy evaluation" 部分在 Kotlin DSL 中工作,也不知道 gitProps 地图如何适合这里;最终这种方法(我知道它是部分错误的)正在返回 null。有什么想法吗?

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

我刚拿到这个插件并看了一下:它提供了一个项目扩展,您正在配置它以指定为什么要填充额外 属性,以及一个任务:"generateGitProperties".此任务是作为 "classes" 任务的依赖项添加的,因此一旦您到达 "shadowJar"

,它就已经是 运行

问题是找出 git 属性并填充额外属性仅在该任务 执行 时发生,因此它们在构建时不可用已配置,因此惰性 GString 恶作剧需要将惰性值向下传递到 shadowJar 配置中,只有在 shadowJar 执行后才会对其进行评估。

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

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

这是可行的,因为它在 "doFirst" 块中,所以它发生在任务执行时,而不是配置时。所以基本上,你可以模仿 "lazy 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 任务的一个子类型。

以下 Kotlin 语法对我有用:

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