How can I apply a plugin to itself using Kotlin DSL? - kotlin

We have an existing plugin project which configures various things (including static analysis), where we want to apply the plugin to the project itself.
The way this currently works for plugins written in Java is, you add the Java src dir to the buildSrc project, and then classes built there can be used in the main project. So I'm trying to get the same thing working for plugins written as Kotlin scripts.
But when I try to build it, compiling buildSrc fails with:
e: C:\Users\Trejkaz\Documents\test\self-applying-gradle-plugin\src\main\kotlin\example.common.gradle.kts: (1, 1): Unresolved reference: allprojects
> Task :buildSrc:compileKotlin FAILED
What's missing in order to make this work?
Further investigation:
If I put a copy of the files in buildSrc/src/main/kotlin, that works.
If I put a copy of the files in buildSrc/src/main/kotlin2 and use srcDirs to set that directory, that fails too. So it really looks like something isn't letting me relocate sources at all.
I pushed a repo to play with this here but what follows is the contents of the build scripts in case it's ever deleted.
The main build.gradle.kts:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
`java-gradle-plugin`
`kotlin-dsl`
// Matching version in Gradle
kotlin("jvm") version "1.5.31"
}
apply(from = "common-build.gradle.kts")
apply(plugin = "example.common") // 👈 trying to apply the compiled plugin here
group = "org.example"
version = "1.0-SNAPSHOT"
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "11"
}
In buildSrc/build.gradle.kts, we have this - note that it adds a source dir for the sources in the main directory:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
`java-gradle-plugin`
`kotlin-dsl`
// Matching version in Gradle
kotlin("jvm") version "1.5.31"
}
apply(from = "../common-build.gradle.kts")
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "11"
}
kotlin {
sourceSets["main"].kotlin.srcDir("../src/main/kotlin")
}
common-build.gradle.kts has everything common to both build scripts which we've figured out how to move to a common location (notably, the KotlinCompile isn't there, later I'll figure out why I can't move that as well):
repositories {
mavenCentral()
}
dependencies {
// Needed to compile Kotlin stuff but not added by the plugin for some reason
"implementation"("org.jetbrains.kotlin:kotlin-scripting-jvm")
}
The plugin script, src/main/kotlin/example.common.gradle.kts, contains:
allprojects {
// Configure something
}

This turns out to be a bug in Gradle's kotlin-dsl plugin.
The workaround is to add the source dirs before applying the plugin.
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
`java-gradle-plugin`
`kotlin-dsl` apply false
// Matching version in Gradle
kotlin("jvm") version "1.5.31"
}
apply(from = "../common-build.gradle.kts")
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "11"
}
kotlin {
sourceSets["main"].kotlin.srcDir("../src/main/kotlin")
}
// Workaround for https://github.com/gradle/gradle/issues/21052 -
// apply kotlin-dsl plugin last, because it erroneously fetches source dirs eagerly.
apply(plugin = "org.gradle.kotlin.kotlin-dsl")

Related

"Could not find method wrapper()" in build.gradle file generated by openapi-generator kotlin client

