Gradle WriteProperties: doLast 内的属性未生效

huangapple go评论53阅读模式
英文:

Gradle WriteProperties: property inside doLast did not work

问题

Gradle WriteProperties: doLast 内部的 property 未生效。

task foo(type: WriteProperties) {
    doLast {
        def value = getValueFromFile()
        property 'foo', value
    }
}

在 doLast 内部的 property foo 被忽略。

英文:

Gradle WriteProperties: property inside doLast did not work.

 task foo(type: WriteProperties) {

    doLast {

        def value = getValueFromFile()
        property 'foo', value
    }
 }

The property foo inside the doLast was ignored.

答案1

得分: 0

查看构建脚本基础doLast { } 在任务操作列表的末尾执行。换句话说,首先执行主任务的操作,然后执行任何doLast操作。

您所做的是在任务执行之后配置属性foo。由于在执行之前未配置任何属性进行写入,foo任务本质上是无操作,因为未配置任何输入。

此外,您还未将文件声明为任务的输入。这将导致较差的增量构建支持。

完整示例:

tasks.register("foo", WriteProperties::class) {
    outputFile = layout.buildDirectory.file("foo.properties").get().asFile
    val examplePropertiesFile = layout.projectDirectory.file("example.properties")

    // 将文件声明为任务的输入,以允许Gradle跟踪
    inputs.file(examplePropertiesFile)

    // 延迟计算/读取值
    val examplePropsValue = provider {
        val props = Properties()
        examplePropertiesFile.asFile.inputStream().use {
            props.load(it)
        }
        props["foo"]
    }

    // 为任务配置属性
    property("foo", examplePropsValue)
}
英文:

Review build script basics. doLast { } is executed at the end of a task's action list. In other words, the main task's action is executed first and then any doLast actions.

What you have done is configured the property foo after the task has executed. Since no properties were configured to be written prior, the foo task is a essentially a noop because none of the inputs are configured.

Additionally, you have not declared the file as an input to the task. This will lead poor incremental builds support.

Complete example:

tasks.register("foo", WriteProperties::class) {
	outputFile = layout.buildDirectory.file("foo.properties").get().asFile
	val examplePropertiesFile = layout.projectDirectory.file("example.properties")

	// Declare the file as input to the task to allow Gradle to track
	inputs.file(examplePropertiesFile)

	// Lazily compute/read the value
	val examplePropsValue = provider {
		val props = Properties()
		examplePropertiesFile.asFile.inputStream().use {
			props.load(it)
		}
		props["foo"]
	}

	// Configure the property for the task
	property("foo", examplePropsValue)
}

huangapple
  • 本文由 发表于 2023年5月7日 11:16:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76192049.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定