Skip to content

Commit 501fccc

Browse files
committed
fix: fix kotlin code modifier issue
1 parent 96b13cb commit 501fccc

File tree

1 file changed

+21
-12
lines changed

1 file changed

+21
-12
lines changed

kotlin/src/main/kotlin/cc/unitmesh/kotlin/provider/KotlinCodeModifier.kt

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -56,21 +56,30 @@ class KotlinCodeModifier : CodeModifier {
5656
return@runReadAction psiClass
5757
} ?: return@invokeLater
5858

59+
try {
60+
val newTestMethod = KtPsiFactory(project).createFunction(code)
61+
if (rootElement.findMethodsByName(newTestMethod.name, false).isNotEmpty()) {
62+
log.error("Method already exists in the class: ${newTestMethod.name}")
63+
}
5964

60-
val newTestMethod = KtPsiFactory(project).createFunction(code)
61-
if (rootElement.findMethodsByName(newTestMethod.name, false).isNotEmpty()) {
62-
log.error("Method already exists in the class: ${newTestMethod.name}")
63-
}
64-
65-
log.info("newTestMethod: ${newTestMethod.text}")
65+
log.info("newTestMethod: ${newTestMethod.text}")
6666

67-
WriteCommandAction.runWriteCommandAction(project) {
68-
val lastMethod = rootElement.methods.lastOrNull()
69-
val lastMethodEndOffset = lastMethod?.textRange?.endOffset ?: 0
67+
WriteCommandAction.runWriteCommandAction(project) {
68+
val lastMethod = rootElement.methods.lastOrNull()
69+
val lastMethodEndOffset = lastMethod?.textRange?.endOffset ?: 0
7070

71-
val document = PsiDocumentManager.getInstance(project).getDocument(rootElement.containingFile)
72-
document?.insertString(lastMethodEndOffset, "\n ")
73-
document?.insertString(lastMethodEndOffset, newTestMethod.text)
71+
val document = PsiDocumentManager.getInstance(project).getDocument(rootElement.containingFile)
72+
document?.insertString(lastMethodEndOffset, "\n ")
73+
document?.insertString(lastMethodEndOffset, newTestMethod.text)
74+
}
75+
} catch (e: Exception) {
76+
log.warn("Failed to insert method: $code", e)
77+
// append to the end of the file
78+
WriteCommandAction.runWriteCommandAction(project) {
79+
val document = PsiDocumentManager.getInstance(project).getDocument(rootElement.containingFile)!!
80+
document?.insertString(document.textLength, "\n ")
81+
document?.insertString(document.textLength, code)
82+
}
7483
}
7584

7685
project.guessProjectDir()?.refresh(true, true)

0 commit comments

Comments
 (0)