de/joshuagleitze

KotlinTestCompiler.kt

Download file
package de.joshuagleitze

import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import org.jetbrains.kotlin.config.Services
import org.junit.jupiter.api.Assertions
import java.nio.file.Path

object KotlinTestCompiler {

	/**
	 * Uses the classpath of the running JVM to compile all files in the
	 * provided [directory]. Fails if the compiler outputs any message with a
	 * severity as bad as or worse than the [failOn] severity.
	 */
	 fun assertKotlinCompiles(
	 	directory: Path,
	 	failOn: CompilerMessageSeverity = CompilerMessageSeverity.ERROR
	 ) {
 		val compilerArgs = K2JVMCompilerArguments().apply {
			freeArgs += directory.toString()
			classpath = System.getProperty("java.class.path")
			noStdlib = true
			noReflect = true
		}
		val errorCollector = KotlinTestCompilerLoggingMessageCollector(failOn)
		K2JVMCompiler().exec(errorCollector, Services.EMPTY, compilerArgs)
		if (errorCollector.hasErrors()) {
			Assertions.fail<Void>("Compilation failed: ${errorCollector.errorMessage} (see output above)")
		}
	}
}