Search code examples
gradlegradle-kotlin-dsl

Configure gradle-download-plugin unzip in kotlin


The documentation of the gradle-download-task plugin shows an example of how to download and unzip a file.

task downloadZipFile(type: Download) {
    src 'https://github.com/michel-kraemer/gradle-download-task/archive/refs/tags/5.5.0.zip'
    dest layout.buildDirectory.file('5.5.0.zip')
}

task downloadAndUnzipFile(dependsOn: downloadZipFile, type: Copy) {
    from zipTree(downloadZipFile.dest)
    into layout.buildDirectory
}

As far as I know the first part will look like this in kotlin. Am I right?

task<Download>("downloadZipFile") {
    src("https://services.gradle.org/distributions/gradle-8.6-bin.zip")
    dest(project.layout.buildDirectory.dir("gradle-dists"))
}

The second part, the unzipping of the file, confuses me. Usually I would convert it to kotlin in this way

task<Copy>("downloadAndUnzipFile") {
    from(zipTree(downloadZipFile.dest))
    into(layout.buildDirectory)
}

But what about the dependsOn: downloadZipFile. How is that converted to kotlin dsl?

Maybe someone can tell me how to read the documentation in order to get to the solution.


Solution

  • Since the task function on the Project returns a Task you can use a val

    val downloadZipFile = task<Download>("downloadZipFile") {
        src("https://services.gradle.org/distributions/gradle-8.6-bin.zip")
        dest(project.layout.buildDirectory.dir("gradle-dists"))
    }
    
    task<Copy>("downloadAndUnzipFile") {
        dependsOn(downloadZipFile)
        from(zipTree(downloadZipFile.dest))
        into(layout.buildDirectory)
    }
    

    or you can use the tasks property of the project and lookup the task,

    task<Download>("downloadZipFile") {
        src("https://services.gradle.org/distributions/gradle-8.6-bin.zip")
        dest(project.layout.buildDirectory.dir("gradle-dists"))
    }
    
    task<Copy>("downloadAndUnzipFile") {
        dependsOn(tasks.getByName("downloadZipFile"))
        from(zipTree(downloadZipFile.dest))
        into(layout.buildDirectory)
    }
    

    I will prefer the first solution since you don't rely on variable names rather then strings. I guess the IDEs support a better rename refactoring.