Load dependency version from server file

I could use some nudges in the right direction again…

I have a server running some software and the version is accessible via a textfile. I can create a task that downloads the file, reads it, does some formatting and I have my version string in a local variable.

val environmentName = project.findProperty("environmentName")?.toString() ?: "dev"
val downloadedDir = layout.buildDirectory.dir("downloaded")
val versionFile = downloadedDir.get().file("${environmentName}.version.txt").asFile
var version = project.findProperty("version")?.toString() ?: "123"

tasks.register<Download>("downloadVersionFile") {
    val environmentName = environmentName
    val downloadUrl = "https://.../version.txt"
    val versionFile = versionFile
    outputs.file(versionFile)
    src(downloadUrl)
    dest(versionFile)
    overwrite(false)
    onlyIfModified(true)
}

tasks.register("setSystemVersion") {
    dependsOn("downloadVersionFile")
    val versionFile = versionFile
    var version = version
    doLast {
        println("Property Version: $version")
        val wholeVersion = versionFile.readText()
        version = wholeVersion.substring(0, wholeVersion.lastIndexOf("."))
        println("System Version: $version")
    }
}

I want to use that version string in my dependencies.

dependencies {
    ...
    implementation("something:something:${version}")
}

I am assuming that I am using the wrong kind of variables and I assume that all I do in tasks comes after the dependencies are set any way. So I know that I am not going in the right direction here any way. :confused:

This is surely not something that I am the first person to do… So help me please! Has anyone done something like this before? Happy for any examples, hint or help! :slight_smile:

You are running into issues because of the Gradle build lifecycle:

  1. Configuration phase - Dependencies are declared
  2. Execution phase - Tasks run

There is no way for that task to run before you declare the dependencies.

Instead, you can fetch the version before the Configuration Phase (think init script/init plugin or an external script and then store the value as a Gradle property / env variable). Alternatively, you can try to get the value during the Configuration Phase using a ValueSource.

1 Like

Or you just use a text resource.

val version = resources.text.fromUri("https://.../version.txt").asString().substringBeforeLast(".")
2 Likes

You put in better words, what I was suspecting! Thanks for the explanation and suggested things to look into for a solution. :slight_smile:

Perfect! Thanks again! :slight_smile: