kotlingradlegradle-plugingradle-kotlin-dsl

Build config for developing a Gradle Plugin written in Kotlin


I want to build a Gradle plugin written in Kotlin and publish it to the Gradle Plugin Portal. However, I am not clear about what build config I need to achieve this. There is a lot of confusing information, and strange errors regarding the 'embedded Kotlin' that Gradle uses.

The plugin development guide doesn’t any examples for a Kotlin + build.gradle.kts (only a simple one that uses java-gradle-plugin)

There’s some technical details about the embedded Kotlin, but it’s not clear about explicit requirements, and is more abstract technical implementation than a practical “how to” guide.

Using gradle init (v8.0.2) creates a project that has the Kotlin version manually set, so it might not match the embedded Kotlin version

// generated by `gradle init` command

plugins {
    // Apply the Java Gradle plugin development plugin to add support for developing Gradle plugins
    `java-gradle-plugin`

    // Apply the Kotlin JVM plugin to add support for Kotlin.
    id("org.jetbrains.kotlin.jvm") version "1.8.10"
}

What config should I use to build a Gradle plugin written in Kotlin?


Solution

  • As I understand it, these are the best-practice rules for configuring a Gradle Project that will build a Gradle Plugin written in Kotlin.

    First, note the markers † and ‡

    Gradle Plugin development with Kotlin - best practice rules

    An example build.gradle.kts

    Since most options are configured by the kotlin-dsl plugin, that provides the simplest method for building a Gradle plugin written in Kotlin.

    1. Create a project using a Gradle version that best matches the Gradle versions you want to support, since the Gradle version being used to build the plugin will provide most defaults.

      (While it is possible to create variants of Gradle plugins per Gradle version, this is very complicated and not well supported by the Gradle API)

    2. Create a build.gradle.kts with the following config:

    // build.gradle.kts
    
    plugins {
      `kotlin-dsl`
      id("com.gradle.plugin-publish") version "$gradlePluginPublishVersion"
    }
    
    // Optional: enable stricter validation, to ensure Gradle configuration is correct
    tasks.validatePlugins {
      enableStricterValidation.set(true)
    }
    
    // create the plugin
    // Read more: https://docs.gradle.org/current/userguide/implementing_gradle_plugins.html#plugin-development-plugin
    gradlePlugin {
      plugins {
        create("simplePlugin") {
          id = "org.example.greeting"
          implementationClass = "org.example.GreetingPlugin"
        }
      }
    }