@@ -56,21 +56,30 @@ class KotlinCodeModifier : CodeModifier {
56
56
return @runReadAction psiClass
57
57
} ? : return @invokeLater
58
58
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
+ }
59
64
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} " )
66
66
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
70
70
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
+ }
74
83
}
75
84
76
85
project.guessProjectDir()?.refresh(true , true )
0 commit comments