英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论