Slackbot
02/24/2023, 7:34 PMVampire
02/24/2023, 10:09 PMAdam
02/25/2023, 11:39 AMsettings.gradle.kts
You could use providers.fileContents { file("custom.properties") }
to first get the file contents
val customPropertiesText: Provider<String> =
providers.fileContents { file("custom.properties") }.asText
And then parse them using java.util.Properties
val customProperties: Provider<java.util.Properties> =
customPropertiesText.map { fileContents ->
val props = java.util.Properties()
props.load(StringReader(fileContents))
props
}
Instead of hard-coding the location to custom.properties
, you could set the location using a project property. So in gradle.properties
add customPropertiesLocation=/path/to/properties
. The benefit is that this property could be overridden per user or via an environment variable (the priority is described here
val customPropertiesFilePath = providers.gradleProperty("customPropertiesFile")
.orElse("$rootDir/custom.properties")
// map the file path to the text content
val customPropertiesText: Provider<String> = customPropertiesFilePath.flatMap { path ->
providers.fileContents { file(path) }.asText
}
Now that the location of custom.properties
isn’t linked to the root project, but can be defined and overridden, it doesn’t necessarily have to be managed in settings.gradle.kts
to apply it to all projects. You could create a convention plugin.
// buildSrc/src/main/kotlin/custom-properties.gradle.kts
// load and parse customPropertiesFile as above...
// convert it to a Map<String, String>
val customProperties: Provider<Map<String, String>> =
customPropertiesText.map { fileContents ->
val props = java.util.Properties()
props.load(StringReader(fileContents))
@Suppress("UNCHECKED_CAST")
props as Map<String, String>
}
// now make the properties available to any subproject that applies the convention
val props = project.objects.mapProperty<String, String>()
props.set(customProperties)
project.extra.set("customProperties", props)
then subprojects can apply the convention-plugin, and access the properties
// some/subproject/build.gradle.kts
plugins {
`custom-properties` // load the convention plugin
}
val customProperties: MapProperty<String, String> by extra
println(customProperties.get())
Luc-Antoine Girardin
03/03/2023, 2:22 PM