Skip to content

Instantly share code, notes, and snippets.

@gmazzo
Last active August 29, 2022 15:47
Show Gist options
  • Save gmazzo/802c700c528061d93c39fba857f6c37d to your computer and use it in GitHub Desktop.
Save gmazzo/802c700c528061d93c39fba857f6c37d to your computer and use it in GitHub Desktop.
A Gradle task to compute checksums
import org.gradle.api.DefaultTask
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.*
import java.security.MessageDigest
@CacheableTask
abstract class Checksum : DefaultTask() {
@get:Input
abstract val algorithm: Property<String>
@get:InputFile
@get:PathSensitive(PathSensitivity.NONE)
abstract val file: RegularFileProperty
@get:Input
@get:Optional
abstract val expectedChecksum: Property<String>
@get:Internal // represented by `checksumFile`
abstract val checksumDirectory: DirectoryProperty
@get:Internal // represented by `checksumFile`
abstract val checksumFileName: Property<String>
@get:OutputFile
abstract val checksumFile: RegularFileProperty
init {
with(project) {
checksumDirectory.convention(layout.dir(provider { temporaryDir }))
checksumFileName.convention(file.asFile.zip(algorithm) { file, algo ->
"${file.name}.${algo.replace("-", "").toLowerCase()}"
})
checksumFile.convention(checksumDirectory.zip(checksumFileName) { dir, file -> dir.file(file) })
}
}
@TaskAction
fun compute() = with(MessageDigest.getInstance(algorithm.get())) {
val file = file.asFile.get()
val checksum = file.inputStream().use {
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var bytes = it.read(buffer)
while (bytes >= 0) {
update(buffer, 0, bytes)
bytes = it.read(buffer)
}
digest().joinToString(separator = "", transform = "%02x"::format)
}
checksumFile.asFile.get().writeText(checksum)
expectedChecksum.orNull?.let { expected ->
check(expected == checksum) {
"""
Verification of '$file' has failed, '$algorithm' checksum does not match:
Expected: $expected
Actual: $checksum
""".trimIndent()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment