Cristhian Escobar
02/21/2024, 12:13 PMlocal.properties
, but I'm not very satisfied with it. I also saw this project https://github.com/yshrsmz/BuildKonfig, but I'm not thrilled with it either. I'm wondering if there's something better out there.
sourcesSets {
val commonMain by getting {
val packageName = "io.company.shared.generated"
val localProperties = project.getLocalProperties()
val configDirectory = File(project.buildDir, "main/kotlin/generated")
// Generate build config for both platforms
generateBuildConfig(localProperties, packageName, configDirectory)
kotlin.srcDir(configDirectory)
...
}
}
fun Project.getLocalProperties(): Properties {
val properties = Properties()
val localPropertiesFile = rootProject.file("local.properties")
if (localPropertiesFile.exists()) {
properties.load(localPropertiesFile.inputStream())
}
return properties
}
// TODO: turn this into a plugin or find a better and scalable alternative
fun generateBuildConfig(properties: Properties, packageName: String, outputDir: File) {
val content = buildString {
appendLine("package $packageName")
appendLine()
appendLine("object SharedBuildConfig {")
properties.forEach { key, value ->
// Skip the SDK.DIR property
if (key.toString() != "sdk.dir") {
// Remove extra quotes from the property value if present
val cleanValue = value.toString().trim().removeSurrounding("\"")
// Properly escape the string and surround with quotes for the Kotlin file
appendLine(" const val ${key.toString().replace(".", "_")
.uppercase(Locale.getDefault())} = \"${cleanValue.replace("\\", "\\\\")}\"")
}
}
appendLine("}")
}
outputDir.apply {
mkdirs()
resolve("SharedBuildConfig.kt").writeText(content)
}
}
Casey Brooks
02/21/2024, 3:22 PMCristhian Escobar
02/21/2024, 5:26 PM