-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
179: Building Custom Gradle Tasks with Kotlin Scripting
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.execorRuntime.getRuntime().exec()) to retrieve the current git commit hash viagit rev-parse --short HEAD. - Define a
RegularFilePropertyas an@OutputFilethat writes this hash to a file namedgit.propertiesin the build directory. - Ensure the task is registered in your main
build.gradle.ktsand is marked asUP-TO-DATEif the git hash hasn't changed (Hint: you may need to add an@Inputthat represents the current commit hash to make incremental builds work correctly).
There are no comments for now.