Skip to content

Commit

Permalink
Merge pull request #564 from Sineaggi/add-support-for-configuration-c…
Browse files Browse the repository at this point in the history
…ache

Fix configuration cache issue
  • Loading branch information
srinivasankavitha authored Jun 16, 2023
2 parents 127a6d2 + ef2b804 commit e5185ac
Show file tree
Hide file tree
Showing 5 changed files with 236 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,22 @@ class CodegenPlugin : Plugin<Project> {
val outputDir = generateJavaTaskProvider.map(GenerateJavaTask::getOutputDir)
mainSourceSet.java.srcDirs(project.files(outputDir).builtBy(generateJavaTaskProvider))

project.configurations.create("dgsCodegen")
project.configurations.findByName("dgsCodegen")?.isCanBeResolved = true
val dgsCodegen = project.configurations.create("dgsCodegen")
dgsCodegen.isCanBeResolved = true
generateJavaTaskProvider.configure {
it.dependencies.addAll(
dgsCodegen.incoming.dependencies.map { dependency ->
InternalSimpleDependency(dependency.name, dependency.group)
}
)
if (GradleVersion.current() >= GradleVersion.version("7.4")) {
it.schemaJarArtifacts.addAll(dgsCodegen.incoming.artifacts.resolvedArtifacts.map { it.map { it.id } })
it.schemaJarFiles.addAll(dgsCodegen.incoming.artifacts.resolvedArtifacts.map { it.map { it.file } })
} else {
it.schemaJarArtifacts.addAll(project.provider { dgsCodegen.incoming.artifacts.artifacts.map { it.id } })
it.schemaJarFiles.addAll(project.provider { dgsCodegen.incoming.artifacts.artifacts.map { it.file } })
}
}

project.afterEvaluate { p ->
if (extensions.clientCoreConventionsEnabled.getOrElse(true)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import com.netflix.graphql.dgs.codegen.CodeGen
import com.netflix.graphql.dgs.codegen.CodeGenConfig
import com.netflix.graphql.dgs.codegen.Language
import org.gradle.api.DefaultTask
import org.gradle.api.artifacts.component.ComponentArtifactIdentifier
import org.gradle.api.tasks.*
import org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapper
import java.io.File
Expand Down Expand Up @@ -148,13 +149,23 @@ open class GenerateJavaTask : DefaultTask() {
@Input
var includeClassImports = mutableMapOf<String, MutableMap<String, String>>()

@Input
val dependencies = project.objects.setProperty(InternalSimpleDependency::class.java)

@Input
val schemaJarArtifacts = project.objects.listProperty(ComponentArtifactIdentifier::class.java)

@InputFiles
val schemaJarFiles = project.objects.listProperty(File::class.java)

@TaskAction
fun generate() {
val schemaJarFilesFromDependencies = emptyList<File>().toMutableList()
val dgsCodegenConfig = project.configurations.findByName("dgsCodegen")
dgsCodegenConfig?.incoming?.dependencies?.forEach { dependency ->
dependencies.get().forEach { dependency ->
logger.info("Found DgsCodegen Dependendency: ${dependency.name}")
val found = dgsCodegenConfig.incoming.artifacts.resolvedArtifacts.get().find { it.id.componentIdentifier.displayName.contains(dependency.group + ":" + dependency.name) }
data class InternalArtifactResult(val id: ComponentArtifactIdentifier, val file: File)
val resolvedArtifacts = schemaJarArtifacts.get().zip(schemaJarFiles.get()) { id, file -> InternalArtifactResult(id, file) }
val found = resolvedArtifacts.find { it.id.componentIdentifier.displayName.contains(dependency.group + ":" + dependency.name) }
if (found != null) {
logger.info("Found DgsCodegen Artifact: ${found.id.displayName}")
schemaJarFilesFromDependencies.add(found.file)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
*
* Copyright 2020 Netflix, Inc.
*
* 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 com.netflix.graphql.dgs.codegen.gradle

import java.io.Serializable

data class InternalSimpleDependency(val name: String, val group: String?) : Serializable
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ package com.netflix.graphql.dgs
import org.assertj.core.api.Assertions.assertThat
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome.SUCCESS
import org.gradle.testkit.runner.TaskOutcome.UP_TO_DATE
import org.junit.jupiter.api.io.TempDir
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
Expand Down Expand Up @@ -106,6 +107,7 @@ class CodegenGradlePluginCompatibilityTest {
.withPluginClasspath()
.withDebug(true)
.withArguments(
"--configuration-cache",
"--stacktrace",
"--info",
"generateJava",
Expand All @@ -114,6 +116,24 @@ class CodegenGradlePluginCompatibilityTest {

assertThat(result.task(":generateJava")).extracting { it?.outcome }.isEqualTo(SUCCESS)
assertThat(result.task(":build")).extracting { it?.outcome }.isEqualTo(SUCCESS)
assertThat(result.output).contains("Configuration cache entry stored.")

val rerunResult = GradleRunner.create()
.withGradleVersion(gradleVersion)
.withProjectDir(projectDir)
.withPluginClasspath()
.withDebug(true)
.withArguments(
"--configuration-cache",
"--stacktrace",
"--info",
"generateJava",
"build"
).build()

assertThat(rerunResult.task(":generateJava")).extracting { it?.outcome }.isEqualTo(UP_TO_DATE)
assertThat(rerunResult.task(":build")).extracting { it?.outcome }.isEqualTo(UP_TO_DATE)
assertThat(rerunResult.output).contains("Configuration cache entry reused.")
}

private fun prepareBuildGradleFile(content: String) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
/*
*
* Copyright 2020 Netflix, Inc.
*
* 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 com.netflix.graphql.dgs

import org.assertj.core.api.Assertions.assertThat
import org.gradle.testkit.runner.GradleRunner
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.File
import java.net.URI
import java.nio.file.*
import kotlin.io.path.createDirectories
import kotlin.io.path.writeText

class CodegenGradlePluginConfigurationCacheTest {

@TempDir
lateinit var projectDir: File

@Test
fun `Test if configuration cache can be reused successfully`() {
prepareBuildGraphQLSchema(
"""
type Query {
test: String
}
""".trimMargin()
)

prepareBuildGradleFile(
"""
plugins {
id 'java'
id 'com.netflix.dgs.codegen'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
generateJava {
packageName = 'com.netflix.testproject.graphql'
generateClient = true
}
// Need to disable the core conventions since the artifacts are not yet visible.
codegen.clientCoreConventionsEnabled = false
""".trimMargin()
)

val runner = GradleRunner.create()
.withProjectDir(projectDir)
.withPluginClasspath()
.withDebug(true)
.withArguments(
"--stacktrace",
"--info",
"--configuration-cache",
"generateJava",
"build"
)

runner.build() // First build, warm up cache
val result = runner.build() // Second build, should use cache

assertThat(result.output).contains("Reusing configuration cache.")
}

@Test
fun `Test if configuration cache can be reused successfully with external schemas`() {
prepareSchemaJar(
"""
type Query {
test: String
}
""".trimMargin()
)

prepareBuildGradleFile(
"""
plugins {
id 'java'
id 'com.netflix.dgs.codegen'
}
repositories {
mavenCentral()
}
dependencies {
// other dependencies
dgsCodegen files("$projectDir/schema.jar")
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
generateJava {
packageName = 'com.netflix.testproject.graphql'
generateClient = true
}
// Need to disable the core conventions since the artifacts are not yet visible.
codegen.clientCoreConventionsEnabled = false
""".trimMargin()
)

val runner = GradleRunner.create()
.withProjectDir(projectDir)
.withPluginClasspath()
.withDebug(true)
.withArguments(
"--stacktrace",
"--info",
"--configuration-cache",
"generateJava",
"build"
)

runner.build() // First build, warm up cache
val result = runner.build() // Second build, should use cache

assertThat(result.output).contains("Reusing configuration cache.")
}

private fun prepareSchemaJar(content: String) {
val env = mapOf("create" to "true")
val uri: URI = URI.create("jar:file:$projectDir/schema.jar")
FileSystems.newFileSystem(uri, env).use { zipfs ->
val pathInZipfile: Path = zipfs.getPath("/schema/schema.graphql")
pathInZipfile.parent.createDirectories()
pathInZipfile.writeText(content)
}
}

private fun prepareBuildGradleFile(content: String) {
writeProjectFile("build.gradle", content)
}

private fun prepareBuildGraphQLSchema(content: String) {
writeProjectFile("src/main/resources/schema/schema.graphql", content)
}

private fun writeProjectFile(relativePath: String, content: String) {
val file = File(projectDir, relativePath)
file.parentFile.mkdirs()
file.writeText(content)
}
}

0 comments on commit e5185ac

Please sign in to comment.