Maddin
Maddin

Reputation: 304

Use version catalog inside precompiled Gradle plugin

I am converting my project with multiple modules to use Precompiled Gradle Plugins. This project also uses Gradle's version catalog (libs.versions.toml) where the documentation explicitly shows how to share it with the build.gradle.kts of the buildSrc directory, which works fine. But unfortunately this does not apply to the plugins themselves. Example:

build-logic/settings.gradle.kts

rootProject.name = "build-logic"

dependencyResolutionManagement {
    versionCatalogs {
        create("libs") {
            from(files("../gradle/libs.versions.toml"))
        }
    }
}

build-logic/build.gradle.kts:

plugins {
    `kotlin-dsl`
    `kotlin-dsl-precompiled-script-plugins`
}

repositories {
    mavenCentral()
}

dependencies {
    implementation(libs.plugins.kotlin.jvm) // works fine
}

build-logic/src/main/kotlin/my-template.gradle.kts

plugins {
    id("org.jetbrains.kotlin.jvm")
}

repositories {
    mavenCentral()
}

dependencies {
    implementation(libs.kotlinx.serialization) // "Unresolved reference: libs"
}

Is it possible to reference "libs" inside my-template.gradle.kts?

Thank you

Upvotes: 4

Views: 2731

Answers (2)

Prochell
Prochell

Reputation: 11

@AhmadMahmoudSaleh You can get rid of error "Unresolved reference to version catalog" by simply enclosing libs in parentheses - (libs). javaClass. This way you will force the compiler to recalculate the type from scratch, rather than bypass the error.

Upvotes: 1

Maddin
Maddin

Reputation: 304

So there is an open issue about this request and a workaround has been found. To use libs inside the precompiled plugin you have to add the following:

build-logic/build.gradle.kts

dependencies {
    implementation(files(libs.javaClass.superclass.protectionDomain.codeSource.location))
}

build-logic/src/main/kotlin/my-template.gradle.kts

import org.gradle.accessors.dm.LibrariesForLibs

val libs = the<LibrariesForLibs>()

dependencies {
    implementation(libs.kotlinx.serialization) // works now!
}

Credit

Upvotes: 5

Related Questions