Skip to content

Commit f0e2372

Browse files
committed
feat(java): refactor code to use runReadAction and replace string operation
The code has been refactored to use `runReadAction` for better performance when working with PSI elements. The string replacement operation has been changed to ensure that the new code is inserted at the beginning of the document instead of after the last class, which was the previous behavior. This commit also includes the import statements for `PsiElementFactory` and `PsiJavaFile` within the `runReadAction` block to ensure that they are executed during the read action.
1 parent 822324b commit f0e2372

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

java/src/main/kotlin/cc/unitmesh/idea/context/JavaCodeModifier.kt

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,7 @@ import com.intellij.openapi.diagnostic.logger
1111
import com.intellij.openapi.project.Project
1212
import com.intellij.openapi.project.guessProjectDir
1313
import com.intellij.openapi.vfs.VirtualFile
14-
import com.intellij.psi.PsiDocumentManager
15-
import com.intellij.psi.PsiElementFactory
16-
import com.intellij.psi.PsiJavaFile
17-
import com.intellij.psi.PsiManager
18-
import com.intellij.psi.PsiMethod
14+
import com.intellij.psi.*
1915

2016
open class JavaCodeModifier : CodeModifier {
2117
companion object {
@@ -43,19 +39,28 @@ open class JavaCodeModifier : CodeModifier {
4339

4440
val isFullCode = trimCode.startsWith("import") && trimCode.contains("class ")
4541
// check is sourceFile has class
46-
val classes = runReadAction {
47-
val psiJavaFile = lookupFile(project, sourceFile)
48-
psiJavaFile.classes
49-
}
42+
val classes = runReadAction { lookupFile(project, sourceFile).classes }
5043

5144
if (classes.isNotEmpty()) {
52-
// replace the last class with the new test class
5345
val lastClass = classes.last()
5446
val classEndOffset = lastClass.textRange.endOffset
5547

48+
val newCode = try {
49+
runReadAction {
50+
val createFileFromText =
51+
PsiFileFactory.getInstance(project)
52+
.createFileFromText("Test.java", JavaLanguage.INSTANCE, trimCode)
53+
54+
createFileFromText?.text ?: trimCode
55+
}
56+
} catch (e: Throwable) {
57+
log.warn("Failed to create file from text: $trimCode", e)
58+
trimCode
59+
}
60+
5661
WriteCommandAction.runWriteCommandAction(project) {
5762
val document = PsiDocumentManager.getInstance(project).getDocument(lastClass.containingFile)
58-
document?.replaceString(classEndOffset, document.textLength, trimCode)
63+
document?.replaceString(0, classEndOffset, newCode)
5964
}
6065

6166
return true

0 commit comments

Comments
 (0)