Dark theme | Light theme

June 27, 2012

Gradle Goodness: Create Checksums for Archives

If we want to create a checksum for a file in Gradle we can use the ANT checksum task. We assign the file name to the file property of the task. Then the checksum task will generate a file with the checksum in the same directory.

Suppose we have a Java project and want to generate a checksum for the JAR file that is generated with the jar task. We can add an extra action to the jar task with the doLast() method. We pass a closure to this method and in the closure we define the action to create a checksum. The file name of the JAR file is accessible via the archivePath property:

apply plugin: 'java'

archivesBaseName = 'checksum-sample'

jar.doLast { task ->
    ant.checksum file: task.archivePath

When we invoke the jar task we get an extra file in the build/libs directory with the name checksum-sample.jar.MD5. This file contains the checksum for the file checksum-sample.jar.

We can make sure in our Gradle build file that all archive tasks (like Zip, Jar, War) generate a checksum file for the archive file of that task. In the following build file we use the withType() method in the afterEvaluate() method to add the checksum task to all tasks of type Zip. This means also task types that extend the Zip task, like Jar, War and Ear, will get the extra action. We also create extra archives in our project to show we don't have to configure them explicitly with the checksum task, but that Gradle will add the action automatically.

apply plugin: 'java'

archivesBaseName = 'checksum-sample'

task sourceJar(type: Jar) {
    from sourceSets.main.allSource
    classifier = 'sources'

task javadocJar(type: Jar, dependsOn: 'javadoc') {
    from javadoc.destinationDir
    classifier = 'javadoc'

artifacts {
    archives sourceJar, javadocJar

tasks.withType(Zip) { task ->
    task.doLast {
        ant.checksum file: it.archivePath

When we invoke the assemble task and look at the file that are generated we get the following command-line output:

$ gradle assemble
:processResources UP-TO-DATE


Total time: 4.161 secs
$ ls -1 build/libs

Written with Gradle 1.0.