Skip to content

Instantly share code, notes, and snippets.

@NikolaDespotoski
Created February 18, 2026 09:52
Show Gist options
  • Select an option

  • Save NikolaDespotoski/c2d3851a61535887e0063412e9674886 to your computer and use it in GitHub Desktop.

Select an option

Save NikolaDespotoski/c2d3851a61535887e0063412e9674886 to your computer and use it in GitHub Desktop.
Merge multiple tomls files into one. Add the merging into .gitignore
/**
* Make sure final lib.versions.toml is added into the .gitignore
*/
dependencyResolutionManagement {
versionCatalogs {
create("libs") {
from(mergedToml())
}
}
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
private fun mergedToml(): ConfigurableFileCollection {
logger.info("Merging toml files...")
val mergedToml = file("../gradle/libs.versions.toml")
val tomlFiles: List<File> = file("../gradle").listFiles().orEmpty().filter {
it.isFile &&
it.extension == "toml" &&
it.name != mergedToml.name
}
mergeTomlFiles(
inputFiles = tomlFiles,
outputFile = mergedToml
)
return files("../gradle/libs.versions.toml")
}
private fun mergeTomlFiles(
inputFiles: Iterable<File>,
outputFile: File
) {
val sections = linkedMapOf<String, LinkedHashMap<String, String>>()
var currentSection: String? = null
inputFiles.forEach { file ->
require(file.exists()) { "TOML file not found: ${file.path}" }
file.forEachLine { raw ->
val line = raw.trim()
when {
line.isEmpty() || line.startsWith("#") -> Unit
line.startsWith("[") && line.endsWith("]") -> {
currentSection = line
sections.putIfAbsent(line, linkedMapOf())
}
currentSection != null && "=" in line -> {
val section = currentSection!!
val (key, value) = line.split("=", limit = 2)
val map = sections.getValue(section)
require(map.putIfAbsent(key.trim(), value.trim()) == null) {
"Duplicate key '${key.trim()}' in section $section"
}
}
}
}
}
outputFile.parentFile.mkdirs()
outputFile.writeText(
buildString {
sections.forEach { (section, entries) ->
appendLine(section)
entries.forEach { (k, v) ->
appendLine("$k = $v")
}
appendLine()
}
}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment