-
-
Notifications
You must be signed in to change notification settings - Fork 757
/
KtCompiler.kt
44 lines (37 loc) · 1.61 KB
/
KtCompiler.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package io.github.detekt.parser
import io.github.detekt.psi.absolutePath
import io.github.detekt.psi.lineSeparator
import org.intellij.lang.annotations.Language
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.com.intellij.openapi.util.text.StringUtilRt
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import java.nio.file.Path
import kotlin.io.path.absolute
import kotlin.io.path.isRegularFile
import kotlin.io.path.name
import kotlin.io.path.readText
open class KtCompiler(
protected val environment: KotlinCoreEnvironment = createKotlinCoreEnvironment(printStream = System.err)
) {
protected val psiFileFactory = KtPsiFactory(environment.project, markGenerated = false)
fun compile(path: Path): KtFile {
require(path.isRegularFile()) { "Given path '$path' should be a regular file!" }
return createKtFile(path.readText(), path)
}
fun createKtFile(@Language("kotlin") content: String, path: Path): KtFile {
val psiFile = psiFileFactory.createPhysicalFile(path.name, StringUtilRt.convertLineSeparators(content))
return psiFile.apply {
val normalizedAbsolutePath = path.absolute().normalize()
this.absolutePath = normalizedAbsolutePath
this.lineSeparator = content.determineLineSeparator()
}
}
}
internal fun String.determineLineSeparator(): String {
val i = this.lastIndexOf('\n')
if (i == -1) {
return if (this.lastIndexOf('\r') == -1) System.lineSeparator() else "\r"
}
return if (i != 0 && this[i - 1] == '\r') "\r\n" else "\n"
}