Home > Software design >  Use Kotlin plugins from buildSrc
Use Kotlin plugins from buildSrc

Time:10-25

How can I apply the Kotlin plugins from a buildSrc plugin?

I have a Kotlin project with a build.gradle.kts file containing this:

plugins {
    application
    kotlin("jvm")
    kotlin("plugin.serialization")
}

I want to create a custom plugin in buildSrc:

import org.gradle.api.Plugin
import org.gradle.api.Project
import org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapper

class MyPlugin: Plugin<Project> {
    override fun apply(project: Project) {
        project.pluginManager.apply("org.gradle.application") //This works
        project.pluginManager.apply("¿kotlin(jvm)?") //<-- Here is my doubt
        project.pluginManager.apply("¿kotlin(plugin.serialization)?") //<-- Here is my doubt
    }
}

And use it like this:

plugins {
    id("com.example.myplugin")
}

CodePudding user response:

To apply Gradle plugins from within buildSrc plugins you need to do two things

  1. Add the plugins as dependencies in buildSrc/build.gradle.kts

    Plugins must be added as dependencies using the Maven coordinates, not the plugin ID. The Maven coordinates of plugins can be found in the Gradle plugin portal.

    // buildSrc/build.gradle.kts
    
    plugins {
      `kotlin-dsl`
    }
    
    dependencies {
      // the Maven coordinates of the Kotlin Gradle and Serialization plugins
      implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.20")
      implementation("org.jetbrains.kotlin:kotlin-serialization:1.7.20")
    }
    
  2. apply the plugins, either using the class, or the plugin ID.

    (Note that kotlin("jvm") is a helper function that obscures the actual Gradle plugin ID, which is org.jetbrains.kotlin.jvm)

    class MyPlugin: Plugin<Project> {
      override fun apply(project: Project) {
    
        project.pluginManager.apply("org.jetbrains.kotlin.jvm")
        project.pluginManager.apply("org.jetbrains.kotlin.plugin.serialization")
    
        // the plugin class for the Kotlin JVM & Serialization plugins
        project.plugins.apply(org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapper::class)
        project.plugins.apply(org.jetbrains.kotlinx.serialization.gradle.SerializationGradleSubplugin::class)
      }
    }
    

    (it wasn't easy to find the plugin classes - I had to dig around in the jar to find the plugin marker artifact, e.g. kotlin-serialization-1.7.20-gradle71.jar!/META-INF/gradle-plugins/org.jetbrains.kotlin.plugin.serialization.properties)

You might also like to use precompiled script plugins. They allow for writing buildSrc script plugins that much more similar to standard build.gradle.kts files, and so you can apply plugins in the plugins block.

// buildSrc/src/main/kotlin/conventions/kotlin-jvm.gradle.kts

plugins {
  kotlin("jvm")
}
  • Related