Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 36 ยท Projects and Practice

Project: A Custom Gradle Plugin with a Task, Extension and Tests

Build a real Gradle plugin step by step: a changelog task with typed inputs and outputs, an extension, plugin registration, TestKit tests and a runnable Java model of its logic.

Reading about plugins is one thing; writing one makes the ideas stick. In this project you build a plugin called changelog that turns a plain list of commit messages into a release-notes file. It has an extension for settings, a cacheable task with declared inputs and outputs, and tests that run a real build with Gradle TestKit.

Everything in the Gradle files is shown read-only (Gradle cannot run on this website). The core algorithm, grouping messages by type, is Java code you can run and change here. Review writing custom plugins and incremental builds first if needed.

The goal

Given a file commits.txt with conventional commit lines:

TEXT
feat: add coupon codes
fix: round totals correctly
docs: explain the CLI flags
feat: support gift cards

the task generateChangelog writes build/changelog/CHANGELOG.md:

TEXT
# Release 1.2.0

## Features
- add coupon codes
- support gift cards

## Fixes
- round totals correctly

## Other
- explain the CLI flags

Step 1: the algorithm first (runs on the site)

Write and debug the logic as plain code before wiring it into Gradle. Try adding a new prefix such as perf.

Java Changelog generator logic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Step 2: project structure

TEXT
changelog-plugin/
  settings.gradle.kts
  build.gradle.kts
  src/main/kotlin/changelog/ChangelogPlugin.kt
  src/main/kotlin/changelog/ChangelogExtension.kt
  src/main/kotlin/changelog/GenerateChangelogTask.kt
  src/test/kotlin/changelog/ChangelogPluginTest.kt
Kotlin
// build.gradle.kts
plugins {
    `kotlin-dsl`            // brings Kotlin, java-gradle-plugin and the Gradle API
}

repositories { mavenCentral() }

gradlePlugin {
    plugins {
        create("changelog") {
            id = "com.example.changelog"
            implementationClass = "changelog.ChangelogPlugin"
        }
    }
}

