Skip to Content
Course content

179: Building Custom Gradle Tasks with Kotlin Scripting

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen too many projects clutter their main build.gradle.kts files with hundreds of lines of custom logic. It's a nightmare to maintain and slows down script evaluation. When you need a custom Gradle task that's more complex than a simple doLast block, the professional move is to encapsulate that logic in a proper class. Today, we're going to build a "Release Manifest Generator"—a task that scans our project version and build timestamp and writes them to a file that our app can read at runtime.

Organizing our logic in buildSrc

Instead of jamming this into the root build script, we'll use the buildSrc directory. Gradle treats buildSrc as a separate build that is compiled before your main project, meaning we get full IDE support and type safety for our custom tasks. If you haven't already, create a directory named buildSrc in your root folder, and add a build.gradle.kts file inside it. You don't need much in there; just the kotlin-dsl plugin:

plugins {
    `kotlin-dsl`
}

Now, inside buildSrc/src/main/kotlin, we'll create our task class. I prefer naming these clearly so any developer glancing at the project knows exactly what the task produces.

Defining the ManifestGenerator task

We'll extend DefaultTask. The core of any custom task is the @TaskAction annotation; this tells Gradle, "this is the actual work to be done." I want this task to take a version string and output a manifest.txt file.

import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputFile
import java.io.File
import java.time.Instant

abstract class ManifestGeneratorTask : DefaultTask() {
    @Input
    abstract var projectVersion: String :: class.java // Wait, I'll fix the syntax here
    
    // Let's use a simpler property approach for clarity
    var version: String = "0.0.0"

    @OutputFile
    var outputFile: File = project.file("${project.buildDir}/manifest.txt")

    @TaskAction
    fun generate() {
        val timestamp = Instant.now().toString()
        val content = "Version: $version\nBuildDate: $timestamp"
        outputFile.writeText(content)
        println("Manifest generated at ${outputFile.absolutePath}")
    }
}

Connecting the task to our build pipeline

Now that the class exists in buildSrc, it's available in our main build.gradle.kts just like any built-in Gradle task. We just need to register it and configure the inputs.

tasks.register<ManifestGeneratorTask>("generateReleaseManifest") {
    version = project.version.toString()
    // The outputFile is already defaulted in the class, but we could override it here
}

If you run ./gradlew generateReleaseManifest, it works. It creates the file, the content is correct, and we're happy. Or so I thought.

Fixing the "Always-Running" Task Bug

Here is where I usually trip up when I'm rushing. I ran the task twice in a row. The second time, Gradle told me :generateReleaseManifest UP-TO-DATE. Wait—actually, in my first draft of this code, it wasn't saying that. It was running every single time, even though nothing changed. That's a huge red flag in Gradle.

The problem? I used a plain var for the version and didn't properly annotate the inputs for Gradle's incremental build engine. If Gradle doesn't know exactly what the inputs (the version string) and outputs (the manifest file) are, it can't determine if the task is "up-to-date." It just assumes the work needs to be redone.

I need to use Gradle's Property API. This is the modern way to handle task inputs because it allows for lazy evaluation. Let's refactor the task in buildSrc:

import org.gradle.api.DefaultTask
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import java.time.Instant

abstract class ManifestGeneratorTask : DefaultTask() {
    @get:Input
    abstract val version: Property<String>

    @get:OutputFile
    abstract val outputFile: RegularFileProperty

    @TaskAction
    fun generate() {
        val timestamp = Instant.now().toString()
        val content = "Version: ${version.get()}\nBuildDate: $timestamp"
        outputFile.get().asFile.writeText(content)
    }
}

And the registration changes slightly to use the set() method:

tasks.register<ManifestGeneratorTask>("generateReleaseManifest") {
    version.set(project.version.toString())
    outputFile.set(project.layout.buildDirectory.file("manifest.txt"))
}

Now, if you run it twice, the second run will be UP-TO-DATE. We've just saved our CI pipeline a few seconds of wasted execution time.




📋 Practical Task

Exercise: Building a Git-Hash Injector Task

To practice what we've learned, create a custom Gradle task in buildSrc called GitHashTask. This task should:

  • Execute a shell command (using project.exec or Runtime.getRuntime().exec()) to retrieve the current git commit hash via git rev-parse --short HEAD.
  • Define a RegularFileProperty as an @OutputFile that writes this hash to a file named git.properties in the build directory.
  • Ensure the task is registered in your main build.gradle.kts and is marked as UP-TO-DATE if the git hash hasn't changed (Hint: you may need to add an @Input that represents the current commit hash to make incremental builds work correctly).
Rating
0 0

There are no comments for now.

to be the first to leave a comment.