I have a simple spring boot project using the kotlin gradle dsl. I want to generate an OpenApi client using the openapi client generator gradle Plugin. I have successfully done so, using this configuration. Until now, this was a single project build. But when i try to include it, i get an error message "Could not find method wrapper()".
This is how i generated the client and added it's file into my source sets:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "3.0.2"
id("io.spring.dependency-management") version "1.1.0"
kotlin("jvm") version "1.7.22"
kotlin("plugin.spring") version "1.7.22"
id("org.openapi.generator") version "6.3.0"
}
// other dependencies
openApiGenerate {
generatorName.set("kotlin")
inputSpec.set("src/main/openapi/my-api.yml")
outputDir.set("$buildDir/generated/my-api")
packageName.set("com.myapi")
}
kotlin.sourceSets["main"].kotlin.srcDir("$buildDir/generated/my-api/src/main/kotlin")
Now i want to use this generated client in my project. It comes with it's own build.gradle (in groovy) which loads the necessary dependencies etc.
I have modified my settings.gradle.kts file accordingly:
rootProject.name = "myapp"
include("build:generated:my-api")
When i reload gradle, i get the follwing error:
> Could not find method wrapper() for arguments [build_gdswinwcvulw9afq79kj4v6h$_run_closure1#582f32f7] on project ':build:generated:my-api' of type org.gradle.api.Project.
This is due to the build.gradle file generated by the generator looking like this:
group 'org.openapitools'
version '1.0.0'
wrapper {
gradleVersion = '7.5'
distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip"
}
buildscript {
ext.kotlin_version = '1.7.21'
repositories {
maven { url "https://repo1.maven.org/maven2" }
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'kotlin'
apply plugin: 'maven-publish'
repositories {
maven { url "https://repo1.maven.org/maven2" }
}
test {
useJUnitPlatform()
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
implementation "com.squareup.moshi:moshi-kotlin:1.13.0"
implementation "com.squareup.moshi:moshi-adapters:1.13.0"
implementation "com.squareup.okhttp3:okhttp:4.10.0"
testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2"
}
I am using Gradle 7.6 and i am a bit out of ideas here since i am pretty new to Gradle.

Kotlin Gradle include runtime when building jar

I'm trying to include the kotlin runtime when building my jar with gradle. I cannot find an update to date thread anywhere online that shows how to do this.
Currently I have tried the following
plugins {
kotlin("jvm") version "1.5.10"
}
repositories {
mavenCentral()
}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
freeCompilerArgs = freeCompilerArgs + "-include-runtime"
jvmTarget = "16"
}
}
This builds the jar fine but doesn't include the runtime like I would expect. How can I configure gradle to do this?
You can use the shadowJar plugin. Add
id("com.github.johnrengelman.shadow") version "7.0.0"
To your plugins, then run ./gradlew shadowJar to create a jar file in build/lib containing the kotlin runtime as well as any of your runtime dependencies

Apply local jar-plugin without using maven

I'd like to load my custom plugin from a local jar. The jar file compiles fine and when I check it, the manifest and the plugin class are there.
gradlePlugin {
plugins {
create("asdf") { // <-- I really call it "asdf" in the kts script
id = "asdf"
implementationClass = "pluginTest.TestPlugin"
version = "1.4.0"
}
}
}
The plugin doesn't do anything useful yet as it should be a proof-of-concept to make sure it actually works at all:
class TestPlugin : Plugin<Project> {
override fun apply(project: Project) {
println("Hallo TestPlugin!")
}
}
I then try to use it like this in another project:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath(files("..\\..\\path\\to\\pluginTest.jar"))
}
}
plugins {
id("asdf") version "1.4.0"
}
but it keeps telling me that:
Plugin [id: 'asdf', version: '1.4.0'] was not found in any of the following sources:
What am I missing here? I use Gradle v6.5.
When you have the plugin jar on the classpath, you can't have a version number in the plugin application. I guess this is because you can't have multiple jars with different versions on the classpath in the first place, so specifying a version here doesn't make any sense (except perhaps to validate that you are using the correct one). This won't fix the problem, but it is a start.
To be honest, I don't know why your approach still won't work. The buildscript block is supposed to set up dependencies for that particular script, and that should make the plugin visible to it. It doesn't for some reason.
Perhaps this is a bug or perhaps this is just an undocumented limitation on the use of the plugin {} block. Maybe you could ask over at the Gradle forums or create an issue for it. However, there are workarounds that don't involve publishing to a (local) Maven repository, which I agree can be a bit annoying.
If you use "apply from" instead of "plugins {}", it works. For some reason, the former can see the buildscript classpath whereas the latter can't:
// build.gradle (Groovy DSL)
buildscript {
dependencies {
classpath(files("..\\..\\path\\to\\pluginTest.jar"))
}
}
apply from: "asdf"
Alternatively, move the buildscript plugin from the build.gradle file to the settings.gradle file. This makes is available to the entire build classpath and will make it work with the plugin block:
// settings.gradle (Groovy DSL):
buildscript {
dependencies {
classpath(files("..\\..\\path\\to\\pluginTest.jar"))
}
}
// build.gradle (Groovy DSL)
plugins {
id("asdf")
}
Lastly, just in case you haven't considered it already, you may be able to add the plugin as a composite build. This will create a source dependency to the plugin and has the advantage that transitive dependencies will be carried over (the ones you put in the plugin's own dependency block) and that it will be built automatically if not up-to-date. I use this approach for integration testing my plugins and also sometimes to apply them to my other real projects to test them in a bigger setting before publishing new versions.
Do that with either:
// settings.gradle (Groovy DSL):
includeBuild("..\\..\\path\\to\\plugin")
// build.gradle (Groovy DSL):
plugins {
id("asdf")
}
Or without hard-coding it in the build (so you can dynamically switch between local and published versions):
// build.gradle (Groovy DSL):
plugins {
id("asdf") version "1.4.0" // Version is optional (will be ignored when the command line switch below)
}
// Run with:
./gradlew --include-build "..\\..\\path\\to\\plugin" build
With #BjørnVester's answer I figured it out!
You need to put the buildscript in settings.gradle.kts as it doesn't get executed in the build.gradle.kts even when placed before plugins.
buildscript {
repositories {
flatDir {
dirs("..\\reusable-kotlin\\build\\libs") // <-- folder with jars
}
}
dependencies {
classpath("com.hedev.kotlin:reusable-kotlin:1.4.0")
}
}
But there's a catch! You must use the file-name of the jar in the classpath's name identifier that goes like this:
group:file-name:version
The file gradle will look for will be file-name-version.jar or file-name.jar which you'll see in the error message if you make a mistake (I added the _ on purpose to trigger the error):
Could not resolve all artifacts for configuration 'classpath'.
Could not find com.hedev.kotlin:reusable-kotlin_:1.4.0. Searched in the following locations:
- file:/C:/some/path/reusable-kotlin/build/libs/reusable-kotlin_-1.4.0.jar
- file:/C:/some/path/reusable-kotlin/build/libs/reusable-kotlin_.jar
In order for this to work I also had to add the group property to the plugin itself:
gradlePlugin {
plugins {
create("asdf") {
id = "asdf"
implementationClass = "com.hedev.kotlin.gradle.TestPlugin"
version = "1.4.0"
group = "com.hedev.kotlin"
}
}
}
Finally you can apply it in build.gradle.kts with (no version here):
plugins {
id("asdf")
}

