Andy Res
Andy Res

Reputation: 16043

How to retrieve library version in gradle task

Suppose that the project dependencies are declared as follows:

dependencies {
    implementation 'io.mylib:core:1.0.0-SNAPSHOT'
    // ....
}

I would like to have a gradle task that will retrieve the mylib dependency and check the version. If the version of the lib is SNAPSHOT then fail the build.

Something like this:

task checkLibVersion(){
   version = getDependencyVersion("io.mylib:core") // <-- how to retrieve version

   if(version.endsWith("-SNAPSHOT"){
      throw new GradleException("Mylib uses snapshot version")
   }
}

This task would be part of the release pipeline and will fail the job if current version of mylib is snapshot.

Does anyone know how to retrieve the version of a particular dependency from a gradle task?

Upvotes: 3

Views: 533

Answers (1)

Andy Res
Andy Res

Reputation: 16043

OK, it seems this can be done pretty easy if the version number is extracted into an extension property:

In the build.gradle of the root project:

buildscript {
    ext.libVersion = '1.3.21-SNAPHOT'
    // ....
}

task checkLibVersion(){
    def version = "$libVersion"

    if (version.endsWith("-SNAPSHOT")){
        throw new GradleException("Mylib uses SNAPSHOT version!")
    }
}

tasks.whenTaskAdded { task ->
    if (task.name == 'assembleRelease') {
        task.dependsOn checkLibVersion()
    }
}

Upvotes: 2

Related Questions