Skip to content
This repository was archived by the owner on Dec 3, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
package org.gradle.kotlin.dsl.integration

import org.gradle.testkit.runner.TaskOutcome.FROM_CACHE
import org.gradle.testkit.runner.TaskOutcome.SUCCESS
import org.gradle.testkit.runner.TaskOutcome.UP_TO_DATE

import org.gradle.kotlin.dsl.fixtures.gradleRunnerFor

import org.hamcrest.CoreMatchers.equalTo
import org.junit.Assert.assertThat
import org.junit.Test


Expand All @@ -25,4 +33,48 @@ class PrecompiledScriptPluginIntegrationTest : AbstractPluginIntegrationTest() {
build("generateScriptPluginAdapters")
build("ktlintC")
}

@Test
fun `precompiled script plugins adapters generation is cached and relocatable`() {

val firstLocation = "first-location"
val secondLocation = "second-location"
val cacheDir = newDir("cache-dir")

withSettingsIn(firstLocation, """
rootProject.name = "test"
$pluginManagementBlock
buildCache {
local<DirectoryBuildCache> {
directory = file("${escapedPathOf(cacheDir)}")
}
}
""")
withBuildScriptIn(firstLocation, """
plugins { `kotlin-dsl` }
repositories { jcenter() }
""")

withFile("$firstLocation/src/main/kotlin/plugin-without-package.gradle.kts")
withFile("$firstLocation/src/main/kotlin/plugins/plugin-with-package.gradle.kts", """
package plugins
""")


val firstDir = existing(firstLocation)
val secondDir = newDir(secondLocation)
firstDir.copyRecursively(secondDir)

val generationTask = ":generateScriptPluginAdapters"

gradleRunnerFor(firstDir, "classes", "--build-cache").build().apply {
assertThat(outcomeOf(generationTask), equalTo(SUCCESS))
}
gradleRunnerFor(firstDir, "classes", "--build-cache").build().apply {
assertThat(outcomeOf(generationTask), equalTo(UP_TO_DATE))
}
gradleRunnerFor(secondDir, "classes", "--build-cache").build().apply {
assertThat(outcomeOf(generationTask), equalTo(FROM_CACHE))
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.gradle.kotlin.dsl.plugins.precompiled

import org.gradle.api.DefaultTask
import org.gradle.api.file.FileTree
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction

import java.io.File


@CacheableTask
open class GenerateScriptPluginAdapters : DefaultTask() {

@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
internal
lateinit var scripts: FileTree

@Internal
internal
lateinit var plugins: List<ScriptPlugin>

@OutputDirectory
var outputDirectory = project.objects.directoryProperty()

@TaskAction
@Suppress("unused")
internal
fun generate() =
outputDirectory.asFile.get().let { outputDir ->
outputDir.mkdirs()
for (scriptPlugin in plugins) {
scriptPlugin.writeScriptPluginAdapterTo(outputDir)
}
}
}


internal
fun ScriptPlugin.writeScriptPluginAdapterTo(outputDir: File) {

val (packageDir, packageDeclaration) =
packageName?.let { packageName ->
packageDir(outputDir, packageName) to "package $packageName"
} ?: outputDir to ""

val outputFile =
packageDir.resolve("$simplePluginAdapterClassName.kt")

outputFile.writeText("""

$packageDeclaration

/**
* Precompiled [$scriptFileName][$compiledScriptTypeName] script plugin.
*
* @see $compiledScriptTypeName
*/
class $simplePluginAdapterClassName : org.gradle.api.Plugin<$targetType> {
override fun apply(target: $targetType) {
try {
Class
.forName("$compiledScriptTypeName")
.getDeclaredConstructor($targetType::class.java)
.newInstance(target)
} catch (e: java.lang.reflect.InvocationTargetException) {
throw e.targetException
}
}
}

""".replaceIndent().trim() + "\n")
}


private
fun packageDir(outputDir: File, packageName: String) =
outputDir.mkdir(packageName.replace('.', '/'))


private
fun File.mkdir(relative: String) =
resolve(relative).apply { mkdirs() }
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@ import org.gradle.plugin.devel.plugins.JavaGradlePluginPlugin
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

import java.io.File


/*
* Exposes `*.gradle.kts` scripts from regular Kotlin source-sets as binary Gradle plugins.
Expand Down Expand Up @@ -149,15 +147,10 @@ fun Project.generatePluginAdaptersFor(scriptPlugins: List<ScriptPlugin>, scriptS
val generatedSourcesDir = layout.buildDirectory.dir("generated-sources/kotlin-dsl-plugins/kotlin")
sourceSets["main"].kotlin.srcDir(generatedSourcesDir)

val generateScriptPluginAdapters by tasks.registering {
inputs.files(scriptSourceFiles)
outputs.dir(generatedSourcesDir)
doLast {
val outputDir = generatedSourcesDir.get().asFile
for (scriptPlugin in scriptPlugins) {
scriptPlugin.writeScriptPluginAdapterTo(outputDir)
}
}
val generateScriptPluginAdapters by tasks.registering(GenerateScriptPluginAdapters::class) {
scripts = scriptSourceFiles
plugins = scriptPlugins
outputDirectory.set(generatedSourcesDir)
}

tasks.named("compileKotlin") {
Expand All @@ -166,53 +159,6 @@ fun Project.generatePluginAdaptersFor(scriptPlugins: List<ScriptPlugin>, scriptS
}


internal
fun ScriptPlugin.writeScriptPluginAdapterTo(outputDir: File) {

val (packageDir, packageDeclaration) =
packageName?.let { packageName ->
packageDir(outputDir, packageName) to "package $packageName"
} ?: outputDir to ""

val outputFile =
packageDir.resolve("$simplePluginAdapterClassName.kt")

outputFile.writeText("""

$packageDeclaration

/**
* Precompiled [$scriptFileName][$compiledScriptTypeName] script plugin.
*
* @see $compiledScriptTypeName
*/
class $simplePluginAdapterClassName : org.gradle.api.Plugin<$targetType> {
override fun apply(target: $targetType) {
try {
Class
.forName("$compiledScriptTypeName")
.getDeclaredConstructor($targetType::class.java)
.newInstance(target)
} catch (e: java.lang.reflect.InvocationTargetException) {
throw e.targetException
}
}
}

""".replaceIndent().trim() + "\n")
}


private
fun packageDir(outputDir: File, packageName: String) =
outputDir.mkdir(packageName.replace('.', '/'))


private
fun File.mkdir(relative: String) =
resolve(relative).apply { mkdirs() }


private
val Project.sourceSets
get() = project.the<SourceSetContainer>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ import org.hamcrest.CoreMatchers.not
import org.junit.Assert.assertThat
import org.junit.Test

import java.io.File


class KotlinDslPluginTest : AbstractPluginTest() {

Expand Down Expand Up @@ -344,10 +342,6 @@ class KotlinDslPluginTest : AbstractPluginTest() {
""")
}

private
fun escapedPathOf(file: File) =
file.absolutePath.replace("\\", "\\\\")

private
fun outputOf(vararg arguments: String) =
buildWithPlugin(*arguments).output
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,10 @@ open class AbstractIntegrationTest {

private
val gradlePropertiesFile by lazy { existing("gradle.properties") }

protected
fun escapedPathOf(file: File) =
file.absolutePath.replace("\\", "\\\\")
}


Expand All @@ -231,7 +235,6 @@ fun containsBuildScanPluginOutput(): Matcher<String> = allOf(
)


private
fun gradleRunnerFor(projectDir: File, vararg arguments: String): GradleRunner = GradleRunner.create().run {
withGradleInstallation(customInstallation())
withProjectDir(projectDir)
Expand Down