I am using kover to analyse the code coverage of my multi-module Android project. Therefore I added some kover configuration in my root build.gradle.kts:
plugins {
alias(libs.plugins.kover)
}
kover {
merge {
...
}
reports {
...
}
}
The configuration is quite large, so I would like to store this code in its own file to keep the build.gradle.kts maintainable. But when extracting the code into a kover-config.gradle.kts
and applying this file in the build.gradle.kts, I get errors that libs
cannot be resolved.
I tried passing the Version Catalog directly like this
apply(from = "kover-config.gradle.kts", to = mapOf("libs" to libs))
I tried passing it via extras:
extra["libs"] = libs
apply(from = "${rootDir}/gradle/scripts/kover-config.gradle.kts")
I tried getting it via the extensions
val libs = extensions.getByType<VersionCatalogsExtension>().named("libs")
But nothing worked. How can this be done?
As of Gradle 8.5 a versionCatalogs
extension is available in Kotlin precompiled script plugins, so you can write
versionCatalogs.named("libs").get()
to access the version catalog named libs
inside your plugin. (Here versionCatalogs
is of type VersionCatalogsExtension
.)
Note this is only available in a precompiled script plugin, whereas you seem to be writing yours in a free-standing Kotlin script file.
For a Kotlin script to be precompiled by Gradle it should sit inside the buildSrc/src/main/kotlin
folder1 and be compiled by the instructions in the buildSrc/build.gradle.kts
build file. Then it can be applied in the plugins block using simply its name, so for a plugin kover-config.gradle.kts
you'd write
plugins {
`kover-config`
}
in the desired main project build file(s), where the backticks are only necessary because hyphens are otherwise illegal characters in Kotlin property names.
I wrote a slighter longer explanation of how to write such a plugin in this answer.
1Or, more generally within the corresponding folder of an included build; but in that case no plugin accessor is generated and the plugin must be applied using the id("...")
syntax