Raphael
Raphael

Reputation: 10589

How to access the project version from within Gradle Kotlin DSL expressions?

I have a Gradle 5.3 build script using Kotlin DSL, similar to this:

plugins {
    `kotlin-dsl`
    `java-library`
}

group = "my.company"
version = "1.2.3"

Here, version= resolves to org.gradle.api.Project.setVersion.

Now, farther down, I'd like to do this (porting from a Groovy DSL build file):

tasks.named<Jar>("jar") {
    manifest {
        attributes(
            "Product-Version" to version
        )
    }
}

Here, version resolves to AbstractArchiveTask.getVersion -- not what I want (and also deprecated)!

Figuring I could use Kotlin's qualified this, I tried to use

"${[email protected]}"

instead (NB: the extra string wrapping gets rid of an additional type error), but I get Unresolved reference: @Project now.

How can I access the project version from within a Kotlin DSL expression?

Upvotes: 1

Views: 2815

Answers (1)

Raphael
Raphael

Reputation: 10589

The Gradle script doesn't seem to be nested inside Project but instead delegates accessors to its relevant properties. In fact, the top-level this is of type Build_gradle.

When those accessors are shadowed, variable project can be used; that is,

project.version

solves the issue at hand. As an alternative,

this@Build_gradle.version

is also valid but less readable.

Upvotes: 1

Related Questions