Does anyone know of a better alternative for wirin...
# gradle
c
Does anyone know of a better alternative for wiring up configuration keys in a KMP shared module? I have implemented my own solution for now that reads values from
local.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.
Copy code
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)
	}
}
c
I’ve been using gmazzo/gradle-buildconfig-plugin in my projects and have been happy with it. Looks pretty similar to the one you posted, but you might check it out to see if it’s any better for your needs.
c
Oh yeah this is much better, thanks @Casey Brooks