-
-
Notifications
You must be signed in to change notification settings - Fork 758
/
KtFiles.kt
46 lines (39 loc) · 1.72 KB
/
KtFiles.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
45
46
package io.github.detekt.psi
import org.jetbrains.kotlin.com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.com.intellij.psi.PsiFile
import org.jetbrains.kotlin.diagnostics.DiagnosticUtils
import org.jetbrains.kotlin.diagnostics.PsiDiagnosticUtils
import org.jetbrains.kotlin.psi.KtFile
import java.nio.file.Path
import kotlin.io.path.Path
private val KOTLIN_GENERIC_SUFFIXES = listOf(".kt", ".kts")
/**
* Removes kotlin specific file name suffixes, e.g. .kt.
* Note, will not remove other possible/known file suffixes like '.java'
*/
fun PsiFile.fileNameWithoutSuffix(multiplatformTargetSuffixes: List<String> = emptyList()): String {
val fileName = this.name
val suffixesToRemove = buildPlatformSpecificSuffixes(multiplatformTargetSuffixes) + KOTLIN_GENERIC_SUFFIXES
for (suffix in suffixesToRemove) {
if (fileName.endsWith(suffix)) {
return fileName.removeSuffix(suffix)
}
}
return fileName
}
fun PsiFile.absolutePath(): Path = Path(virtualFile.path)
// KtFile.virtualFilePath is cached so should be a tiny bit more performant when called repeatedly for the same file.
fun KtFile.absolutePath(): Path = Path(virtualFilePath)
// #3317 If any rule mutates the PsiElement, searching the original PsiElement may throw an exception.
fun getLineAndColumnInPsiFile(file: PsiFile, range: TextRange): PsiDiagnosticUtils.LineAndColumn? {
return if (file.textLength == 0) {
null
} else {
runCatching {
@Suppress("ForbiddenMethodCall")
DiagnosticUtils.getLineAndColumnInPsiFile(file, range)
}.getOrNull()
}
}
private fun buildPlatformSpecificSuffixes(platforms: List<String>): List<String> =
platforms.map { platform -> ".$platform.kt" }