Skip to content

Commit 8525a0b

Browse files
committed
fix(devins): refactor write action to use runReadAction and WriteCommandAction for better performance and error handling #143
1 parent 8083b51 commit 8525a0b

File tree

1 file changed

+13
-13
lines changed
  • exts/devins-lang/src/main/kotlin/cc/unitmesh/devti/language/compiler/exec

1 file changed

+13
-13
lines changed

exts/devins-lang/src/main/kotlin/cc/unitmesh/devti/language/compiler/exec/WriteInsCommand.kt

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ import cc.unitmesh.devti.language.compiler.error.DEVINS_ERROR
44
import cc.unitmesh.devti.language.compiler.model.LineInfo
55
import cc.unitmesh.devti.language.utils.lookupFile
66
import cc.unitmesh.devti.util.parser.Code
7-
import com.intellij.openapi.application.WriteAction
7+
import com.intellij.openapi.application.runReadAction
8+
import com.intellij.openapi.command.WriteCommandAction
89
import com.intellij.openapi.project.Project
910
import com.intellij.psi.PsiDocumentManager
1011
import com.intellij.psi.PsiManager
@@ -19,25 +20,24 @@ class WriteInsCommand(val myProject: Project, val argument: String, val content:
1920
val virtualFile = myProject.lookupFile(filename) ?: return "$DEVINS_ERROR: File not found: $argument"
2021
val psiFile = PsiManager.getInstance(myProject).findFile(virtualFile)
2122
?: return "$DEVINS_ERROR: File not found: $argument"
22-
val document = PsiDocumentManager.getInstance(myProject).getDocument(psiFile)
23-
?: return "$DEVINS_ERROR: File not found: $argument"
2423

25-
val resultMsg = WriteAction.computeAndWait<String, Throwable> {
26-
val startLine = range?.startLine ?: 0
27-
val endLine = range?.endLine ?: document.lineCount
24+
val document = runReadAction {
25+
PsiDocumentManager.getInstance(myProject).getDocument(psiFile)
26+
} ?: return "$DEVINS_ERROR: File not found: $argument"
27+
28+
val startLine = range?.startLine ?: 0
29+
val endLine = range?.endLine ?: document.lineCount
2830

31+
try {
2932
val startOffset = document.getLineStartOffset(startLine)
3033
val endOffset = document.getLineEndOffset(endLine - 1)
31-
32-
try {
34+
WriteCommandAction.runWriteCommandAction(myProject) {
3335
document.replaceString(startOffset, endOffset, content)
34-
} catch (e: Exception) {
35-
return@computeAndWait "$DEVINS_ERROR: ${e.message}"
3636
}
3737

38-
return@computeAndWait "Writing to file: $argument"
38+
return "Writing to file: $argument"
39+
} catch (e: Exception) {
40+
return "$DEVINS_ERROR: ${e.message}"
3941
}
40-
41-
return resultMsg
4242
}
4343
}

0 commit comments

Comments
 (0)