Applying org.jetbrains.kotlin.jvm within custom Gradle plugin not working

I'm writing a custom Gradle plugin using Kotlin. The goal is to apply and configure certain plugins within this custom plugin. Consumers should only need to apply the custom plugin and be all set.
The problem:
I want to apply these two kotlin plugins (and other plugins) in the custom plugin (which can be applied like this normally in a Gradle build script):
kotlin("jvm") version "1.4.10"
kotlin("plugin.spring") version "1.4.10"
But when applying them from within my own plugin a couple of things goes wrong.
The jar task is not found. I get this complaint in the project consuming my plugin.
The contents of the dependencies section, e.g api, implementation etc are also causing errors, like if Gradle doesn't understand what they are.
I can, in the consuming project however, simply add the line below to the build script to get the jar task back, and make dependencies work again:
kotlin("jvm") version "1.4.10"
I also wrote a sort of debug function in the consuming Gradle build, just to see what plugins are applied. They all print true when I apply only my own plugin (or add kotlin-jvm to the script manually). Which seems to me like my own plugin is doing its job.
open class GreetingTask : DefaultTask() {
#TaskAction
fun greet() {
println("hello from GreetingTask")
println(project.pluginManager.hasPlugin("org.springframework.boot"))
println(project.pluginManager.hasPlugin("io.spring.dependency-management"))
println(project.pluginManager.hasPlugin("com.github.ben-manes.versions"))
println(project.pluginManager.hasPlugin("org.jetbrains.kotlin.jvm"))
println(project.pluginManager.hasPlugin("org.jetbrains.kotlin.plugin.spring"))
println(project.pluginManager.hasPlugin("java"))
}
}
My apply method so far in my plugin:
override fun apply(project: Project) {
configureRepositories(project)
configureTesting(project)
configureJava(project)
configureSpringBoot(project)
configureSpringDependencyManagement(project)
configureKotlin(project)
configureVersions(project)
configurePublishing(project)
}
And for setting up Kotlin:
private fun configureKotlin(project: Project) {
project.pluginManager.apply("org.jetbrains.kotlin.jvm")
project.pluginManager.apply("org.jetbrains.kotlin.plugin.spring")
project.tasks.withType(KotlinCompile::class.java).configureEach { task ->
task.kotlinOptions.freeCompilerArgs = listOf("-Xjsr305=strict")
task.kotlinOptions.jvmTarget = "11"
}
}
All the other configureXYZ seems to work out fine.
I solved it. The problem was how I applied the plugin.
This does NOT work:
build.gradle.kts
buildscript {
repositories {
mavenLocal()
gradlePluginPortal()
}
dependencies {
classpath("com.praqma:demo:1.0.0")
}
}
apply(plugin = "com.praqma.demo.DemoPlugin")
This does work:
settings.gradle.kts
pluginManagement {
repositories {
mavenLocal()
gradlePluginPortal()
}
}
build.gradle.kts
plugins {
id("gradle.demoPlugin") version "0.0.1-SNAPSHOT"
}

