Gradle: run k2js out-of-process if Gradle >= 3.2 is used

This commit is contained in:
Alexey Tsvetkov
2016-11-18 20:05:40 +03:00
parent 38445aca8f
commit f70ba8b18d
3 changed files with 143 additions and 2 deletions
@@ -1,5 +1,7 @@
package org.jetbrains.kotlin.gradle
import org.jetbrains.kotlin.gradle.util.getFileByName
import org.jetbrains.kotlin.gradle.util.modify
import org.junit.Test
class Kotlin2JsGradlePluginIT : BaseGradleIT() {
@@ -71,5 +73,20 @@ class Kotlin2JsGradlePluginIT : BaseGradleIT() {
assertContains("compileKotlin2Js.kotlinOptions.outputFile should be specified.")
}
}
@Test
fun testKotlinJsBuiltins() {
val project = Project("kotlinBuiltins", "3.2")
project.setupWorkingDir()
val buildGradle = project.projectDir.getFileByName("build.gradle")
buildGradle.modify {
it.replace("apply plugin: \"kotlin\"", "apply plugin: \"kotlin2js\"") +
"\ncompileKotlin2Js.kotlinOptions.outputFile = \"out/out.js\""
}
project.build("build") {
assertSuccessful()
}
}
}
@@ -18,6 +18,7 @@ package org.jetbrains.kotlin.gradle.tasks
import org.codehaus.groovy.runtime.MethodClosure
import org.gradle.api.GradleException
import org.gradle.api.Task
import org.gradle.api.file.SourceDirectorySet
import org.gradle.api.logging.Logger
import org.gradle.api.tasks.SourceTask
@@ -50,6 +51,7 @@ import org.jetbrains.kotlin.incremental.multiproject.ArtifactDifferenceRegistryP
import org.jetbrains.kotlin.utils.LibraryUtils
import java.io.File
import java.util.*
import kotlin.concurrent.thread
import kotlin.properties.Delegates
const val ANNOTATIONS_PLUGIN_NAME = "org.jetbrains.kotlin.kapt"
@@ -355,6 +357,8 @@ open class Kotlin2JsCompile() : AbstractKotlinCompile<K2JSCompilerArguments>(),
override val kotlinOptions: KotlinJsOptions
get() = kotlinOptionsImpl
var compilerJarFile: File? = null
@Suppress("unused")
val outputFile: String?
get() = kotlinOptions.outputFile
@@ -375,7 +379,6 @@ open class Kotlin2JsCompile() : AbstractKotlinCompile<K2JSCompilerArguments>(),
}
override fun callCompiler(args: K2JSCompilerArguments, allKotlinSources: List<File>, changedFiles: ChangedFiles) {
val messageCollector = GradleMessageCollector(logger)
logger.debug("Calling compiler")
destinationDir.mkdirs()
args.freeArgs = args.freeArgs + allKotlinSources.map { it.absolutePath }
@@ -385,7 +388,21 @@ open class Kotlin2JsCompile() : AbstractKotlinCompile<K2JSCompilerArguments>(),
}
logger.kotlinDebug("compiling with args ${ArgumentUtils.convertArgumentsToStringList(args)}")
val exitCode = compiler.exec(messageCollector, Services.EMPTY, args)
val gradleVersion = getGradleVersion()
val exitCode = if (gradleVersion == null || gradleVersion >= ParsedGradleVersion(3, 2)) {
// Gradle 3.2 bundles kotlin compiler
// This can cause problems with builtins resolution
// Compiling out of process as a workaround
val argsArray = ArgumentUtils.convertArgumentsToStringList(args).toTypedArray()
val compilerJar = compilerJarFile
?: findKotlinJsCompilerJar(project)
?: throw IllegalStateException("Could not find kotlin compiler jar. As a workaround specify $name.compilerJarFile")
compileOutOfProcess(argsArray, compiler.javaClass.canonicalName, compilerJar)
}
else {
compileInProcess(args)
}
when (exitCode) {
ExitCode.OK -> {
@@ -396,6 +413,50 @@ open class Kotlin2JsCompile() : AbstractKotlinCompile<K2JSCompilerArguments>(),
else -> throw GradleException("Unexpected exit code: $exitCode")
}
}
private fun compileInProcess(args: K2JSCompilerArguments): ExitCode {
val messageCollector = GradleMessageCollector(logger)
val exitCode = compiler.exec(messageCollector, Services.EMPTY, args)
return exitCode
}
}
private fun Task.getGradleVersion(): ParsedGradleVersion? {
val gradleVersion = project.gradle.gradleVersion
val result = ParsedGradleVersion.parse(gradleVersion)
if (result == null) {
project.logger.kotlinDebug("Could not parse gradle version: $gradleVersion")
}
return result
}
private fun compileOutOfProcess(
argsArray: Array<String>,
compilerClassName: String,
compilerJar: File
): ExitCode {
try {
val javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"
val builder = ProcessBuilder(javaBin, "-cp", compilerJar.absolutePath, compilerClassName, *argsArray)
val process = builder.start()
// important to read inputStream, otherwise the process may hang on some systems
val readErrThread = thread {
process.errorStream!!.bufferedReader().forEachLine {
System.err.println(it)
}
}
process.inputStream!!.bufferedReader().forEachLine {
System.out.println(it)
}
readErrThread.join()
val exitCode = process.waitFor()
if (exitCode == 0) return ExitCode.OK else return ExitCode.COMPILATION_ERROR
}
catch (e: Throwable) {
return ExitCode.INTERNAL_ERROR
}
}
internal class GradleMessageCollector(val logger: Logger) : MessageCollector {
@@ -0,0 +1,63 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* 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.jetbrains.kotlin.gradle.tasks
import org.gradle.api.Project
import java.io.File
import java.util.zip.ZipFile
private val K2JVM_COMPILER_CLASS = "org.jetbrains.kotlin.cli.jvm.K2JVMCompiler"
private val K2JS_COMPILER_CLASS = "org.jetbrains.kotlin.cli.js.K2JSCompiler"
internal fun findKotlinJvmCompilerJar(project: Project): File? =
findKotlinCompilerJar(project, K2JVM_COMPILER_CLASS)
internal fun findKotlinJsCompilerJar(project: Project): File? =
findKotlinCompilerJar(project, K2JS_COMPILER_CLASS)
private fun findKotlinCompilerJar(project: Project, compilerClassName: String): File? {
fun Project.classpathJars(): Sequence<File> =
buildscript.configurations.findByName("classpath")?.files?.asSequence() ?: emptySequence()
val entryToFind = compilerClassName.replace(".", "/") + ".class"
val jarFromClasspath = project.classpathJars().firstOrNull { it.hasEntry(entryToFind) }
val compilerJar = jarFromClasspath
return compilerJar
}
private fun File.hasEntry(entryToFind: String): Boolean {
val zip = ZipFile(this)
try {
val enumeration = zip.entries()
while (enumeration.hasMoreElements()) {
val entry = enumeration.nextElement()
if (entry.name.equals(entryToFind, ignoreCase = true)) return true
}
}
catch (e: Exception) {
return false
}
finally {
zip.close()
}
return false
}