Skip to content

Commit

Permalink
fix(devins): refactor write action to use runReadAction and WriteComm…
Browse files Browse the repository at this point in the history
…andAction for better performance and error handling #143
  • Loading branch information
phodal committed Apr 10, 2024
1 parent 8083b51 commit 8525a0b
Showing 1 changed file with 13 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import cc.unitmesh.devti.language.compiler.error.DEVINS_ERROR
import cc.unitmesh.devti.language.compiler.model.LineInfo
import cc.unitmesh.devti.language.utils.lookupFile
import cc.unitmesh.devti.util.parser.Code
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiManager
Expand All @@ -19,25 +20,24 @@ class WriteInsCommand(val myProject: Project, val argument: String, val content:
val virtualFile = myProject.lookupFile(filename) ?: return "$DEVINS_ERROR: File not found: $argument"
val psiFile = PsiManager.getInstance(myProject).findFile(virtualFile)
?: return "$DEVINS_ERROR: File not found: $argument"
val document = PsiDocumentManager.getInstance(myProject).getDocument(psiFile)
?: return "$DEVINS_ERROR: File not found: $argument"

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

val startLine = range?.startLine ?: 0
val endLine = range?.endLine ?: document.lineCount

try {
val startOffset = document.getLineStartOffset(startLine)
val endOffset = document.getLineEndOffset(endLine - 1)

try {
WriteCommandAction.runWriteCommandAction(myProject) {
document.replaceString(startOffset, endOffset, content)
} catch (e: Exception) {
return@computeAndWait "$DEVINS_ERROR: ${e.message}"
}

return@computeAndWait "Writing to file: $argument"
return "Writing to file: $argument"
} catch (e: Exception) {
return "$DEVINS_ERROR: ${e.message}"
}

return resultMsg
}
}

0 comments on commit 8525a0b

Please sign in to comment.