I try to generate a build-info.properties
file using dynamic data not available in the configuration phase.
The file does not exist initially.
This is my best try so far (using Kotlin everywhere):
abstract class WriteBuildInfoFile : WriteProperties() {
companion object {
private val buildInfoFilePath = "resources/main/build-info.properties"
}
@InputFile
@Optional
val inputBuildInfoFile = project.objects.fileProperty()
init {
val buildInfoFile = project.layout.buildDirectory.file(buildInfoFilePath)
if (buildInfoFile.get().asFile.exists()) {
inputBuildInfoFile.set(buildInfoFile)
}
setOutputFile(buildInfoFile)
}
@TaskAction
override fun writeProperties() {
val existingProperties = Properties()
inputBuildInfoFile.orNull?.asFile?.also {
if (it.exists()) {
it.inputStream().use { existingProperties.load(it) }
}
}
fun <K, V> Map<K, V>.mergeEntries() {
forEach {
val key = it.key.toString()
if (!properties.containsKey(key)) {
property(key, it.value.toString())
}
}
}
existingProperties.mergeEntries() // Merge properties from the optionally existing file
extra.properties.mergeEntries() // Merge properties added by tasks
super.writeProperties()
}
}
And the usage:
val generateBuildInfo: TaskProvider<WriteBuildInfoFile> by tasks.registering(WriteBuildInfoFile::class) {
dependsOn(someTask)
// The following line works if uncommented
// extraProperties["propertyOnlyForTesting"] = "testValue"
}
val someTask by tasks.registering {
doLast {
...
// The following line causes the exception
generateBuildInfo.extraProperties["someProperty"] = someDynamicValue
}
}
tasks.named<BootJar>("bootJar") {
dependsOn(generateBuildInfo)
...
}
The exception I get:
class org.gradle.api.internal.tasks.DefaultTaskContainer$TaskCreatingProvider_Decorated cannot be cast to class org.gradle.api.plugins.ExtensionAware (org.gradle.api.internal.tasks.DefaultTaskContainer$TaskCreatingProvider_Decorated and org.gradle.api.plugins.ExtensionAware are in unnamed module of loader org.gradle.internal.classloader.VisitableURLClassLoader @5e265ba4)
Do you have any idea how can I pass dynamic properties to a task if not by using its extra properties?
Thanks.