How to set up Kotlin PSI for IntelliJ IDEA Gradle Plugin?

I'm building a Plugin for the IntelliJ IDE to manipulate Kotlin files in a project. I've been able to write a bunch of tests to take a Kotlin file and generate a new file based on its contents. When I run this plugin in the IDE I'm unable to detect files as Kotlin files. When looking at the debugger my file says that it is a KtFile from the org.jetbrains.kotlin.psi library. But if I try to cast it to a KtFile I get an error:
java.lang.ClassCastException: org.jetbrains.kotlin.psi.KtFile cannot be cast to org.jetbrains.kotlin.psi.KtFile
So apparently the library version is off between runtime and compile time. What do I have to do to configure my plugin to use the correct Kotlin PSI at plugin runtime?
My plugin.xml looks like this:
<idea-plugin>
<id>...</id>
<name>...</name>
<vendor email="..." url="...">...</vendor>
<description><...</description>
<depends>com.intellij.modules.all</depends>
<depends>org.jetbrains.kotlin</depends>
<actions>...</actions>
</idea-plugin>
My build.gradle.kts looks like:
plugins {
id("org.jetbrains.intellij") version "0.4.16"
kotlin("jvm") version "1.3.61"
}
group = "..."
version = "..."
repositories {
mavenCentral()
}
dependencies {
implementation(kotlin("stdlib-jdk8"))
implementation(kotlin("compiler-embeddable", "1.3.61"))
implementation(kotlin("gradle-plugin", "1.3.61"))
testImplementation(group = "junit", name = "junit", version = "4.12")
}
buildscript {
repositories { mavenCentral() }
dependencies {
classpath(kotlin("compiler-embeddable", "1.3.61"))
classpath(kotlin("gradle-plugin", "1.3.61"))
}
}
intellij {
version = "2019.1.4"
setPlugins("Kotlin")
}
tasks {
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
}
tasks.getByName<org.jetbrains.intellij.tasks.PatchPluginXmlTask>("patchPluginXml") {
changeNotes("...")
}
I already am aware of How to include Kotlin PSI classes (e.g. KtClass) in Intellij IDEA Gradle plugin project written in Kotlin? and How to add Kotlin PSI source files to IDEA Plugin project configuration which is essentially what I want to be answered but haven't gotten anything to fix my issue. Maybe there is some documentation on this issue but it evades my searches.
Your dependencies should include implementation(kotlin("reflect")) and plugin.xml should include <depends>org.jetbrains.kotlin</depends>