dependencies {
    testImplementation(gradleTestKit())
    testImplementation(platform("org.junit:junit-bom:5.11.4"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

tasks.test { useJUnitPlatform() }

Step 3: the extension

Kotlin
// ChangelogExtension.kt
package changelog

import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property

interface ChangelogExtension {
    val commitsFile: RegularFileProperty
    val releaseVersion: Property<String>
}

Interfaces with Property members are enough: Gradle implements them at runtime. Users configure it as

Kotlin
changelog {
    commitsFile = layout.projectDirectory.file("commits.txt")
    releaseVersion = "1.2.0"
}

Step 4: the task

Kotlin
// GenerateChangelogTask.kt
package changelog

import org.gradle.api.DefaultTask
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction

@CacheableTask
abstract class GenerateChangelogTask : DefaultTask() {

    @get:InputFile
    @get:PathSensitive(PathSensitivity.NONE)
    abstract val commitsFile: RegularFileProperty

    @get:Input
    abstract val releaseVersion: Property<String>

    @get:OutputFile
    abstract val outputFile: RegularFileProperty

    @TaskAction
    fun generate() {
        val groups = linkedMapOf("Features" to mutableListOf<String>(),
                                 "Fixes" to mutableListOf(), "Other" to mutableListOf())
        commitsFile.get().asFile.readLines().filter { it.isNotBlank() }.forEach { line ->
            val type = line.substringBefore(':', "").trim()
            val text = line.substringAfter(':', line).trim()
            val group = when (type) { "feat" -> "Features"; "fix" -> "Fixes"; else -> "Other" }
            groups.getValue(group).add(text)
        }
        val body = buildString {
            append("# Release ${releaseVersion.get()}\n")
            groups.forEach { (title, items) ->
                if (items.isNotEmpty()) {
                    append("\n## $title\n")
                    items.forEach { append("- $it\n") }
                }
            }
        }
        outputFile.get().asFile.apply { parentFile.mkdirs(); writeText(body) }
    }
}

Points to notice, which come straight from earlier lessons:

  • every input and the output are declared, so the task is up to date when nothing changes;
  • @CacheableTask plus PathSensitivity.NONE lets the result be restored from the build cache even if the project sits at another path;
  • it does not touch project during execution, so it works with the configuration cache.

Step 5: the plugin

Kotlin
// ChangelogPlugin.kt
package changelog

import org.gradle.api.Plugin
import org.gradle.api.Project

class ChangelogPlugin : Plugin<Project> {
    override fun apply(project: Project) {
        val ext = project.extensions.create("changelog", ChangelogExtension::class.java)
        ext.releaseVersion.convention(project.provider { project.version.toString() })

        project.tasks.register("generateChangelog", GenerateChangelogTask::class.java) {
            group = "documentation"
            description = "Writes release notes from conventional commit messages."
            commitsFile.set(ext.commitsFile)
            releaseVersion.set(ext.releaseVersion)
            outputFile.set(project.layout.buildDirectory.file("changelog/CHANGELOG.md"))
        }
    }
}

Step 6: test with TestKit

Kotlin
// ChangelogPluginTest.kt
package changelog

import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.File

class ChangelogPluginTest {
    @TempDir lateinit var dir: File

    @Test
    fun `groups commits and is up to date on second run`() {
        File(dir, "settings.gradle.kts").writeText("rootProject.name = \"demo\"")
        File(dir, "commits.txt").writeText("feat: a\nfix: b\n")
        File(dir, "build.gradle.kts").writeText("""
            plugins { id("com.example.changelog") }
            version = "1.0.0"
            changelog { commitsFile = layout.projectDirectory.file("commits.txt") }
        """.trimIndent())

        fun run() = GradleRunner.create()
            .withProjectDir(dir).withPluginClasspath()
            .withArguments("generateChangelog").build()

        val first = run()
        assertEquals(TaskOutcome.SUCCESS, first.task(":generateChangelog")!!.outcome)
        val text = File(dir, "build/changelog/CHANGELOG.md").readText()
        assertTrue(text.contains("## Features\n- a"))

        val second = run()
        assertEquals(TaskOutcome.UP_TO_DATE, second.task(":generateChangelog")!!.outcome)
    }
}

The test builds a throwaway project, applies the plugin from the test classpath, runs the task twice and asserts both on the output file and on the up-to-date outcome. That second assertion guards the input/output declarations.

Step 7: use it

Publish it to mavenLocal() or include it as a build (includeBuild("changelog-plugin") in pluginManagement, see composite builds), then in any project:

Kotlin
plugins { id("com.example.changelog") version "1.0.0" }

changelog { commitsFile = file("commits.txt") }

Run ./gradlew generateChangelog and cat build/changelog/CHANGELOG.md.

A runnable up-to-date model

This second stand-in shows the behaviour the TestKit test checks: the same inputs give an "UP-TO-DATE" result.

Java Stand-in: the second run is up to date

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stretch goals

  1. Add an outputFormat property (md or txt) as an @Input and see the task re-run when it changes.
  2. Make the task fail with a clear message if the commits file is empty.
  3. Add a second task verifyChangelog and wire it to check.
  4. Publish the plugin to the Plugin Portal.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the task mark commitsFile with @InputFile and releaseVersion with @Input?

    Declared inputs and outputs enable up-to-date checks and build caching.
  2. 2. What does a TestKit test with GradleRunner do?

    GradleRunner starts an actual build, so you test the plugin the way users use it.
  3. 3. How does the plugin connect the extension to the task?

    commitsFile.set(ext.commitsFile) wires properties lazily, so users may configure the extension after the plugin applies.
  4. 4. Why develop the algorithm as plain code first?

    Separating logic from Gradle API wiring keeps both simple and testable.

Summary

  • A plugin consists of an extension, a typed task and a Plugin<Project> that wires them lazily.
  • Declare inputs and outputs and use @CacheableTask for incremental and cacheable work.
  • Test with TestKit, including the up-to-date outcome of a second run.
  • Register the plugin ID in gradlePlugin {} and consume it from a composite build or repository.

Next: Project: a CI pipeline for a Gradle build