'Gradle 7.2 Custom Plugin: How to consume a version catalog within the apply(project: Project)?

I have a Gradle 7.2 custom plugin that is working properly. I want to configure it to use the new Gradle Version Catalog for dependency information. I know how to configure and use the version catalog, and have generated a shared jar for our shared dependencies. It is being read by a few other builds without any issues.

However, I cannot seem to find the correct incantation to consume the version catalog jar by the plugin when it is setting dependencies. I keep getting "Extension of type 'VersionCatalogsExtension' does not exist".

Here are two snippets showing what I have done to access the version catalog in the apply method:

    override fun apply(project: Project) {
        val libs = project
           .extensions
           .getByType(VersionCatalogsExtension::class.java)
           .named("libs")
        
        addBuildDependencies(libs)
            .
            .
            .
private fun Project.addBuildDependencies(libs: VersionCatalog) {
    dependencies.apply {
        // BOMs
        add(JavaPlugin.IMPLEMENTATION_CONFIGURATION_NAME, platform(libs.findDependency("arrow.bom").get()))
        add(JavaPlugin.IMPLEMENTATION_CONFIGURATION_NAME, platform(libs.findDependency("detekt.bom").get()))

I'd appreciate any snippets or redirects.

Thanks, Mike



Solution 1:[1]

How are you applying the plugin?

I noticed that if you're trying to do it from an allProjects or subprojects block it doesn't work, it fails with this error:

Extension of type 'VersionCatalogsExtension' does not exist. Currently registered extension types: ...

I assume this the same reason why we can't use libs directly inside those blocks, see this comment for more details.

A solution is to reference the custom plugin directly in the projects that will use it and avoid cross-configuration.

Solution 2:[2]

Please make sure you add this block of code in your settings.gradle.kts file

enableFeaturePreview("VERSION_CATALOGS")
// == Define locations for components ==
dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
    versionCatalogs {
        create("libs") {
            from(files("PATH/libs.versions.toml"))
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex Ciminian
Solution 2 Karthik