All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.tschuchort.compiletesting.Utils.kt Maven / Gradle / Ivy

package com.tschuchort.compiletesting

import java.io.File
import java.io.FileDescriptor
import java.io.FileOutputStream
import java.io.PrintStream
import java.net.URL
import java.net.URLClassLoader
import java.nio.charset.Charset
import javax.lang.model.SourceVersion
import okio.Buffer

internal fun  MutableCollection.addAll(vararg elems: E) = addAll(elems)

internal fun getJavaHome(): File {
    val path = System.getProperty("java.home")
        ?: System.getenv("JAVA_HOME")
        ?: throw IllegalStateException("no java home found")

    return File(path).also { check(it.isDirectory) }
}

internal val processJdkHome by lazy {
    if(isJdk9OrLater())
        getJavaHome()
    else
        getJavaHome().parentFile
}

/** Checks if the JDK of the host process is version 9 or later */
internal fun isJdk9OrLater(): Boolean
        = SourceVersion.latestSupported().compareTo(SourceVersion.RELEASE_8) > 0

internal fun File.listFilesRecursively(): List = walkTopDown()
    .filter { it.isFile }
    .toList()

internal fun File.hasKotlinFileExtension() = hasFileExtension(listOf("kt", "kts"))

internal fun File.hasJavaFileExtension() = hasFileExtension(listOf("java"))

internal fun File.hasFileExtension(extensions: List)
    = extensions.any{ it.equals(extension, ignoreCase = true) }

internal fun URLClassLoader.addUrl(url: URL) {
    val addUrlMethod = URLClassLoader::class.java.getDeclaredMethod("addURL", URL::class.java)
    addUrlMethod.isAccessible = true
    addUrlMethod.invoke(this, url)
}

internal inline fun  withSystemProperty(key: String, value: String, f: () -> T): T
        = withSystemProperties(mapOf(key to value), f)


internal inline fun  withSystemProperties(properties: Map, f: () -> T): T {
    val previousProperties = mutableMapOf()

    for ((key, value) in properties) {
        previousProperties[key] = System.getProperty(key)
        System.setProperty(key, value)
    }

    try {
        return f()
    } finally {
        for ((key, value) in previousProperties) {
            if (value != null)
                System.setProperty(key, value)
        }
    }
}

internal inline fun  withSystemOut(stream: PrintStream, crossinline f: () -> R): R {
    System.setOut(stream)
    val ret = f()
    System.setOut(PrintStream(FileOutputStream(FileDescriptor.out)))
    return ret
}

internal inline fun  captureSystemOut(crossinline f: () -> R): Pair {
    val systemOutBuffer = Buffer()
    val ret = withSystemOut(PrintStream(systemOutBuffer.outputStream()), f)
    return Pair(ret, systemOutBuffer.readString(Charset.defaultCharset()))
}

internal fun File.existsOrNull(): File? = if (exists()) this else null




© 2015 - 2024 Weber Informatics LLC | Privacy Policy